nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/ihooks.py
python
Hooks.load_package
(self, name, filename, file=None)
return imp.load_module(name, file, filename, ("", "", PKG_DIRECTORY))
[]
def load_package(self, name, filename, file=None): return imp.load_module(name, file, filename, ("", "", PKG_DIRECTORY))
[ "def", "load_package", "(", "self", ",", "name", ",", "filename", ",", "file", "=", "None", ")", ":", "return", "imp", ".", "load_module", "(", "name", ",", "file", ",", "filename", ",", "(", "\"\"", ",", "\"\"", ",", "PKG_DIRECTORY", ")", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/ihooks.py#L175-L176
p-christ/Deep-Reinforcement-Learning-Algorithms-with-PyTorch
135d3e2e06bbde2868047d738e3fc2d73fd8cc93
environments/Atari_Environment.py
python
wrap_deepmind
(env, episode_life=True, clip_rewards=True, frame_stack=True, scale=True)
return env
Configure environment for DeepMind-style Atari
Configure environment for DeepMind-style Atari
[ "Configure", "environment", "for", "DeepMind", "-", "style", "Atari" ]
def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=True, scale=True): """Configure environment for DeepMind-style Atari """ if episode_life: env = EpisodicLifeEnv(env) if 'FIRE' in env.unwrapped.get_action_meanings(): env = FireResetEnv(env) env = WarpFrame(env) if scale: env = ScaledFloatFrame(env) if clip_rewards: env = ClipRewardEnv(env) if frame_stack: env = FrameStack(env, 4) return env
[ "def", "wrap_deepmind", "(", "env", ",", "episode_life", "=", "True", ",", "clip_rewards", "=", "True", ",", "frame_stack", "=", "True", ",", "scale", "=", "True", ")", ":", "if", "episode_life", ":", "env", "=", "EpisodicLifeEnv", "(", "env", ")", "if", "'FIRE'", "in", "env", ".", "unwrapped", ".", "get_action_meanings", "(", ")", ":", "env", "=", "FireResetEnv", "(", "env", ")", "env", "=", "WarpFrame", "(", "env", ")", "if", "scale", ":", "env", "=", "ScaledFloatFrame", "(", "env", ")", "if", "clip_rewards", ":", "env", "=", "ClipRewardEnv", "(", "env", ")", "if", "frame_stack", ":", "env", "=", "FrameStack", "(", "env", ",", "4", ")", "return", "env" ]
https://github.com/p-christ/Deep-Reinforcement-Learning-Algorithms-with-PyTorch/blob/135d3e2e06bbde2868047d738e3fc2d73fd8cc93/environments/Atari_Environment.py#L15-L28
FSecureLABS/needle
891b6601262020bb2df98f81f6c0ef2d97ddd82c
needle/core/device/device.py
python
Device.connect
(self)
Connect to the device (both SSH and AGENT).
Connect to the device (both SSH and AGENT).
[ "Connect", "to", "the", "device", "(", "both", "SSH", "and", "AGENT", ")", "." ]
def connect(self): """Connect to the device (both SSH and AGENT).""" # Using USB, setup port forwarding first if self.is_usb(): self._portforward_usb_start() self._portforward_agent_start() # Setup channels self._connect_agent() self.ssh = self._connect_ssh()
[ "def", "connect", "(", "self", ")", ":", "# Using USB, setup port forwarding first", "if", "self", ".", "is_usb", "(", ")", ":", "self", ".", "_portforward_usb_start", "(", ")", "self", ".", "_portforward_agent_start", "(", ")", "# Setup channels", "self", ".", "_connect_agent", "(", ")", "self", ".", "ssh", "=", "self", ".", "_connect_ssh", "(", ")" ]
https://github.com/FSecureLABS/needle/blob/891b6601262020bb2df98f81f6c0ef2d97ddd82c/needle/core/device/device.py#L211-L219
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/maasserver/rpc/regionservice.py
python
Region.update_lease
( self, cluster_uuid, action, mac, ip_family, ip, timestamp, lease_time=None, hostname=None, )
return d
update_lease( cluster_uuid, action, mac, ip_family, ip, timestamp, lease_time, hostname) Implementation of :py:class`~provisioningserver.rpc.region.UpdateLease`.
update_lease( cluster_uuid, action, mac, ip_family, ip, timestamp, lease_time, hostname)
[ "update_lease", "(", "cluster_uuid", "action", "mac", "ip_family", "ip", "timestamp", "lease_time", "hostname", ")" ]
def update_lease( self, cluster_uuid, action, mac, ip_family, ip, timestamp, lease_time=None, hostname=None, ): """update_lease( cluster_uuid, action, mac, ip_family, ip, timestamp, lease_time, hostname) Implementation of :py:class`~provisioningserver.rpc.region.UpdateLease`. """ dbtasks = eventloop.services.getServiceNamed("database-tasks") d = dbtasks.deferTask( leases.update_lease, action, mac, ip_family, ip, timestamp, lease_time, hostname, ) # Catch all errors except the NoSuchCluster failure. We want that to # be sent back to the cluster. def err_NoSuchCluster_passThrough(failure): if failure.check(NoSuchCluster): return failure else: log.err(failure, "Unhandled failure in updating lease.") return {} d.addErrback(err_NoSuchCluster_passThrough) # Wait for the record to be handled. This will cause the cluster to # send one at a time. So they are processed in order no matter which # region recieves the message. return d
[ "def", "update_lease", "(", "self", ",", "cluster_uuid", ",", "action", ",", "mac", ",", "ip_family", ",", "ip", ",", "timestamp", ",", "lease_time", "=", "None", ",", "hostname", "=", "None", ",", ")", ":", "dbtasks", "=", "eventloop", ".", "services", ".", "getServiceNamed", "(", "\"database-tasks\"", ")", "d", "=", "dbtasks", ".", "deferTask", "(", "leases", ".", "update_lease", ",", "action", ",", "mac", ",", "ip_family", ",", "ip", ",", "timestamp", ",", "lease_time", ",", "hostname", ",", ")", "# Catch all errors except the NoSuchCluster failure. We want that to", "# be sent back to the cluster.", "def", "err_NoSuchCluster_passThrough", "(", "failure", ")", ":", "if", "failure", ".", "check", "(", "NoSuchCluster", ")", ":", "return", "failure", "else", ":", "log", ".", "err", "(", "failure", ",", "\"Unhandled failure in updating lease.\"", ")", "return", "{", "}", "d", ".", "addErrback", "(", "err_NoSuchCluster_passThrough", ")", "# Wait for the record to be handled. This will cause the cluster to", "# send one at a time. So they are processed in order no matter which", "# region recieves the message.", "return", "d" ]
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/maasserver/rpc/regionservice.py#L117-L161
hhstore/annotated-py-projects
4f4eca9a3913a19983cae496279a72699c083a0b
flask/flask-0.5/flask/helpers.py
python
_PackageBoundObject.has_static_folder
(self)
return os.path.isdir(os.path.join(self.root_path, 'static'))
判断 App 根目录下,是否存在 'static'文件夹, 存在为真.
判断 App 根目录下,是否存在 'static'文件夹, 存在为真.
[ "判断", "App", "根目录下", "是否存在", "static", "文件夹", "存在为真", "." ]
def has_static_folder(self): """判断 App 根目录下,是否存在 'static'文件夹, 存在为真. """ return os.path.isdir(os.path.join(self.root_path, 'static'))
[ "def", "has_static_folder", "(", "self", ")", ":", "return", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "self", ".", "root_path", ",", "'static'", ")", ")" ]
https://github.com/hhstore/annotated-py-projects/blob/4f4eca9a3913a19983cae496279a72699c083a0b/flask/flask-0.5/flask/helpers.py#L361-L364
ring04h/wyportmap
c4201e2313504e780a7f25238eba2a2d3223e739
sqlalchemy/orm/events.py
python
SessionEvents.after_begin
(self, session, transaction, connection)
Execute after a transaction is begun on a connection :param session: The target :class:`.Session`. :param transaction: The :class:`.SessionTransaction`. :param connection: The :class:`~.engine.Connection` object which will be used for SQL statements. .. seealso:: :meth:`~.SessionEvents.before_commit` :meth:`~.SessionEvents.after_commit` :meth:`~.SessionEvents.after_transaction_create` :meth:`~.SessionEvents.after_transaction_end`
Execute after a transaction is begun on a connection
[ "Execute", "after", "a", "transaction", "is", "begun", "on", "a", "connection" ]
def after_begin(self, session, transaction, connection): """Execute after a transaction is begun on a connection :param session: The target :class:`.Session`. :param transaction: The :class:`.SessionTransaction`. :param connection: The :class:`~.engine.Connection` object which will be used for SQL statements. .. seealso:: :meth:`~.SessionEvents.before_commit` :meth:`~.SessionEvents.after_commit` :meth:`~.SessionEvents.after_transaction_create` :meth:`~.SessionEvents.after_transaction_end` """
[ "def", "after_begin", "(", "self", ",", "session", ",", "transaction", ",", "connection", ")", ":" ]
https://github.com/ring04h/wyportmap/blob/c4201e2313504e780a7f25238eba2a2d3223e739/sqlalchemy/orm/events.py#L1464-L1482
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/http/multipartparser.py
python
MultiPartParser.IE_sanitize
(self, filename)
return filename and filename[filename.rfind("\\")+1:].strip()
Cleanup filename from Internet Explorer full paths.
Cleanup filename from Internet Explorer full paths.
[ "Cleanup", "filename", "from", "Internet", "Explorer", "full", "paths", "." ]
def IE_sanitize(self, filename): """Cleanup filename from Internet Explorer full paths.""" return filename and filename[filename.rfind("\\")+1:].strip()
[ "def", "IE_sanitize", "(", "self", ",", "filename", ")", ":", "return", "filename", "and", "filename", "[", "filename", ".", "rfind", "(", "\"\\\\\"", ")", "+", "1", ":", "]", ".", "strip", "(", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/http/multipartparser.py#L261-L263
scikit-learn-contrib/DESlib
64260ae7c6dd745ef0003cc6322c9f829c807708
deslib/util/aggregation.py
python
average_combiner
(classifier_ensemble, X)
return average_rule(ensemble_proba)
Ensemble combination using the Average rule. Parameters ---------- classifier_ensemble : list of shape = [n_classifiers] Containing the ensemble of classifiers used in the aggregation scheme. X : array of shape (n_samples, n_features) The input data. Returns ------- predicted_label : array of shape (n_samples) The label of each query sample predicted using the majority voting rule
Ensemble combination using the Average rule.
[ "Ensemble", "combination", "using", "the", "Average", "rule", "." ]
def average_combiner(classifier_ensemble, X): """Ensemble combination using the Average rule. Parameters ---------- classifier_ensemble : list of shape = [n_classifiers] Containing the ensemble of classifiers used in the aggregation scheme. X : array of shape (n_samples, n_features) The input data. Returns ------- predicted_label : array of shape (n_samples) The label of each query sample predicted using the majority voting rule """ ensemble_proba = _get_ensemble_probabilities(classifier_ensemble, X) return average_rule(ensemble_proba)
[ "def", "average_combiner", "(", "classifier_ensemble", ",", "X", ")", ":", "ensemble_proba", "=", "_get_ensemble_probabilities", "(", "classifier_ensemble", ",", "X", ")", "return", "average_rule", "(", "ensemble_proba", ")" ]
https://github.com/scikit-learn-contrib/DESlib/blob/64260ae7c6dd745ef0003cc6322c9f829c807708/deslib/util/aggregation.py#L262-L279
graphcore/examples
46d2b7687b829778369fc6328170a7b14761e5c6
code_examples/tensorflow/ssd/bounding_box_utils/bounding_box_utils.py
python
convert_coordinates2
(tensor, start_index, conversion)
return tensor1
A matrix multiplication implementation of `convert_coordinates()`. Supports only conversion between the 'centroids' and 'minmax' formats. This function is marginally slower on average than `convert_coordinates()`, probably because it involves more (unnecessary) arithmetic operations (unnecessary because the two matrices are sparse). For details please refer to the documentation of `convert_coordinates()`.
A matrix multiplication implementation of `convert_coordinates()`. Supports only conversion between the 'centroids' and 'minmax' formats.
[ "A", "matrix", "multiplication", "implementation", "of", "convert_coordinates", "()", ".", "Supports", "only", "conversion", "between", "the", "centroids", "and", "minmax", "formats", "." ]
def convert_coordinates2(tensor, start_index, conversion): """ A matrix multiplication implementation of `convert_coordinates()`. Supports only conversion between the 'centroids' and 'minmax' formats. This function is marginally slower on average than `convert_coordinates()`, probably because it involves more (unnecessary) arithmetic operations (unnecessary because the two matrices are sparse). For details please refer to the documentation of `convert_coordinates()`. """ ind = start_index tensor1 = np.copy(tensor).astype(np.float) if conversion == 'minmax2centroids': M = np.array([[0.5, 0., -1., 0.], [0.5, 0., 1., 0.], [0., 0.5, 0., -1.], [0., 0.5, 0., 1.]]) tensor1[..., ind:ind+4] = np.dot(tensor1[..., ind:ind+4], M) elif conversion == 'centroids2minmax': M = np.array([[1., 1., 0., 0.], [0., 0., 1., 1.], [-0.5, 0.5, 0., 0.], [0., 0., -0.5, 0.5]]) # The multiplicative inverse of the matrix above tensor1[..., ind:ind+4] = np.dot(tensor1[..., ind:ind+4], M) else: raise ValueError("Unexpected conversion value. Supported values are 'minmax2centroids' and 'centroids2minmax'.") return tensor1
[ "def", "convert_coordinates2", "(", "tensor", ",", "start_index", ",", "conversion", ")", ":", "ind", "=", "start_index", "tensor1", "=", "np", ".", "copy", "(", "tensor", ")", ".", "astype", "(", "np", ".", "float", ")", "if", "conversion", "==", "'minmax2centroids'", ":", "M", "=", "np", ".", "array", "(", "[", "[", "0.5", ",", "0.", ",", "-", "1.", ",", "0.", "]", ",", "[", "0.5", ",", "0.", ",", "1.", ",", "0.", "]", ",", "[", "0.", ",", "0.5", ",", "0.", ",", "-", "1.", "]", ",", "[", "0.", ",", "0.5", ",", "0.", ",", "1.", "]", "]", ")", "tensor1", "[", "...", ",", "ind", ":", "ind", "+", "4", "]", "=", "np", ".", "dot", "(", "tensor1", "[", "...", ",", "ind", ":", "ind", "+", "4", "]", ",", "M", ")", "elif", "conversion", "==", "'centroids2minmax'", ":", "M", "=", "np", ".", "array", "(", "[", "[", "1.", ",", "1.", ",", "0.", ",", "0.", "]", ",", "[", "0.", ",", "0.", ",", "1.", ",", "1.", "]", ",", "[", "-", "0.5", ",", "0.5", ",", "0.", ",", "0.", "]", ",", "[", "0.", ",", "0.", ",", "-", "0.5", ",", "0.5", "]", "]", ")", "# The multiplicative inverse of the matrix above", "tensor1", "[", "...", ",", "ind", ":", "ind", "+", "4", "]", "=", "np", ".", "dot", "(", "tensor1", "[", "...", ",", "ind", ":", "ind", "+", "4", "]", ",", "M", ")", "else", ":", "raise", "ValueError", "(", "\"Unexpected conversion value. Supported values are 'minmax2centroids' and 'centroids2minmax'.\"", ")", "return", "tensor1" ]
https://github.com/graphcore/examples/blob/46d2b7687b829778369fc6328170a7b14761e5c6/code_examples/tensorflow/ssd/bounding_box_utils/bounding_box_utils.py#L92-L120
carnal0wnage/weirdAAL
c14e36d7bb82447f38a43da203f4bc29429f4cf4
modules/aws/recon.py
python
module_recon_defaults
()
Recon defaults that every account seems to have minus route53_geolocations (static data) python3 weirdAAL.py -m recon_defaults -t demo
Recon defaults that every account seems to have minus route53_geolocations (static data) python3 weirdAAL.py -m recon_defaults -t demo
[ "Recon", "defaults", "that", "every", "account", "seems", "to", "have", "minus", "route53_geolocations", "(", "static", "data", ")", "python3", "weirdAAL", ".", "py", "-", "m", "recon_defaults", "-", "t", "demo" ]
def module_recon_defaults(): ''' Recon defaults that every account seems to have minus route53_geolocations (static data) python3 weirdAAL.py -m recon_defaults -t demo ''' elasticbeanstalk_describe_applications() elasticbeanstalk_describe_application_versions() elasticbeanstalk_describe_environments() elasticbeanstalk_describe_events() opsworks_describe_stacks() # list_geolocations() # not work looking at, it's static data sts_get_accountid_all()
[ "def", "module_recon_defaults", "(", ")", ":", "elasticbeanstalk_describe_applications", "(", ")", "elasticbeanstalk_describe_application_versions", "(", ")", "elasticbeanstalk_describe_environments", "(", ")", "elasticbeanstalk_describe_events", "(", ")", "opsworks_describe_stacks", "(", ")", "# list_geolocations() # not work looking at, it's static data", "sts_get_accountid_all", "(", ")" ]
https://github.com/carnal0wnage/weirdAAL/blob/c14e36d7bb82447f38a43da203f4bc29429f4cf4/modules/aws/recon.py#L252-L263
openstack/manila
142990edc027e14839d5deaf4954dd6fc88de15e
manila/share/drivers/ganesha/manager.py
python
GaneshaManager.add_export
(self, name, confdict)
Add an export to Ganesha specified by confdict.
Add an export to Ganesha specified by confdict.
[ "Add", "an", "export", "to", "Ganesha", "specified", "by", "confdict", "." ]
def add_export(self, name, confdict): """Add an export to Ganesha specified by confdict.""" xid = confdict["EXPORT"]["Export_Id"] undos = [] _mkindex_called = False try: path = self._write_export(name, confdict) if self.ganesha_rados_store_enable: undos.append(lambda: self._rm_export_rados_object(name)) undos.append(lambda: self._rm_file(path)) else: undos.append(lambda: self._rm_export_file(name)) self._dbus_send_ganesha("AddExport", "string:" + path, "string:EXPORT(Export_Id=%d)" % xid) undos.append(lambda: self._remove_export_dbus(xid)) if self.ganesha_rados_store_enable: # Clean up temp export file used for the DBus call self._rm_file(path) self._add_rados_object_url_to_index(name) else: _mkindex_called = True self._mkindex() except exception.ProcessExecutionError as e: for u in undos: u() if not self.ganesha_rados_store_enable and not _mkindex_called: self._mkindex() raise exception.GaneshaCommandFailure( stdout=e.stdout, stderr=e.stderr, exit_code=e.exit_code, cmd=e.cmd)
[ "def", "add_export", "(", "self", ",", "name", ",", "confdict", ")", ":", "xid", "=", "confdict", "[", "\"EXPORT\"", "]", "[", "\"Export_Id\"", "]", "undos", "=", "[", "]", "_mkindex_called", "=", "False", "try", ":", "path", "=", "self", ".", "_write_export", "(", "name", ",", "confdict", ")", "if", "self", ".", "ganesha_rados_store_enable", ":", "undos", ".", "append", "(", "lambda", ":", "self", ".", "_rm_export_rados_object", "(", "name", ")", ")", "undos", ".", "append", "(", "lambda", ":", "self", ".", "_rm_file", "(", "path", ")", ")", "else", ":", "undos", ".", "append", "(", "lambda", ":", "self", ".", "_rm_export_file", "(", "name", ")", ")", "self", ".", "_dbus_send_ganesha", "(", "\"AddExport\"", ",", "\"string:\"", "+", "path", ",", "\"string:EXPORT(Export_Id=%d)\"", "%", "xid", ")", "undos", ".", "append", "(", "lambda", ":", "self", ".", "_remove_export_dbus", "(", "xid", ")", ")", "if", "self", ".", "ganesha_rados_store_enable", ":", "# Clean up temp export file used for the DBus call", "self", ".", "_rm_file", "(", "path", ")", "self", ".", "_add_rados_object_url_to_index", "(", "name", ")", "else", ":", "_mkindex_called", "=", "True", "self", ".", "_mkindex", "(", ")", "except", "exception", ".", "ProcessExecutionError", "as", "e", ":", "for", "u", "in", "undos", ":", "u", "(", ")", "if", "not", "self", ".", "ganesha_rados_store_enable", "and", "not", "_mkindex_called", ":", "self", ".", "_mkindex", "(", ")", "raise", "exception", ".", "GaneshaCommandFailure", "(", "stdout", "=", "e", ".", "stdout", ",", "stderr", "=", "e", ".", "stderr", ",", "exit_code", "=", "e", ".", "exit_code", ",", "cmd", "=", "e", ".", "cmd", ")" ]
https://github.com/openstack/manila/blob/142990edc027e14839d5deaf4954dd6fc88de15e/manila/share/drivers/ganesha/manager.py#L459-L490
rucio/rucio
6d0d358e04f5431f0b9a98ae40f31af0ddff4833
lib/rucio/api/rse.py
python
get_rse_protocols
(rse, issuer, vo='def')
return rse_module.get_rse_protocols(rse_id)
Returns all matching protocols (including detailed information) for the given RSE. :param rse: The RSE name. :param issuer: The issuer account. :param vo: The VO to act on. :returns: A dict with all supported protocols and their attibutes.
Returns all matching protocols (including detailed information) for the given RSE.
[ "Returns", "all", "matching", "protocols", "(", "including", "detailed", "information", ")", "for", "the", "given", "RSE", "." ]
def get_rse_protocols(rse, issuer, vo='def'): """ Returns all matching protocols (including detailed information) for the given RSE. :param rse: The RSE name. :param issuer: The issuer account. :param vo: The VO to act on. :returns: A dict with all supported protocols and their attibutes. """ rse_id = rse_module.get_rse_id(rse=rse, vo=vo) return rse_module.get_rse_protocols(rse_id)
[ "def", "get_rse_protocols", "(", "rse", ",", "issuer", ",", "vo", "=", "'def'", ")", ":", "rse_id", "=", "rse_module", ".", "get_rse_id", "(", "rse", "=", "rse", ",", "vo", "=", "vo", ")", "return", "rse_module", ".", "get_rse_protocols", "(", "rse_id", ")" ]
https://github.com/rucio/rucio/blob/6d0d358e04f5431f0b9a98ae40f31af0ddff4833/lib/rucio/api/rse.py#L223-L234
mlflow/mlflow
364aca7daf0fcee3ec407ae0b1b16d9cb3085081
mlflow/pytorch/__init__.py
python
save_state_dict
(state_dict, path, **kwargs)
Save a state_dict to a path on the local file system :param state_dict: state_dict to be saved. :param path: Local path where the state_dict is to be saved. :param kwargs: kwargs to pass to ``torch.save``.
Save a state_dict to a path on the local file system
[ "Save", "a", "state_dict", "to", "a", "path", "on", "the", "local", "file", "system" ]
def save_state_dict(state_dict, path, **kwargs): """ Save a state_dict to a path on the local file system :param state_dict: state_dict to be saved. :param path: Local path where the state_dict is to be saved. :param kwargs: kwargs to pass to ``torch.save``. """ import torch # The object type check here aims to prevent a scenario where a user accidentally passees # a model instead of a state_dict and `torch.save` (which accepts both model and state_dict) # successfully completes, leaving the user unaware of the mistake. if not isinstance(state_dict, dict): raise TypeError( "Invalid object type for `state_dict`: {}. Must be an instance of `dict`".format( type(state_dict) ) ) os.makedirs(path, exist_ok=True) state_dict_path = os.path.join(path, _TORCH_STATE_DICT_FILE_NAME) torch.save(state_dict, state_dict_path, **kwargs)
[ "def", "save_state_dict", "(", "state_dict", ",", "path", ",", "*", "*", "kwargs", ")", ":", "import", "torch", "# The object type check here aims to prevent a scenario where a user accidentally passees", "# a model instead of a state_dict and `torch.save` (which accepts both model and state_dict)", "# successfully completes, leaving the user unaware of the mistake.", "if", "not", "isinstance", "(", "state_dict", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"Invalid object type for `state_dict`: {}. Must be an instance of `dict`\"", ".", "format", "(", "type", "(", "state_dict", ")", ")", ")", "os", ".", "makedirs", "(", "path", ",", "exist_ok", "=", "True", ")", "state_dict_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "_TORCH_STATE_DICT_FILE_NAME", ")", "torch", ".", "save", "(", "state_dict", ",", "state_dict_path", ",", "*", "*", "kwargs", ")" ]
https://github.com/mlflow/mlflow/blob/364aca7daf0fcee3ec407ae0b1b16d9cb3085081/mlflow/pytorch/__init__.py#L816-L838
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/xmlrpc/server.py
python
list_public_methods
(obj)
return [member for member in dir(obj) if not member.startswith('_') and callable(getattr(obj, member))]
Returns a list of attribute strings, found in the specified object, which represent callable attributes
Returns a list of attribute strings, found in the specified object, which represent callable attributes
[ "Returns", "a", "list", "of", "attribute", "strings", "found", "in", "the", "specified", "object", "which", "represent", "callable", "attributes" ]
def list_public_methods(obj): """Returns a list of attribute strings, found in the specified object, which represent callable attributes""" return [member for member in dir(obj) if not member.startswith('_') and callable(getattr(obj, member))]
[ "def", "list_public_methods", "(", "obj", ")", ":", "return", "[", "member", "for", "member", "in", "dir", "(", "obj", ")", "if", "not", "member", ".", "startswith", "(", "'_'", ")", "and", "callable", "(", "getattr", "(", "obj", ",", "member", ")", ")", "]" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/xmlrpc/server.py#L146-L152
bikalims/bika.lims
35e4bbdb5a3912cae0b5eb13e51097c8b0486349
bika/lims/browser/sample/partitions.py
python
SamplePartitionsView.__call__
(self)
return super(SamplePartitionsView, self).__call__()
[]
def __call__(self): mtool = getToolByName(self.context, 'portal_membership') checkPermission = mtool.checkPermission if self.context.portal_type == 'AnalysisRequest': self.sample = self.context.getSample() else: self.sample = self.context if checkPermission(AddSamplePartition, self.sample): self.context_actions[_('Add')] = \ {'url': self.sample.absolute_url() + '/createSamplePartition', 'icon': '++resource++bika.lims.images/add.png'} return super(SamplePartitionsView, self).__call__()
[ "def", "__call__", "(", "self", ")", ":", "mtool", "=", "getToolByName", "(", "self", ".", "context", ",", "'portal_membership'", ")", "checkPermission", "=", "mtool", ".", "checkPermission", "if", "self", ".", "context", ".", "portal_type", "==", "'AnalysisRequest'", ":", "self", ".", "sample", "=", "self", ".", "context", ".", "getSample", "(", ")", "else", ":", "self", ".", "sample", "=", "self", ".", "context", "if", "checkPermission", "(", "AddSamplePartition", ",", "self", ".", "sample", ")", ":", "self", ".", "context_actions", "[", "_", "(", "'Add'", ")", "]", "=", "{", "'url'", ":", "self", ".", "sample", ".", "absolute_url", "(", ")", "+", "'/createSamplePartition'", ",", "'icon'", ":", "'++resource++bika.lims.images/add.png'", "}", "return", "super", "(", "SamplePartitionsView", ",", "self", ")", ".", "__call__", "(", ")" ]
https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/browser/sample/partitions.py#L93-L105
facebook/FAI-PEP
632918e8b4025044b67eb24aff57027e84836995
ailab/file_storage/views.py
python
upload
(request)
return JsonResponse(res)
[]
def upload(request): # Handle file upload if request.method == "POST" and "file" in request.FILES: file = request.FILES["file"] model_file = ModelFile(name=str(file), file=file) model_file.save() # Redirect to the document list after POST res = { "status": "success", "path": model_file.file.url, } else: res = {"status": "fail"} return JsonResponse(res)
[ "def", "upload", "(", "request", ")", ":", "# Handle file upload", "if", "request", ".", "method", "==", "\"POST\"", "and", "\"file\"", "in", "request", ".", "FILES", ":", "file", "=", "request", ".", "FILES", "[", "\"file\"", "]", "model_file", "=", "ModelFile", "(", "name", "=", "str", "(", "file", ")", ",", "file", "=", "file", ")", "model_file", ".", "save", "(", ")", "# Redirect to the document list after POST", "res", "=", "{", "\"status\"", ":", "\"success\"", ",", "\"path\"", ":", "model_file", ".", "file", ".", "url", ",", "}", "else", ":", "res", "=", "{", "\"status\"", ":", "\"fail\"", "}", "return", "JsonResponse", "(", "res", ")" ]
https://github.com/facebook/FAI-PEP/blob/632918e8b4025044b67eb24aff57027e84836995/ailab/file_storage/views.py#L11-L27
flaskbb/flaskbb
de13a37fcb713b9c627632210ab9a7bb980d591f
flaskbb/cli/translations.py
python
compile_translation
(is_all, plugin)
Compiles the translations.
Compiles the translations.
[ "Compiles", "the", "translations", "." ]
def compile_translation(is_all, plugin): """Compiles the translations.""" if plugin is not None: validate_plugin(plugin) click.secho("[+] Compiling language files for plugin {}..." .format(plugin), fg="cyan") compile_plugin_translations(plugin) else: click.secho("[+] Compiling language files...", fg="cyan") compile_translations(include_plugins=is_all)
[ "def", "compile_translation", "(", "is_all", ",", "plugin", ")", ":", "if", "plugin", "is", "not", "None", ":", "validate_plugin", "(", "plugin", ")", "click", ".", "secho", "(", "\"[+] Compiling language files for plugin {}...\"", ".", "format", "(", "plugin", ")", ",", "fg", "=", "\"cyan\"", ")", "compile_plugin_translations", "(", "plugin", ")", "else", ":", "click", ".", "secho", "(", "\"[+] Compiling language files...\"", ",", "fg", "=", "\"cyan\"", ")", "compile_translations", "(", "include_plugins", "=", "is_all", ")" ]
https://github.com/flaskbb/flaskbb/blob/de13a37fcb713b9c627632210ab9a7bb980d591f/flaskbb/cli/translations.py#L67-L76
graphbrain/graphbrain
96cb902d9e22d8dc8c2110ff3176b9aafdeba444
graphbrain/patterns.py
python
PatternCounter.count
(self, edge)
[]
def count(self, edge): if not edge.is_atom(): if self._matches_expansions(edge): for pattern in self._edge2patterns(edge): self.patterns[hedge(pattern)] += 1 if self.count_subedges: for subedge in edge: self.count(subedge)
[ "def", "count", "(", "self", ",", "edge", ")", ":", "if", "not", "edge", ".", "is_atom", "(", ")", ":", "if", "self", ".", "_matches_expansions", "(", "edge", ")", ":", "for", "pattern", "in", "self", ".", "_edge2patterns", "(", "edge", ")", ":", "self", ".", "patterns", "[", "hedge", "(", "pattern", ")", "]", "+=", "1", "if", "self", ".", "count_subedges", ":", "for", "subedge", "in", "edge", ":", "self", ".", "count", "(", "subedge", ")" ]
https://github.com/graphbrain/graphbrain/blob/96cb902d9e22d8dc8c2110ff3176b9aafdeba444/graphbrain/patterns.py#L118-L125
uccser/cs-unplugged
f83593f872792e71a9fab3f2d77a0f489205926b
csunplugged/config/views.py
python
get_release_and_commit
(request)
return JsonResponse({ "VERSION_NUMBER": __version__, "GIT_SHA": settings.GIT_SHA, })
Return JSON containing the version number and Git commit hash.
Return JSON containing the version number and Git commit hash.
[ "Return", "JSON", "containing", "the", "version", "number", "and", "Git", "commit", "hash", "." ]
def get_release_and_commit(request): """Return JSON containing the version number and Git commit hash.""" return JsonResponse({ "VERSION_NUMBER": __version__, "GIT_SHA": settings.GIT_SHA, })
[ "def", "get_release_and_commit", "(", "request", ")", ":", "return", "JsonResponse", "(", "{", "\"VERSION_NUMBER\"", ":", "__version__", ",", "\"GIT_SHA\"", ":", "settings", ".", "GIT_SHA", ",", "}", ")" ]
https://github.com/uccser/cs-unplugged/blob/f83593f872792e71a9fab3f2d77a0f489205926b/csunplugged/config/views.py#L11-L16
elastic/elasticsearch-py
6ef1adfa3c840a84afda7369cd8e43ae7dc45cdb
elasticsearch/_sync/client/security.py
python
SecurityClient.invalidate_token
( self, *, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, realm_name: Optional[Any] = None, refresh_token: Optional[str] = None, token: Optional[str] = None, username: Optional[Any] = None, )
return self._perform_request("DELETE", __target, headers=__headers, body=__body)
Invalidates one or more access tokens or refresh tokens. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-token.html>`_ :param realm_name: :param refresh_token: :param token: :param username:
Invalidates one or more access tokens or refresh tokens.
[ "Invalidates", "one", "or", "more", "access", "tokens", "or", "refresh", "tokens", "." ]
def invalidate_token( self, *, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, realm_name: Optional[Any] = None, refresh_token: Optional[str] = None, token: Optional[str] = None, username: Optional[Any] = None, ) -> ObjectApiResponse[Any]: """ Invalidates one or more access tokens or refresh tokens. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-token.html>`_ :param realm_name: :param refresh_token: :param token: :param username: """ __path = "/_security/oauth2/token" __query: Dict[str, Any] = {} __body: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if human is not None: __query["human"] = human if pretty is not None: __query["pretty"] = pretty if realm_name is not None: __body["realm_name"] = realm_name if refresh_token is not None: __body["refresh_token"] = refresh_token if token is not None: __body["token"] = token if username is not None: __body["username"] = username if __query: __target = f"{__path}?{_quote_query(__query)}" else: __target = __path __headers = {"accept": "application/json", "content-type": "application/json"} return self._perform_request("DELETE", __target, headers=__headers, body=__body)
[ "def", "invalidate_token", "(", "self", ",", "*", ",", "error_trace", ":", "Optional", "[", "bool", "]", "=", "None", ",", "filter_path", ":", "Optional", "[", "Union", "[", "List", "[", "str", "]", ",", "str", "]", "]", "=", "None", ",", "human", ":", "Optional", "[", "bool", "]", "=", "None", ",", "pretty", ":", "Optional", "[", "bool", "]", "=", "None", ",", "realm_name", ":", "Optional", "[", "Any", "]", "=", "None", ",", "refresh_token", ":", "Optional", "[", "str", "]", "=", "None", ",", "token", ":", "Optional", "[", "str", "]", "=", "None", ",", "username", ":", "Optional", "[", "Any", "]", "=", "None", ",", ")", "->", "ObjectApiResponse", "[", "Any", "]", ":", "__path", "=", "\"/_security/oauth2/token\"", "__query", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "__body", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "if", "error_trace", "is", "not", "None", ":", "__query", "[", "\"error_trace\"", "]", "=", "error_trace", "if", "filter_path", "is", "not", "None", ":", "__query", "[", "\"filter_path\"", "]", "=", "filter_path", "if", "human", "is", "not", "None", ":", "__query", "[", "\"human\"", "]", "=", "human", "if", "pretty", "is", "not", "None", ":", "__query", "[", "\"pretty\"", "]", "=", "pretty", "if", "realm_name", "is", "not", "None", ":", "__body", "[", "\"realm_name\"", "]", "=", "realm_name", "if", "refresh_token", "is", "not", "None", ":", "__body", "[", "\"refresh_token\"", "]", "=", "refresh_token", "if", "token", "is", "not", "None", ":", "__body", "[", "\"token\"", "]", "=", "token", "if", "username", "is", "not", "None", ":", "__body", "[", "\"username\"", "]", "=", "username", "if", "__query", ":", "__target", "=", "f\"{__path}?{_quote_query(__query)}\"", "else", ":", "__target", "=", "__path", "__headers", "=", "{", "\"accept\"", ":", "\"application/json\"", ",", "\"content-type\"", ":", "\"application/json\"", "}", "return", "self", ".", "_perform_request", "(", "\"DELETE\"", ",", "__target", ",", "headers", "=", "__headers", ",", "body", "=", "__body", ")" ]
https://github.com/elastic/elasticsearch-py/blob/6ef1adfa3c840a84afda7369cd8e43ae7dc45cdb/elasticsearch/_sync/client/security.py#L1347-L1393
ring04h/weakfilescan
b1a3066e3fdcd60b8ecf635526f49cb5ad603064
libs/requests/models.py
python
RequestEncodingMixin.path_url
(self)
return ''.join(url)
Build the path URL to use.
Build the path URL to use.
[ "Build", "the", "path", "URL", "to", "use", "." ]
def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url)
[ "def", "path_url", "(", "self", ")", ":", "url", "=", "[", "]", "p", "=", "urlsplit", "(", "self", ".", "url", ")", "path", "=", "p", ".", "path", "if", "not", "path", ":", "path", "=", "'/'", "url", ".", "append", "(", "path", ")", "query", "=", "p", ".", "query", "if", "query", ":", "url", ".", "append", "(", "'?'", ")", "url", ".", "append", "(", "query", ")", "return", "''", ".", "join", "(", "url", ")" ]
https://github.com/ring04h/weakfilescan/blob/b1a3066e3fdcd60b8ecf635526f49cb5ad603064/libs/requests/models.py#L54-L72
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.bz2open
(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs)
return t
Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed.
Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed.
[ "Open", "bzip2", "compressed", "tar", "archive", "name", "for", "reading", "or", "writing", ".", "Appending", "is", "not", "allowed", "." ]
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'.") try: import bz2 except ImportError: raise CompressionError("bz2 module is not available") if fileobj is not None: fileobj = _BZ2Proxy(fileobj, mode) else: fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel) try: t = cls.taropen(name, mode, fileobj, **kwargs) except (IOError, EOFError): fileobj.close() raise ReadError("not a bzip2 file") t._extfileobj = False return t
[ "def", "bz2open", "(", "cls", ",", "name", ",", "mode", "=", "\"r\"", ",", "fileobj", "=", "None", ",", "compresslevel", "=", "9", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "mode", ")", ">", "1", "or", "mode", "not", "in", "\"rw\"", ":", "raise", "ValueError", "(", "\"mode must be 'r' or 'w'.\"", ")", "try", ":", "import", "bz2", "except", "ImportError", ":", "raise", "CompressionError", "(", "\"bz2 module is not available\"", ")", "if", "fileobj", "is", "not", "None", ":", "fileobj", "=", "_BZ2Proxy", "(", "fileobj", ",", "mode", ")", "else", ":", "fileobj", "=", "bz2", ".", "BZ2File", "(", "name", ",", "mode", ",", "compresslevel", "=", "compresslevel", ")", "try", ":", "t", "=", "cls", ".", "taropen", "(", "name", ",", "mode", ",", "fileobj", ",", "*", "*", "kwargs", ")", "except", "(", "IOError", ",", "EOFError", ")", ":", "fileobj", ".", "close", "(", ")", "raise", "ReadError", "(", "\"not a bzip2 file\"", ")", "t", ".", "_extfileobj", "=", "False", "return", "t" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/repackage/pip/pip/_vendor/distlib/_backport/tarfile.py#L1829-L1852
williballenthin/python-registry
11e857623469dd28ed14519a08d2db7c8228ca0c
Registry/Registry.py
python
Registry.hive_name
(self)
return self._regf.hive_name()
Returns the internal file name
Returns the internal file name
[ "Returns", "the", "internal", "file", "name" ]
def hive_name(self): """Returns the internal file name""" return self._regf.hive_name()
[ "def", "hive_name", "(", "self", ")", ":", "return", "self", ".", "_regf", ".", "hive_name", "(", ")" ]
https://github.com/williballenthin/python-registry/blob/11e857623469dd28ed14519a08d2db7c8228ca0c/Registry/Registry.py#L401-L403
beeware/ouroboros
a29123c6fab6a807caffbb7587cf548e0c370296
ouroboros/threading.py
python
Barrier.reset
(self)
Reset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised.
Reset the barrier to the initial state.
[ "Reset", "the", "barrier", "to", "the", "initial", "state", "." ]
def reset(self): """Reset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised. """ with self._cond: if self._count > 0: if self._state == 0: #reset the barrier, waking up threads self._state = -1 elif self._state == -2: #was broken, set it to reset state #which clears when the last thread exits self._state = -1 else: self._state = 0 self._cond.notify_all()
[ "def", "reset", "(", "self", ")", ":", "with", "self", ".", "_cond", ":", "if", "self", ".", "_count", ">", "0", ":", "if", "self", ".", "_state", "==", "0", ":", "#reset the barrier, waking up threads", "self", ".", "_state", "=", "-", "1", "elif", "self", ".", "_state", "==", "-", "2", ":", "#was broken, set it to reset state", "#which clears when the last thread exits", "self", ".", "_state", "=", "-", "1", "else", ":", "self", ".", "_state", "=", "0", "self", ".", "_cond", ".", "notify_all", "(", ")" ]
https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/threading.py#L659-L677
SCons/scons
309f0234d1d9cc76955818be47c5c722f577dac6
SCons/Node/Python.py
python
Value.get_csig
(self, calc=None)
return contents
Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents. Returns string. Ideally string of hex digits. (Not bytes)
Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.
[ "Because", "we", "re", "a", "Python", "value", "node", "and", "don", "t", "have", "a", "real", "timestamp", "we", "get", "to", "ignore", "the", "calculator", "and", "just", "use", "the", "value", "contents", "." ]
def get_csig(self, calc=None): """Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents. Returns string. Ideally string of hex digits. (Not bytes) """ try: return self.ninfo.csig except AttributeError: pass contents = self.get_text_contents() self.get_ninfo().csig = contents return contents
[ "def", "get_csig", "(", "self", ",", "calc", "=", "None", ")", ":", "try", ":", "return", "self", ".", "ninfo", ".", "csig", "except", "AttributeError", ":", "pass", "contents", "=", "self", ".", "get_text_contents", "(", ")", "self", ".", "get_ninfo", "(", ")", ".", "csig", "=", "contents", "return", "contents" ]
https://github.com/SCons/scons/blob/309f0234d1d9cc76955818be47c5c722f577dac6/SCons/Node/Python.py#L149-L164
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/_weakrefset.py
python
WeakSet.__gt__
(self, other)
return self.data > set(map(ref, other))
[]
def __gt__(self, other): return self.data > set(map(ref, other))
[ "def", "__gt__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "data", ">", "set", "(", "map", "(", "ref", ",", "other", ")", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/_weakrefset.py#L171-L172
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_pvc.py
python
PersistentVolumeClaim.find_access_mode
(self, inc_mode)
return index
find a user
find a user
[ "find", "a", "user" ]
def find_access_mode(self, inc_mode): ''' find a user ''' index = None try: index = self.access_modes.index(inc_mode) except ValueError as _: return index return index
[ "def", "find_access_mode", "(", "self", ",", "inc_mode", ")", ":", "index", "=", "None", "try", ":", "index", "=", "self", ".", "access_modes", ".", "index", "(", "inc_mode", ")", "except", "ValueError", "as", "_", ":", "return", "index", "return", "index" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_pvc.py#L1684-L1692
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/imghdr.py
python
test_tiff
(h, f)
TIFF (can be in Motorola or Intel byte order)
TIFF (can be in Motorola or Intel byte order)
[ "TIFF", "(", "can", "be", "in", "Motorola", "or", "Intel", "byte", "order", ")" ]
def test_tiff(h, f): """TIFF (can be in Motorola or Intel byte order)""" if h[:2] in (b'MM', b'II'): return 'tiff'
[ "def", "test_tiff", "(", "h", ",", "f", ")", ":", "if", "h", "[", ":", "2", "]", "in", "(", "b'MM'", ",", "b'II'", ")", ":", "return", "'tiff'" ]
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/imghdr.py#L57-L60
aleju/imgaug
0101108d4fed06bc5056c4a03e2bcb0216dac326
imgaug/augmenters/geometric.py
python
WithPolarWarping._warp_polygons_
(cls, psois)
return cls._warp_cbaois_(psois)
[]
def _warp_polygons_(cls, psois): return cls._warp_cbaois_(psois)
[ "def", "_warp_polygons_", "(", "cls", ",", "psois", ")", ":", "return", "cls", ".", "_warp_cbaois_", "(", "psois", ")" ]
https://github.com/aleju/imgaug/blob/0101108d4fed06bc5056c4a03e2bcb0216dac326/imgaug/augmenters/geometric.py#L5515-L5516
tahoe-lafs/tahoe-lafs
766a53b5208c03c45ca0a98e97eee76870276aa1
src/allmydata/interfaces.py
python
IDirectoryNode.set_nodes
(entries, overwrite=True)
Add multiple children to a directory node. Takes a dict mapping unicode childname to (child_node, metdata) tuples. If metdata=None, the original metadata is left unmodified. Returns a Deferred that fires (with this dirnode) when the operation finishes. This is equivalent to calling set_node() multiple times, but is much more efficient.
Add multiple children to a directory node. Takes a dict mapping unicode childname to (child_node, metdata) tuples. If metdata=None, the original metadata is left unmodified. Returns a Deferred that fires (with this dirnode) when the operation finishes. This is equivalent to calling set_node() multiple times, but is much more efficient.
[ "Add", "multiple", "children", "to", "a", "directory", "node", ".", "Takes", "a", "dict", "mapping", "unicode", "childname", "to", "(", "child_node", "metdata", ")", "tuples", ".", "If", "metdata", "=", "None", "the", "original", "metadata", "is", "left", "unmodified", ".", "Returns", "a", "Deferred", "that", "fires", "(", "with", "this", "dirnode", ")", "when", "the", "operation", "finishes", ".", "This", "is", "equivalent", "to", "calling", "set_node", "()", "multiple", "times", "but", "is", "much", "more", "efficient", "." ]
def set_nodes(entries, overwrite=True): """Add multiple children to a directory node. Takes a dict mapping unicode childname to (child_node, metdata) tuples. If metdata=None, the original metadata is left unmodified. Returns a Deferred that fires (with this dirnode) when the operation finishes. This is equivalent to calling set_node() multiple times, but is much more efficient."""
[ "def", "set_nodes", "(", "entries", ",", "overwrite", "=", "True", ")", ":" ]
https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/interfaces.py#L1420-L1426
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/urllib3/connectionpool.py
python
HTTPConnectionPool._make_request
(self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw)
return httplib_response
Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instance of :class:`urllib3.util.Timeout`, which gives you more fine-grained control over your timeouts.
Perform a request on a given urllib connection object taken from our pool.
[ "Perform", "a", "request", "on", "a", "given", "urllib", "connection", "object", "taken", "from", "our", "pool", "." ]
def _make_request(self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw): """ Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instance of :class:`urllib3.util.Timeout`, which gives you more fine-grained control over your timeouts. """ self.num_requests += 1 timeout_obj = self._get_timeout(timeout) timeout_obj.start_connect() conn.timeout = timeout_obj.connect_timeout # Trigger any extra validation we need to do. try: self._validate_conn(conn) except (SocketTimeout, BaseSSLError) as e: # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) raise # conn.request() calls httplib.*.request, not the method in # urllib3.request. It also calls makefile (recv) on the socket. if chunked: conn.request_chunked(method, url, **httplib_request_kw) else: conn.request(method, url, **httplib_request_kw) # Reset the timeout for the recv() on the socket read_timeout = timeout_obj.read_timeout # App Engine doesn't have a sock attr if getattr(conn, 'sock', None): # In Python 3 socket.py will catch EAGAIN and return None when you # try and read into the file pointer created by http.client, which # instead raises a BadStatusLine exception. Instead of catching # the exception and assuming all BadStatusLine exceptions are read # timeouts, check for a zero timeout before making the request. if read_timeout == 0: raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % read_timeout) if read_timeout is Timeout.DEFAULT_TIMEOUT: conn.sock.settimeout(socket.getdefaulttimeout()) else: # None or a value conn.sock.settimeout(read_timeout) # Receive the response from the server try: try: # Python 2.7, use buffering of HTTP responses httplib_response = conn.getresponse(buffering=True) except TypeError: # Python 2.6 and older, Python 3 try: httplib_response = conn.getresponse() except Exception as e: # Remove the TypeError from the exception chain in Python 3; # otherwise it looks like a programming error was the cause. six.raise_from(e, None) except (SocketTimeout, BaseSSLError, SocketError) as e: self._raise_timeout(err=e, url=url, timeout_value=read_timeout) raise # AppEngine doesn't have a version attr. http_version = getattr(conn, '_http_vsn_str', 'HTTP/?') log.debug("%s://%s:%s \"%s %s %s\" %s %s", self.scheme, self.host, self.port, method, url, http_version, httplib_response.status, httplib_response.length) try: assert_header_parsing(httplib_response.msg) except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3 log.warning( 'Failed to parse headers (url=%s): %s', self._absolute_url(url), hpe, exc_info=True) return httplib_response
[ "def", "_make_request", "(", "self", ",", "conn", ",", "method", ",", "url", ",", "timeout", "=", "_Default", ",", "chunked", "=", "False", ",", "*", "*", "httplib_request_kw", ")", ":", "self", ".", "num_requests", "+=", "1", "timeout_obj", "=", "self", ".", "_get_timeout", "(", "timeout", ")", "timeout_obj", ".", "start_connect", "(", ")", "conn", ".", "timeout", "=", "timeout_obj", ".", "connect_timeout", "# Trigger any extra validation we need to do.", "try", ":", "self", ".", "_validate_conn", "(", "conn", ")", "except", "(", "SocketTimeout", ",", "BaseSSLError", ")", "as", "e", ":", "# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.", "self", ".", "_raise_timeout", "(", "err", "=", "e", ",", "url", "=", "url", ",", "timeout_value", "=", "conn", ".", "timeout", ")", "raise", "# conn.request() calls httplib.*.request, not the method in", "# urllib3.request. It also calls makefile (recv) on the socket.", "if", "chunked", ":", "conn", ".", "request_chunked", "(", "method", ",", "url", ",", "*", "*", "httplib_request_kw", ")", "else", ":", "conn", ".", "request", "(", "method", ",", "url", ",", "*", "*", "httplib_request_kw", ")", "# Reset the timeout for the recv() on the socket", "read_timeout", "=", "timeout_obj", ".", "read_timeout", "# App Engine doesn't have a sock attr", "if", "getattr", "(", "conn", ",", "'sock'", ",", "None", ")", ":", "# In Python 3 socket.py will catch EAGAIN and return None when you", "# try and read into the file pointer created by http.client, which", "# instead raises a BadStatusLine exception. Instead of catching", "# the exception and assuming all BadStatusLine exceptions are read", "# timeouts, check for a zero timeout before making the request.", "if", "read_timeout", "==", "0", ":", "raise", "ReadTimeoutError", "(", "self", ",", "url", ",", "\"Read timed out. (read timeout=%s)\"", "%", "read_timeout", ")", "if", "read_timeout", "is", "Timeout", ".", "DEFAULT_TIMEOUT", ":", "conn", ".", "sock", ".", "settimeout", "(", "socket", ".", "getdefaulttimeout", "(", ")", ")", "else", ":", "# None or a value", "conn", ".", "sock", ".", "settimeout", "(", "read_timeout", ")", "# Receive the response from the server", "try", ":", "try", ":", "# Python 2.7, use buffering of HTTP responses", "httplib_response", "=", "conn", ".", "getresponse", "(", "buffering", "=", "True", ")", "except", "TypeError", ":", "# Python 2.6 and older, Python 3", "try", ":", "httplib_response", "=", "conn", ".", "getresponse", "(", ")", "except", "Exception", "as", "e", ":", "# Remove the TypeError from the exception chain in Python 3;", "# otherwise it looks like a programming error was the cause.", "six", ".", "raise_from", "(", "e", ",", "None", ")", "except", "(", "SocketTimeout", ",", "BaseSSLError", ",", "SocketError", ")", "as", "e", ":", "self", ".", "_raise_timeout", "(", "err", "=", "e", ",", "url", "=", "url", ",", "timeout_value", "=", "read_timeout", ")", "raise", "# AppEngine doesn't have a version attr.", "http_version", "=", "getattr", "(", "conn", ",", "'_http_vsn_str'", ",", "'HTTP/?'", ")", "log", ".", "debug", "(", "\"%s://%s:%s \\\"%s %s %s\\\" %s %s\"", ",", "self", ".", "scheme", ",", "self", ".", "host", ",", "self", ".", "port", ",", "method", ",", "url", ",", "http_version", ",", "httplib_response", ".", "status", ",", "httplib_response", ".", "length", ")", "try", ":", "assert_header_parsing", "(", "httplib_response", ".", "msg", ")", "except", "(", "HeaderParsingError", ",", "TypeError", ")", "as", "hpe", ":", "# Platform-specific: Python 3", "log", ".", "warning", "(", "'Failed to parse headers (url=%s): %s'", ",", "self", ".", "_absolute_url", "(", "url", ")", ",", "hpe", ",", "exc_info", "=", "True", ")", "return", "httplib_response" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/urllib3/connectionpool.py#L322-L405
mvillalba/python-ant
5937964fdd091bb65ff6169a7a947c66acc51344
src/ant/core/message.py
python
Message.getSize
(self)
return len(self.getPayload()) + 4
[]
def getSize(self): return len(self.getPayload()) + 4
[ "def", "getSize", "(", "self", ")", ":", "return", "len", "(", "self", ".", "getPayload", "(", ")", ")", "+", "4" ]
https://github.com/mvillalba/python-ant/blob/5937964fdd091bb65ff6169a7a947c66acc51344/src/ant/core/message.py#L69-L70
wrye-bash/wrye-bash
d495c47cfdb44475befa523438a40c4419cb386f
Mopy/bash/bolt.py
python
Path.getNorm
(str_or_path)
return os.path.normpath(str_or_path)
Return the normpath for specified basename/Path object.
Return the normpath for specified basename/Path object.
[ "Return", "the", "normpath", "for", "specified", "basename", "/", "Path", "object", "." ]
def getNorm(str_or_path): # type: (str|bytes|Path) -> str """Return the normpath for specified basename/Path object.""" if isinstance(str_or_path, Path): return str_or_path._s elif not str_or_path: return u'' # and not maybe b'' elif isinstance(str_or_path, bytes): str_or_path = decoder(str_or_path) return os.path.normpath(str_or_path)
[ "def", "getNorm", "(", "str_or_path", ")", ":", "# type: (str|bytes|Path) -> str", "if", "isinstance", "(", "str_or_path", ",", "Path", ")", ":", "return", "str_or_path", ".", "_s", "elif", "not", "str_or_path", ":", "return", "u''", "# and not maybe b''", "elif", "isinstance", "(", "str_or_path", ",", "bytes", ")", ":", "str_or_path", "=", "decoder", "(", "str_or_path", ")", "return", "os", ".", "path", ".", "normpath", "(", "str_or_path", ")" ]
https://github.com/wrye-bash/wrye-bash/blob/d495c47cfdb44475befa523438a40c4419cb386f/Mopy/bash/bolt.py#L507-L513
chrismaddalena/ODIN
03fb0044fe658df4d67ffbb8223060958537f17e
lib/reporter.py
python
Reporter.create_lookalike_table
(self,client,domain)
Record lookalike domains and the threat feed results for each domain. Parameters: client The name of the target organization domain The domain name to use for the typo-squatting checks
Record lookalike domains and the threat feed results for each domain.
[ "Record", "lookalike", "domains", "and", "the", "threat", "feed", "results", "for", "each", "domain", "." ]
def create_lookalike_table(self,client,domain): """Record lookalike domains and the threat feed results for each domain. Parameters: client The name of the target organization domain The domain name to use for the typo-squatting checks """ lookalike_results = self.lookalike_toolkit.run_domain_twister(domain) if lookalike_results: # Record each typosquatted domain for result in lookalike_results: domain = result['domain'] rank = result['rank'] a_records = result['a_records'] mx_records = result['mx_records'] malicious = result['malicious'] self.c.execute("INSERT INTO lookalike VALUES (?,?,?,?,?,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)", (domain,str(rank),a_records,mx_records,malicious)) self.conn.commit() # Check each domain with URLVoid for reputation data tree = self.lookalike_toolkit.run_urlvoid_lookup(domain) count = "" engines = "" if tree is not None: # Check to see if urlvoid shows the domain flagged by any engines try: for child in tree: malicious_check = child.tag if malicious_check == "detections": detections = tree[1] engines = detections[0] count = ET.tostring(detections[1],method='text').rstrip().decode('ascii') temp = [] for engine in engines: temp.append(ET.tostring(engine,method='text').rstrip().decode('ascii')) engines = ", ".join(temp) rep_data = tree[0] if len(rep_data) == 0: pass else: target = ET.tostring(rep_data[0],method='text').rstrip().decode('ascii') domain_age = ET.tostring(rep_data[3],method='text').rstrip().decode('ascii') google_rank = ET.tostring(rep_data[4],method='text').rstrip().decode('ascii') alexa_rank = ET.tostring(rep_data[5],method='text').rstrip().decode('ascii') if rep_data[11]: ip_data = rep_data[11] ip_add = ET.tostring(ip_data[0],method='text').rstrip().decode('ascii') hostnames = ET.tostring(ip_data[1],method='text').rstrip().decode('ascii') asn = ET.tostring(ip_data[2],method='text').rstrip().decode('ascii') asn_name = ET.tostring(ip_data[3],method='text').rstrip().decode('ascii') else: ip_add = None hostnames = None asn = None asn_name = None self.c.execute('''UPDATE lookalike SET 'urlvoid_ip'=?, 'hostname'=?, 'domain_age'=?, 'google_rank'=?, 'alexa_rank'=?, 'asn'=?, 'asn_name'=?, 'urlvoid_hit'=?, 'urlvoid_engines'=? WHERE domain = ?''', (ip_add,hostnames,domain_age,google_rank,alexa_rank,asn, asn_name,count,engines,target)) self.conn.commit() except: # click.secho("[!] There was an error getting the data for {}.".format(domain),fg="red") pass
[ "def", "create_lookalike_table", "(", "self", ",", "client", ",", "domain", ")", ":", "lookalike_results", "=", "self", ".", "lookalike_toolkit", ".", "run_domain_twister", "(", "domain", ")", "if", "lookalike_results", ":", "# Record each typosquatted domain", "for", "result", "in", "lookalike_results", ":", "domain", "=", "result", "[", "'domain'", "]", "rank", "=", "result", "[", "'rank'", "]", "a_records", "=", "result", "[", "'a_records'", "]", "mx_records", "=", "result", "[", "'mx_records'", "]", "malicious", "=", "result", "[", "'malicious'", "]", "self", ".", "c", ".", "execute", "(", "\"INSERT INTO lookalike VALUES (?,?,?,?,?,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)\"", ",", "(", "domain", ",", "str", "(", "rank", ")", ",", "a_records", ",", "mx_records", ",", "malicious", ")", ")", "self", ".", "conn", ".", "commit", "(", ")", "# Check each domain with URLVoid for reputation data", "tree", "=", "self", ".", "lookalike_toolkit", ".", "run_urlvoid_lookup", "(", "domain", ")", "count", "=", "\"\"", "engines", "=", "\"\"", "if", "tree", "is", "not", "None", ":", "# Check to see if urlvoid shows the domain flagged by any engines", "try", ":", "for", "child", "in", "tree", ":", "malicious_check", "=", "child", ".", "tag", "if", "malicious_check", "==", "\"detections\"", ":", "detections", "=", "tree", "[", "1", "]", "engines", "=", "detections", "[", "0", "]", "count", "=", "ET", ".", "tostring", "(", "detections", "[", "1", "]", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", "temp", "=", "[", "]", "for", "engine", "in", "engines", ":", "temp", ".", "append", "(", "ET", ".", "tostring", "(", "engine", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", ")", "engines", "=", "\", \"", ".", "join", "(", "temp", ")", "rep_data", "=", "tree", "[", "0", "]", "if", "len", "(", "rep_data", ")", "==", "0", ":", "pass", "else", ":", "target", "=", "ET", ".", "tostring", "(", "rep_data", "[", "0", "]", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", "domain_age", "=", "ET", ".", "tostring", "(", "rep_data", "[", "3", "]", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", "google_rank", "=", "ET", ".", "tostring", "(", "rep_data", "[", "4", "]", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", "alexa_rank", "=", "ET", ".", "tostring", "(", "rep_data", "[", "5", "]", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", "if", "rep_data", "[", "11", "]", ":", "ip_data", "=", "rep_data", "[", "11", "]", "ip_add", "=", "ET", ".", "tostring", "(", "ip_data", "[", "0", "]", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", "hostnames", "=", "ET", ".", "tostring", "(", "ip_data", "[", "1", "]", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", "asn", "=", "ET", ".", "tostring", "(", "ip_data", "[", "2", "]", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", "asn_name", "=", "ET", ".", "tostring", "(", "ip_data", "[", "3", "]", ",", "method", "=", "'text'", ")", ".", "rstrip", "(", ")", ".", "decode", "(", "'ascii'", ")", "else", ":", "ip_add", "=", "None", "hostnames", "=", "None", "asn", "=", "None", "asn_name", "=", "None", "self", ".", "c", ".", "execute", "(", "'''UPDATE lookalike\n SET 'urlvoid_ip'=?,\n 'hostname'=?,\n 'domain_age'=?,\n 'google_rank'=?,\n 'alexa_rank'=?,\n 'asn'=?,\n 'asn_name'=?,\n 'urlvoid_hit'=?,\n 'urlvoid_engines'=?\n WHERE domain = ?'''", ",", "(", "ip_add", ",", "hostnames", ",", "domain_age", ",", "google_rank", ",", "alexa_rank", ",", "asn", ",", "asn_name", ",", "count", ",", "engines", ",", "target", ")", ")", "self", ".", "conn", ".", "commit", "(", ")", "except", ":", "# click.secho(\"[!] There was an error getting the data for {}.\".format(domain),fg=\"red\")", "pass" ]
https://github.com/chrismaddalena/ODIN/blob/03fb0044fe658df4d67ffbb8223060958537f17e/lib/reporter.py#L917-L988
anchore/anchore-engine
bb18b70e0cbcad58beb44cd439d00067d8f7ea8b
anchore_engine/services/policy_engine/engine/policy/gates/npms.py
python
NpmCheckGate.prepare_context
(self, image_obj, context)
return context
Prep the npm names and versions :rtype: :param image_obj: :param context: :return:
Prep the npm names and versions :rtype: :param image_obj: :param context: :return:
[ "Prep", "the", "npm", "names", "and", "versions", ":", "rtype", ":", ":", "param", "image_obj", ":", ":", "param", "context", ":", ":", "return", ":" ]
def prepare_context(self, image_obj, context): """ Prep the npm names and versions :rtype: :param image_obj: :param context: :return: """ db_npms = image_obj.get_packages_by_type("npm") if not db_npms: return context # context.data[NPM_LISTING_KEY] = {p.name: p.versions_json for p in image_obj.npms} npm_listing_key_data = {} for p in db_npms: if p.name not in npm_listing_key_data: npm_listing_key_data[p.name] = [] npm_listing_key_data[p.name].append(p.version) context.data[NPM_LISTING_KEY] = npm_listing_key_data npms = list(context.data[NPM_LISTING_KEY].keys()) context.data[NPM_MATCH_KEY] = [] chunks = [npms[i : i + 100] for i in range(0, len(npms), 100)] for key_range in chunks: context.data[NPM_MATCH_KEY] += ( context.db.query(NpmMetadata) .filter(NpmMetadata.name.in_(key_range)) .all() ) return context
[ "def", "prepare_context", "(", "self", ",", "image_obj", ",", "context", ")", ":", "db_npms", "=", "image_obj", ".", "get_packages_by_type", "(", "\"npm\"", ")", "if", "not", "db_npms", ":", "return", "context", "# context.data[NPM_LISTING_KEY] = {p.name: p.versions_json for p in image_obj.npms}", "npm_listing_key_data", "=", "{", "}", "for", "p", "in", "db_npms", ":", "if", "p", ".", "name", "not", "in", "npm_listing_key_data", ":", "npm_listing_key_data", "[", "p", ".", "name", "]", "=", "[", "]", "npm_listing_key_data", "[", "p", ".", "name", "]", ".", "append", "(", "p", ".", "version", ")", "context", ".", "data", "[", "NPM_LISTING_KEY", "]", "=", "npm_listing_key_data", "npms", "=", "list", "(", "context", ".", "data", "[", "NPM_LISTING_KEY", "]", ".", "keys", "(", ")", ")", "context", ".", "data", "[", "NPM_MATCH_KEY", "]", "=", "[", "]", "chunks", "=", "[", "npms", "[", "i", ":", "i", "+", "100", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "npms", ")", ",", "100", ")", "]", "for", "key_range", "in", "chunks", ":", "context", ".", "data", "[", "NPM_MATCH_KEY", "]", "+=", "(", "context", ".", "db", ".", "query", "(", "NpmMetadata", ")", ".", "filter", "(", "NpmMetadata", ".", "name", ".", "in_", "(", "key_range", ")", ")", ".", "all", "(", ")", ")", "return", "context" ]
https://github.com/anchore/anchore-engine/blob/bb18b70e0cbcad58beb44cd439d00067d8f7ea8b/anchore_engine/services/policy_engine/engine/policy/gates/npms.py#L204-L235
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/core/exprtools.py
python
Factors.__init__
(self, factors=None)
Initialize Factors from dict or expr. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x >>> from sympy import I >>> e = 2*x**3 >>> Factors(e) Factors({2: 1, x: 3}) >>> Factors(e.as_powers_dict()) Factors({2: 1, x: 3}) >>> f = _ >>> f.factors # underlying dictionary {2: 1, x: 3} >>> f.gens # base of each factor frozenset({2, x}) >>> Factors(0) Factors({0: 1}) >>> Factors(I) Factors({I: 1}) Notes ===== Although a dictionary can be passed, only minimal checking is performed: powers of -1 and I are made canonical.
Initialize Factors from dict or expr.
[ "Initialize", "Factors", "from", "dict", "or", "expr", "." ]
def __init__(self, factors=None): # Factors """Initialize Factors from dict or expr. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x >>> from sympy import I >>> e = 2*x**3 >>> Factors(e) Factors({2: 1, x: 3}) >>> Factors(e.as_powers_dict()) Factors({2: 1, x: 3}) >>> f = _ >>> f.factors # underlying dictionary {2: 1, x: 3} >>> f.gens # base of each factor frozenset({2, x}) >>> Factors(0) Factors({0: 1}) >>> Factors(I) Factors({I: 1}) Notes ===== Although a dictionary can be passed, only minimal checking is performed: powers of -1 and I are made canonical. """ if isinstance(factors, (SYMPY_INTS, float)): factors = S(factors) if isinstance(factors, Factors): factors = factors.factors.copy() elif factors is None or factors is S.One: factors = {} elif factors is S.Zero or factors == 0: factors = {S.Zero: S.One} elif isinstance(factors, Number): n = factors factors = {} if n < 0: factors[S.NegativeOne] = S.One n = -n if n is not S.One: if n.is_Float or n.is_Integer or n is S.Infinity: factors[n] = S.One elif n.is_Rational: # since we're processing Numbers, the denominator is # stored with a negative exponent; all other factors # are left . if n.p != 1: factors[Integer(n.p)] = S.One factors[Integer(n.q)] = S.NegativeOne else: raise ValueError('Expected Float|Rational|Integer, not %s' % n) elif isinstance(factors, Basic) and not factors.args: factors = {factors: S.One} elif isinstance(factors, Expr): c, nc = factors.args_cnc() i = c.count(I) for _ in range(i): c.remove(I) factors = dict(Mul._from_args(c).as_powers_dict()) # Handle all rational Coefficients for f in list(factors.keys()): if isinstance(f, Rational) and not isinstance(f, Integer): p, q = Integer(f.p), Integer(f.q) factors[p] = (factors[p] if p in factors else 0) + factors[f] factors[q] = (factors[q] if q in factors else 0) - factors[f] factors.pop(f) if i: factors[I] = S.One*i if nc: factors[Mul(*nc, evaluate=False)] = S.One else: factors = factors.copy() # /!\ should be dict-like # tidy up -/+1 and I exponents if Rational handle = [] for k in factors: if k is I or k in (-1, 1): handle.append(k) if handle: i1 = S.One for k in handle: if not _isnumber(factors[k]): continue i1 *= k**factors.pop(k) if i1 is not S.One: for a in i1.args if i1.is_Mul else [i1]: # at worst, -1.0*I*(-1)**e if a is S.NegativeOne: factors[a] = S.One elif a is I: factors[I] = S.One elif a.is_Pow: if S.NegativeOne not in factors: factors[S.NegativeOne] = S.Zero factors[S.NegativeOne] += a.exp elif a == 1: factors[a] = S.One elif a == -1: factors[-a] = S.One factors[S.NegativeOne] = S.One else: raise ValueError('unexpected factor in i1: %s' % a) self.factors = factors keys = getattr(factors, 'keys', None) if keys is None: raise TypeError('expecting Expr or dictionary') self.gens = frozenset(keys())
[ "def", "__init__", "(", "self", ",", "factors", "=", "None", ")", ":", "# Factors", "if", "isinstance", "(", "factors", ",", "(", "SYMPY_INTS", ",", "float", ")", ")", ":", "factors", "=", "S", "(", "factors", ")", "if", "isinstance", "(", "factors", ",", "Factors", ")", ":", "factors", "=", "factors", ".", "factors", ".", "copy", "(", ")", "elif", "factors", "is", "None", "or", "factors", "is", "S", ".", "One", ":", "factors", "=", "{", "}", "elif", "factors", "is", "S", ".", "Zero", "or", "factors", "==", "0", ":", "factors", "=", "{", "S", ".", "Zero", ":", "S", ".", "One", "}", "elif", "isinstance", "(", "factors", ",", "Number", ")", ":", "n", "=", "factors", "factors", "=", "{", "}", "if", "n", "<", "0", ":", "factors", "[", "S", ".", "NegativeOne", "]", "=", "S", ".", "One", "n", "=", "-", "n", "if", "n", "is", "not", "S", ".", "One", ":", "if", "n", ".", "is_Float", "or", "n", ".", "is_Integer", "or", "n", "is", "S", ".", "Infinity", ":", "factors", "[", "n", "]", "=", "S", ".", "One", "elif", "n", ".", "is_Rational", ":", "# since we're processing Numbers, the denominator is", "# stored with a negative exponent; all other factors", "# are left .", "if", "n", ".", "p", "!=", "1", ":", "factors", "[", "Integer", "(", "n", ".", "p", ")", "]", "=", "S", ".", "One", "factors", "[", "Integer", "(", "n", ".", "q", ")", "]", "=", "S", ".", "NegativeOne", "else", ":", "raise", "ValueError", "(", "'Expected Float|Rational|Integer, not %s'", "%", "n", ")", "elif", "isinstance", "(", "factors", ",", "Basic", ")", "and", "not", "factors", ".", "args", ":", "factors", "=", "{", "factors", ":", "S", ".", "One", "}", "elif", "isinstance", "(", "factors", ",", "Expr", ")", ":", "c", ",", "nc", "=", "factors", ".", "args_cnc", "(", ")", "i", "=", "c", ".", "count", "(", "I", ")", "for", "_", "in", "range", "(", "i", ")", ":", "c", ".", "remove", "(", "I", ")", "factors", "=", "dict", "(", "Mul", ".", "_from_args", "(", "c", ")", ".", "as_powers_dict", "(", ")", ")", "# Handle all rational Coefficients", "for", "f", "in", "list", "(", "factors", ".", "keys", "(", ")", ")", ":", "if", "isinstance", "(", "f", ",", "Rational", ")", "and", "not", "isinstance", "(", "f", ",", "Integer", ")", ":", "p", ",", "q", "=", "Integer", "(", "f", ".", "p", ")", ",", "Integer", "(", "f", ".", "q", ")", "factors", "[", "p", "]", "=", "(", "factors", "[", "p", "]", "if", "p", "in", "factors", "else", "0", ")", "+", "factors", "[", "f", "]", "factors", "[", "q", "]", "=", "(", "factors", "[", "q", "]", "if", "q", "in", "factors", "else", "0", ")", "-", "factors", "[", "f", "]", "factors", ".", "pop", "(", "f", ")", "if", "i", ":", "factors", "[", "I", "]", "=", "S", ".", "One", "*", "i", "if", "nc", ":", "factors", "[", "Mul", "(", "*", "nc", ",", "evaluate", "=", "False", ")", "]", "=", "S", ".", "One", "else", ":", "factors", "=", "factors", ".", "copy", "(", ")", "# /!\\ should be dict-like", "# tidy up -/+1 and I exponents if Rational", "handle", "=", "[", "]", "for", "k", "in", "factors", ":", "if", "k", "is", "I", "or", "k", "in", "(", "-", "1", ",", "1", ")", ":", "handle", ".", "append", "(", "k", ")", "if", "handle", ":", "i1", "=", "S", ".", "One", "for", "k", "in", "handle", ":", "if", "not", "_isnumber", "(", "factors", "[", "k", "]", ")", ":", "continue", "i1", "*=", "k", "**", "factors", ".", "pop", "(", "k", ")", "if", "i1", "is", "not", "S", ".", "One", ":", "for", "a", "in", "i1", ".", "args", "if", "i1", ".", "is_Mul", "else", "[", "i1", "]", ":", "# at worst, -1.0*I*(-1)**e", "if", "a", "is", "S", ".", "NegativeOne", ":", "factors", "[", "a", "]", "=", "S", ".", "One", "elif", "a", "is", "I", ":", "factors", "[", "I", "]", "=", "S", ".", "One", "elif", "a", ".", "is_Pow", ":", "if", "S", ".", "NegativeOne", "not", "in", "factors", ":", "factors", "[", "S", ".", "NegativeOne", "]", "=", "S", ".", "Zero", "factors", "[", "S", ".", "NegativeOne", "]", "+=", "a", ".", "exp", "elif", "a", "==", "1", ":", "factors", "[", "a", "]", "=", "S", ".", "One", "elif", "a", "==", "-", "1", ":", "factors", "[", "-", "a", "]", "=", "S", ".", "One", "factors", "[", "S", ".", "NegativeOne", "]", "=", "S", ".", "One", "else", ":", "raise", "ValueError", "(", "'unexpected factor in i1: %s'", "%", "a", ")", "self", ".", "factors", "=", "factors", "keys", "=", "getattr", "(", "factors", ",", "'keys'", ",", "None", ")", "if", "keys", "is", "None", ":", "raise", "TypeError", "(", "'expecting Expr or dictionary'", ")", "self", ".", "gens", "=", "frozenset", "(", "keys", "(", ")", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/core/exprtools.py#L292-L405
Azure/azure-linux-extensions
a42ef718c746abab2b3c6a21da87b29e76364558
OSPatching/azure/storage/blobservice.py
python
BlobService.list_blobs
(self, container_name, prefix=None, marker=None, maxresults=None, include=None, delimiter=None)
return _parse_blob_enum_results_list(response)
Returns the list of blobs under the specified container. container_name: Name of existing container. prefix: Optional. Filters the results to return only blobs whose names begin with the specified prefix. marker: Optional. A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client. maxresults: Optional. Specifies the maximum number of blobs to return, including all BlobPrefix elements. If the request does not specify maxresults or specifies a value greater than 5,000, the server will return up to 5,000 items. Setting maxresults to a value less than or equal to zero results in error response code 400 (Bad Request). include: Optional. Specifies one or more datasets to include in the response. To specify more than one of these options on the URI, you must separate each option with a comma. Valid values are: snapshots: Specifies that snapshots should be included in the enumeration. Snapshots are listed from oldest to newest in the response. metadata: Specifies that blob metadata be returned in the response. uncommittedblobs: Specifies that blobs for which blocks have been uploaded, but which have not been committed using Put Block List (REST API), be included in the response. copy: Version 2012-02-12 and newer. Specifies that metadata related to any current or previous Copy Blob operation should be included in the response. delimiter: Optional. When the request includes this parameter, the operation returns a BlobPrefix element in the response body that acts as a placeholder for all blobs whose names begin with the same substring up to the appearance of the delimiter character. The delimiter may be a single character or a string.
Returns the list of blobs under the specified container.
[ "Returns", "the", "list", "of", "blobs", "under", "the", "specified", "container", "." ]
def list_blobs(self, container_name, prefix=None, marker=None, maxresults=None, include=None, delimiter=None): ''' Returns the list of blobs under the specified container. container_name: Name of existing container. prefix: Optional. Filters the results to return only blobs whose names begin with the specified prefix. marker: Optional. A string value that identifies the portion of the list to be returned with the next list operation. The operation returns a marker value within the response body if the list returned was not complete. The marker value may then be used in a subsequent call to request the next set of list items. The marker value is opaque to the client. maxresults: Optional. Specifies the maximum number of blobs to return, including all BlobPrefix elements. If the request does not specify maxresults or specifies a value greater than 5,000, the server will return up to 5,000 items. Setting maxresults to a value less than or equal to zero results in error response code 400 (Bad Request). include: Optional. Specifies one or more datasets to include in the response. To specify more than one of these options on the URI, you must separate each option with a comma. Valid values are: snapshots: Specifies that snapshots should be included in the enumeration. Snapshots are listed from oldest to newest in the response. metadata: Specifies that blob metadata be returned in the response. uncommittedblobs: Specifies that blobs for which blocks have been uploaded, but which have not been committed using Put Block List (REST API), be included in the response. copy: Version 2012-02-12 and newer. Specifies that metadata related to any current or previous Copy Blob operation should be included in the response. delimiter: Optional. When the request includes this parameter, the operation returns a BlobPrefix element in the response body that acts as a placeholder for all blobs whose names begin with the same substring up to the appearance of the delimiter character. The delimiter may be a single character or a string. ''' _validate_not_none('container_name', container_name) request = HTTPRequest() request.method = 'GET' request.host = self._get_host() request.path = '/' + \ _str(container_name) + '?restype=container&comp=list' request.query = [ ('prefix', _str_or_none(prefix)), ('delimiter', _str_or_none(delimiter)), ('marker', _str_or_none(marker)), ('maxresults', _int_or_none(maxresults)), ('include', _str_or_none(include)) ] request.path, request.query = _update_request_uri_query_local_storage( request, self.use_local_storage) request.headers = _update_storage_blob_header( request, self.account_name, self.account_key) response = self._perform_request(request) return _parse_blob_enum_results_list(response)
[ "def", "list_blobs", "(", "self", ",", "container_name", ",", "prefix", "=", "None", ",", "marker", "=", "None", ",", "maxresults", "=", "None", ",", "include", "=", "None", ",", "delimiter", "=", "None", ")", ":", "_validate_not_none", "(", "'container_name'", ",", "container_name", ")", "request", "=", "HTTPRequest", "(", ")", "request", ".", "method", "=", "'GET'", "request", ".", "host", "=", "self", ".", "_get_host", "(", ")", "request", ".", "path", "=", "'/'", "+", "_str", "(", "container_name", ")", "+", "'?restype=container&comp=list'", "request", ".", "query", "=", "[", "(", "'prefix'", ",", "_str_or_none", "(", "prefix", ")", ")", ",", "(", "'delimiter'", ",", "_str_or_none", "(", "delimiter", ")", ")", ",", "(", "'marker'", ",", "_str_or_none", "(", "marker", ")", ")", ",", "(", "'maxresults'", ",", "_int_or_none", "(", "maxresults", ")", ")", ",", "(", "'include'", ",", "_str_or_none", "(", "include", ")", ")", "]", "request", ".", "path", ",", "request", ".", "query", "=", "_update_request_uri_query_local_storage", "(", "request", ",", "self", ".", "use_local_storage", ")", "request", ".", "headers", "=", "_update_storage_blob_header", "(", "request", ",", "self", ".", "account_name", ",", "self", ".", "account_key", ")", "response", "=", "self", ".", "_perform_request", "(", "request", ")", "return", "_parse_blob_enum_results_list", "(", "response", ")" ]
https://github.com/Azure/azure-linux-extensions/blob/a42ef718c746abab2b3c6a21da87b29e76364558/OSPatching/azure/storage/blobservice.py#L421-L487
kbandla/ImmunityDebugger
2abc03fb15c8f3ed0914e1175c4d8933977c73e3
1.85/Libs/debugtypes.py
python
Module.getEntry
(self)
Get Entry from module @rtype: DWORD @return: Entry
Get Entry from module
[ "Get", "Entry", "from", "module" ]
def getEntry(self): """ Get Entry from module @rtype: DWORD @return: Entry """ try: return self.modDict['entry'][0] except KeyError: return None
[ "def", "getEntry", "(", "self", ")", ":", "try", ":", "return", "self", ".", "modDict", "[", "'entry'", "]", "[", "0", "]", "except", "KeyError", ":", "return", "None" ]
https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.85/Libs/debugtypes.py#L375-L385
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/ca_certs.py
python
print_cert_subject
(cert, reason)
:param cert: The asn1crypto.x509.Certificate object :param reason: None if being exported, or a unicode string of the reason not being exported
:param cert: The asn1crypto.x509.Certificate object
[ ":", "param", "cert", ":", "The", "asn1crypto", ".", "x509", ".", "Certificate", "object" ]
def print_cert_subject(cert, reason): """ :param cert: The asn1crypto.x509.Certificate object :param reason: None if being exported, or a unicode string of the reason not being exported """ if reason is None: console_write( u''' Exported certificate: %s ''', cert.subject.human_friendly ) else: console_write( u''' Skipped certificate: %s - reason %s ''', (cert.subject.human_friendly, reason) )
[ "def", "print_cert_subject", "(", "cert", ",", "reason", ")", ":", "if", "reason", "is", "None", ":", "console_write", "(", "u'''\n Exported certificate: %s\n '''", ",", "cert", ".", "subject", ".", "human_friendly", ")", "else", ":", "console_write", "(", "u'''\n Skipped certificate: %s - reason %s\n '''", ",", "(", "cert", ".", "subject", ".", "human_friendly", ",", "reason", ")", ")" ]
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/ca_certs.py#L94-L117
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/lib2to3/refactor.py
python
RefactoringTool.log_error
(self, msg, *args, **kwds)
Called when an error occurs.
Called when an error occurs.
[ "Called", "when", "an", "error", "occurs", "." ]
def log_error(self, msg, *args, **kwds): """Called when an error occurs.""" raise
[ "def", "log_error", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "raise" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/lib2to3/refactor.py#L261-L263
beancount/beancount
cb3526a1af95b3b5be70347470c381b5a86055fe
beancount/plugins/commodity_attr.py
python
validate_commodity_attr
(entries, unused_options_map, config_str)
return entries, errors
Check that all Commodity directives have a valid attribute. Args: entries: A list of directives. unused_options_map: An options map. config_str: A configuration string. Returns: A list of new errors, if any were found.
Check that all Commodity directives have a valid attribute.
[ "Check", "that", "all", "Commodity", "directives", "have", "a", "valid", "attribute", "." ]
def validate_commodity_attr(entries, unused_options_map, config_str): """Check that all Commodity directives have a valid attribute. Args: entries: A list of directives. unused_options_map: An options map. config_str: A configuration string. Returns: A list of new errors, if any were found. """ errors = [] # pylint: disable=eval-used config_obj = eval(config_str, {}, {}) if not isinstance(config_obj, dict): errors.append(ConfigError( data.new_metadata('<commodity_attr>', 0), "Invalid configuration for commodity_attr plugin; skipping.", None)) return entries, errors validmap = {attr: frozenset(values) if values is not None else None for attr, values in config_obj.items()} for entry in entries: if not isinstance(entry, data.Commodity): continue for attr, values in validmap.items(): value = entry.meta.get(attr, None) if value is None: errors.append(CommodityError( entry.meta, "Missing attribute '{}' for Commodity directive {}".format( attr, entry.currency), None)) continue if values and value not in values: errors.append(CommodityError( entry.meta, "Invalid value '{}' for attribute {}, Commodity".format(value, attr) + " directive {}; valid options: {}".format( entry.currency, ', '.join(values)), None)) return entries, errors
[ "def", "validate_commodity_attr", "(", "entries", ",", "unused_options_map", ",", "config_str", ")", ":", "errors", "=", "[", "]", "# pylint: disable=eval-used", "config_obj", "=", "eval", "(", "config_str", ",", "{", "}", ",", "{", "}", ")", "if", "not", "isinstance", "(", "config_obj", ",", "dict", ")", ":", "errors", ".", "append", "(", "ConfigError", "(", "data", ".", "new_metadata", "(", "'<commodity_attr>'", ",", "0", ")", ",", "\"Invalid configuration for commodity_attr plugin; skipping.\"", ",", "None", ")", ")", "return", "entries", ",", "errors", "validmap", "=", "{", "attr", ":", "frozenset", "(", "values", ")", "if", "values", "is", "not", "None", "else", "None", "for", "attr", ",", "values", "in", "config_obj", ".", "items", "(", ")", "}", "for", "entry", "in", "entries", ":", "if", "not", "isinstance", "(", "entry", ",", "data", ".", "Commodity", ")", ":", "continue", "for", "attr", ",", "values", "in", "validmap", ".", "items", "(", ")", ":", "value", "=", "entry", ".", "meta", ".", "get", "(", "attr", ",", "None", ")", "if", "value", "is", "None", ":", "errors", ".", "append", "(", "CommodityError", "(", "entry", ".", "meta", ",", "\"Missing attribute '{}' for Commodity directive {}\"", ".", "format", "(", "attr", ",", "entry", ".", "currency", ")", ",", "None", ")", ")", "continue", "if", "values", "and", "value", "not", "in", "values", ":", "errors", ".", "append", "(", "CommodityError", "(", "entry", ".", "meta", ",", "\"Invalid value '{}' for attribute {}, Commodity\"", ".", "format", "(", "value", ",", "attr", ")", "+", "\" directive {}; valid options: {}\"", ".", "format", "(", "entry", ".", "currency", ",", "', '", ".", "join", "(", "values", ")", ")", ",", "None", ")", ")", "return", "entries", ",", "errors" ]
https://github.com/beancount/beancount/blob/cb3526a1af95b3b5be70347470c381b5a86055fe/beancount/plugins/commodity_attr.py#L31-L71
slackapi/python-slack-sdk
2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7
slack_sdk/models/dialogs/__init__.py
python
DialogBuilder.text_area
( self, *, name: str, label: str, optional: bool = False, placeholder: Optional[str] = None, hint: Optional[str] = None, value: Optional[str] = None, min_length: int = 0, max_length: int = 3000, subtype: Optional[str] = None, )
return self
A textarea is a multi-line plain text editing control. You've likely encountered these on the world wide web. Use this element if you want a relatively long answer from users. The element UI provides a remaining character count to the max_length you have set or the default, 3000. https://api.slack.com/dialogs#attributes_textarea_elements Args: name: Name of form element. Required. No more than 300 characters. label: Label displayed to user. Required. 48 character maximum. optional: Provide true when the form element is not required. By default, form elements are required. placeholder: A string displayed as needed to help guide users in completing the element. 150 character maximum. hint: Helpful text provided to assist users in answering a question. Up to 150 characters. value: A default value for this field. Up to 3000 characters. min_length: Minimum input length allowed for element. 1-3000 characters. Defaults to 0. max_length: Maximum input length allowed for element. 0-3000 characters. Defaults to 3000. subtype: A subtype for this text input. Accepts email, number, tel, or url. In some form factors, optimized input is provided for this subtype.
A textarea is a multi-line plain text editing control. You've likely encountered these on the world wide web. Use this element if you want a relatively long answer from users. The element UI provides a remaining character count to the max_length you have set or the default, 3000.
[ "A", "textarea", "is", "a", "multi", "-", "line", "plain", "text", "editing", "control", ".", "You", "ve", "likely", "encountered", "these", "on", "the", "world", "wide", "web", ".", "Use", "this", "element", "if", "you", "want", "a", "relatively", "long", "answer", "from", "users", ".", "The", "element", "UI", "provides", "a", "remaining", "character", "count", "to", "the", "max_length", "you", "have", "set", "or", "the", "default", "3000", "." ]
def text_area( self, *, name: str, label: str, optional: bool = False, placeholder: Optional[str] = None, hint: Optional[str] = None, value: Optional[str] = None, min_length: int = 0, max_length: int = 3000, subtype: Optional[str] = None, ) -> "DialogBuilder": """ A textarea is a multi-line plain text editing control. You've likely encountered these on the world wide web. Use this element if you want a relatively long answer from users. The element UI provides a remaining character count to the max_length you have set or the default, 3000. https://api.slack.com/dialogs#attributes_textarea_elements Args: name: Name of form element. Required. No more than 300 characters. label: Label displayed to user. Required. 48 character maximum. optional: Provide true when the form element is not required. By default, form elements are required. placeholder: A string displayed as needed to help guide users in completing the element. 150 character maximum. hint: Helpful text provided to assist users in answering a question. Up to 150 characters. value: A default value for this field. Up to 3000 characters. min_length: Minimum input length allowed for element. 1-3000 characters. Defaults to 0. max_length: Maximum input length allowed for element. 0-3000 characters. Defaults to 3000. subtype: A subtype for this text input. Accepts email, number, tel, or url. In some form factors, optimized input is provided for this subtype. """ self._elements.append( DialogTextArea( name=name, label=label, optional=optional, placeholder=placeholder, hint=hint, value=value, min_length=min_length, max_length=max_length, subtype=subtype, ) ) return self
[ "def", "text_area", "(", "self", ",", "*", ",", "name", ":", "str", ",", "label", ":", "str", ",", "optional", ":", "bool", "=", "False", ",", "placeholder", ":", "Optional", "[", "str", "]", "=", "None", ",", "hint", ":", "Optional", "[", "str", "]", "=", "None", ",", "value", ":", "Optional", "[", "str", "]", "=", "None", ",", "min_length", ":", "int", "=", "0", ",", "max_length", ":", "int", "=", "3000", ",", "subtype", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", "->", "\"DialogBuilder\"", ":", "self", ".", "_elements", ".", "append", "(", "DialogTextArea", "(", "name", "=", "name", ",", "label", "=", "label", ",", "optional", "=", "optional", ",", "placeholder", "=", "placeholder", ",", "hint", "=", "hint", ",", "value", "=", "value", ",", "min_length", "=", "min_length", ",", "max_length", "=", "max_length", ",", "subtype", "=", "subtype", ",", ")", ")", "return", "self" ]
https://github.com/slackapi/python-slack-sdk/blob/2dee6656ffacb7de0c29bb2a6c2b51ec6b5dbce7/slack_sdk/models/dialogs/__init__.py#L570-L623
FrancoisSchnell/GPicSync
07d7c4b7da44e4e6665abb94bbb9ef6da0e779d1
src/gpicsync-GUI.py
python
GUI.__init__
(self,parent, title)
Initialize the main frame
Initialize the main frame
[ "Initialize", "the", "main", "frame" ]
def __init__(self,parent, title): """Initialize the main frame""" global bkg wx.Frame.__init__(self, parent, wx.ID_ANY, title="GPicSync",size=(1000,600)) favicon = wx.Icon('gpicsync.ico', wx.BITMAP_TYPE_ICO, 16, 16) wx.Frame.SetIcon(self, favicon) self.tcam_l="00:00:00" self.tgps_l="00:00:00" self.log=False self.stop=False self.interpolation=False self.picDir="" self.timezone=None self.utcOffset="0" self.backup=True self.picDirDefault="" self.GMaps=False self.urlGMaps="" self.geonames_username="gpicsync" self.geonamesTags=False self.geoname_nearbyplace=True self.geoname_region=True self.geoname_country=True self.geoname_summary=True self.geoname_caption=True self.datesMustMatch=True self.geoname_userdefine="" self.maxTimeDifference="300" self.language="English" self.timeStamp=False self.defaultLat="0.000000" self.defaultLon="0.000000" self.geoname_IPTCsummary="" # Search for an eventual gpicsync.conf file configFile=False if sys.platform=="win32": confPath=os.environ["ALLUSERSPROFILE"]+"/gpicsync.conf" print ("Searching configuration file "+confPath) if os.path.isfile(confPath): configFile=True fconf=open(os.environ["ALLUSERSPROFILE"]+"/gpicsync.conf","r+") else: configFile= False if sys.platform in ["linux", "darwin"]: confPath=os.path.expanduser("~/.gpicsync.conf") print ("Searching configuration file ~/.gpicsync.conf") if os.path.isfile(confPath): configFile=True fconf=open(os.path.expanduser("~/.gpicsync.conf"),"r+") else: confPath="./gpicsync.conf" if os.path.isfile(confPath): configFile=True fconf=open(confPath,"r+") else: configFile=False if configFile==False: print ("Couldn't find the configuration file.") dialog=wx.MessageDialog(self,message="Couldn't find the configuration file", style=wx.OK|wx.CANCEL|wx.ICON_INFORMATION) dialog.ShowModal() wx.CallAfter(self.consolePrint,"\n"+"Couldn't find the configuration file."+"\n") print ("Attempting to read the configuration file...") #try: if configFile!=False: conf = configparser.ConfigParser() conf.read_file(fconf) #parse the config file if conf.has_option("gpicsync","timezone") == True: self.timezone=conf.get("gpicsync","timezone") if self.timezone=="": self.timezone=None print ("Timezone is :"+str(self.timezone)) if conf.has_option("gpicsync","UTCOffset") == True: self.utcOffset=conf.get("gpicsync","utcoffset") if conf.has_option("gpicsync","backup") == True: self.backup=eval(conf.get("gpicsync","backup")) if conf.has_option("gpicsync","urlGMaps") == True: self.urlGMaps=conf.get("gpicsync","urlGMaps") if conf.has_option("gpicsync","geonamesTags") == True: self.geonamesTags=eval(conf.get("gpicsync","geonamesTags")) if conf.has_option("gpicsync","interpolation") == True: self.interpolation=eval(conf.get("gpicsync","interpolation")) if conf.has_option("gpicsync","datesMustMatch") == True: self.datesMustMatch=eval(conf.get("gpicsync","datesMustMatch")) if conf.has_option("gpicsync","log") == True: self.log=eval(conf.get("gpicsync","log")) if conf.has_option("gpicsync","GMaps") == True: self.GMaps=eval(conf.get("gpicsync","GMaps")) if conf.has_option("gpicsync","UTCOffset") == True: self.utcOffset=conf.get("gpicsync","UTCOffset") if conf.has_option("gpicsync","maxTimeDifference") == True: self.maxTimeDifference=conf.get("gpicsync","maxTimeDifference") if conf.has_option("gpicsync","language") == True: self.language=conf.get("gpicsync","language") if conf.has_option("gpicsync","geonames_username") == True: geonames_username_fromConf=conf.get("gpicsync","geonames_username") print ("reading from conf file geonames_username", geonames_username_fromConf, type(geonames_username_fromConf)) if geonames_username_fromConf not in ["","gpicsync"]: self.geonames_username=geonames_username_fromConf print ("This unsername for geonames will be used:", self.geonames_username) if conf.has_option("gpicsync","geoname_nearbyplace") == True: self.geoname_nearbyplace=eval(conf.get("gpicsync","geoname_nearbyplace")) if conf.has_option("gpicsync","geoname_region") == True: self.geoname_region=eval(conf.get("gpicsync","geoname_region")) if conf.has_option("gpicsync","geoname_country") == True: self.geoname_country=eval(conf.get("gpicsync","geoname_country")) if conf.has_option("gpicsync","geoname_summary") == True: self.geoname_summary=eval(conf.get("gpicsync","geoname_summary")) if conf.has_option("gpicsync","geoname_userdefine") == True: self.geoname_userdefine=conf.get("gpicsync","geoname_userdefine") if conf.has_option("gpicsync","geoname_caption") == True: self.geoname_caption=eval(conf.get("gpicsync","geoname_caption")) if conf.has_option("gpicsync","geoname_IPTCsummary") == True: self.geoname_IPTCsummary=conf.get("gpicsync","geoname_IPTCsummary") if conf.has_option("gpicsync","defaultdirectory") == True: self.picDir=conf.get("gpicsync","defaultdirectory") if conf.has_option("gpicsync","getimestamp") == True: self.timeStamp=eval(conf.get("gpicsync","getimestamp")) fconf.close() print ("Finished reading the conf. file") #except: if 0: wx.CallAfter(self.consolePrint,"\n" +"An error happened while reading the configuration file."+"\n") try: #print self.language locale_dir="locale" if self.language=="system": lang = gettext.translation('gpicsync-GUI', locale_dir, codeset=codeset) lang.install(unicode=True) elif self.language=="French": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['fr'], codeset=codeset) lang.install(unicode=True) elif self.language=="Italian": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['it'], codeset=codeset) lang.install(unicode=True) elif self.language=="German": #lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['de'], codeset=codeset) lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['de']) lang.install(unicode=True) elif self.language=="S.Chinese": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['zh_CN'], codeset=codeset) lang.install(unicode=True) elif self.language=="T.Chinese": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['zh_TW'], codeset=codeset) lang.install(unicode=True) elif self.language=="Catalan": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['ca'], codeset=codeset) lang.install(unicode=True) elif self.language=="Spanish": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['es'], codeset=codeset) lang.install(unicode=True) elif self.language=="Polish": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['pl'], codeset=codeset) lang.install(unicode=True) elif self.language=="Dutch": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['nl'], codeset=codeset) lang.install(unicode=True) elif self.language=="Portuguese": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['pt'], codeset=codeset) lang.install(unicode=True) elif self.language=="Brazilian Portuguese": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['pt_BR'], codeset=codeset) lang.install(unicode=True) elif self.language=="Czech": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['cs'], codeset=codeset) lang.install(unicode=True) elif self.language=="Russian": lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['ru'], codeset=codeset) lang.install(unicode=True) else: gettext.install('gpicsync-GUI', "None",unicode=True) except: print ("Couldn't load translation.") del locale_dir ##### Menus ##### bkg=wx.Panel(self) #bkg.SetBackgroundColour((244,180,56)) statusBar=self.CreateStatusBar() menuBar=wx.MenuBar() menu1=wx.Menu() menuBar.Append(menu1,("&Options")) self._ltcID = wx.NewId() self._langID = wx.NewId() timeShift=menu1.Append(self._ltcID, "Local time correction", "Applies a local time correction") languageChoice=menu1.Append(self._langID, "Language", "Choose language") if sys.platform == 'win32': self._confID = wx.NewId() configFile=menu1.Append(self._confID,"Configuration file") self.Bind(wx.EVT_MENU,self.showConfig, id=self._confID) self.Bind(wx.EVT_MENU,self.localtimeFrame, id=self._ltcID) self.Bind(wx.EVT_MENU,self.languageApp, id=self._langID) menuTools=wx.Menu() menuBar.Append(menuTools,("&Tools")) self._erID = wx.NewId() self._egwID = wx.NewId() self._rtID = wx.NewId() self._giID = wx.NewId() self._kgID = wx.NewId() exifReader=menuTools.Append(self._erID, "EXIF reader") exifGeoWriter=menuTools.Append(self._egwID, "EXIF writer") renameToolMenu=menuTools.Append(self._rtID, "Geo-Rename pictures") gpxInspectorMenu=menuTools.Append(self._giID, "GPX Inspector") kmzGeneratorMenu=menuTools.Append(self._kgID, "KMZ Generator") self.Bind(wx.EVT_MENU,self.exifFrame, id=self._erID) self.Bind(wx.EVT_MENU,self.geoWriterFrame, id=self._egwID) self.Bind(wx.EVT_MENU,self.renameFrame, id=self._rtID) self.Bind(wx.EVT_MENU,self.gpxInspectorFrame, id=self._giID) self.Bind(wx.EVT_MENU,self.kmzGeneratorFrame, id=self._kgID) menu2=wx.Menu() menuBar.Append(menu2,("&Help")) self._aboutID = wx.NewId() about=menu2.Append(self._aboutID, "About...") self.Bind(wx.EVT_MENU,self.aboutApp, id=self._aboutID) ##### Mains panel widgets definitions ##### # Pictures dir and Gpx search buttons dirButton=wx.Button(bkg,size=(150,-1),label=("Pictures folder")) gpxButton=wx.Button(bkg,size=(150,-1),label=("GPS file")) self.dirEntry=wx.TextCtrl(bkg) self.gpxEntry=wx.TextCtrl(bkg) self.Bind(wx.EVT_BUTTON, self.findPictures, dirButton) self.Bind(wx.EVT_BUTTON, self.findGpx, gpxButton) # Commands buttons (sync,quit,stop,etc) syncButton=wx.Button(bkg,size=(250,-1),label=(" Synchronise ! ")) quitButton=wx.Button(bkg,label=("Quit"),size=(-1,-1)) quitAndSaveButton=wx.Button(bkg,label=("Quit and save settings"),size=(-1,-1)) stopButton=wx.Button(bkg,label=("Stop"),size=(-1,-1)) clearButton=wx.Button(bkg,label=("Clear"),size=(-1,-1)) if sys.platform != 'win32': viewInGEButton=wx.Button(bkg,label=("View in Google Earth"),size=(-1,-1)) self.Bind(wx.EVT_BUTTON, self.syncPictures, syncButton) self.Bind(wx.EVT_BUTTON, self.exitApp,quitButton) self.Bind(wx.EVT_BUTTON, self.exitAppSave,quitAndSaveButton) self.Bind(wx.EVT_BUTTON, self.stopApp,stopButton) self.Bind(wx.EVT_BUTTON, self.clearConsole,clearButton) if sys.platform != 'win32': self.Bind(wx.EVT_BUTTON, self.viewInGE,viewInGEButton) # Main Options box optionPrebox=wx.StaticBox(bkg, -1, ("Options:")) optionbox=wx.StaticBoxSizer(optionPrebox, wx.VERTICAL) # Elevation options eleLabel=wx.StaticText(bkg, -1," "+("Elevation")+":") eleList=[("Clamp to the ground"), ("absolute value (for flights)"),("absolute value + extrude (for flights)")] self.elevationChoice=wx.Choice(bkg, -1, (-1,-1), choices = eleList) self.elevationChoice.SetSelection(0) # Google Earth Icons choice iconsLabel=wx.StaticText(bkg, -1," "+("Icons")+":") iconsList=[("picture thumb"), ("camera icon")] self.iconsChoice=wx.Choice(bkg, -1, (-1,-1), choices = iconsList) self.iconsChoice.SetSelection(0) # Geonames options tmp1=("Geonames in specific IPTC fields") tmp2=("Geonames in XMP format") gnOptList=[("Geonames in IPTC + HTML Summary in IPTC caption"),("Geonames in IPTC"), ("Geonames/geotagged in EXIF keywords + HTML summary in IPTC caption"),("Geonames/geotagged in EXIF keywords")] self.gnOptChoice=wx.Choice(bkg, -1, (-1,-1), choices = gnOptList) self.gnOptChoice.SetSelection(0) # UTC value and timezone self.utcLabel = wx.StaticText(bkg, -1,("UTC Offset=")) self.utcEntry=wx.TextCtrl(bkg,size=(40,-1)) self.utcEntry.SetValue(self.utcOffset) if timezones: #if 1: tzLabel = wx.StaticText(bkg, -1,("Select time zone:")) self.tzButton = wx.Button(bkg, -1, ("Manual UTC offset"), size=(150,-1), style=wx.BU_LEFT) if self.timezone: self.tzButton.SetLabel(self.timezone) self.utcLabel.Disable() self.utcEntry.Disable() self.tzMenu = wx.Menu() self._mtzID = wx.NewId() manualTZmenu = self.tzMenu.Append(self._mtzID, "Manual UTC offset") self.Bind(wx.EVT_MENU, self.manualTZ, id=self._mtzID) tz_regions = {} for i,item in enumerate(timezones): items = item.split('/') reg = "" menu = self.tzMenu for r in items[:-1]: reg += '/' + r if reg not in tz_regions: newmenu = wx.Menu() menu.AppendMenu(-1, r, newmenu) menu = newmenu tz_regions[reg] = menu else: menu = tz_regions[reg] z = items[-1] menu.Append(3000+i, z) self.Bind(wx.EVT_MENU, self.selectTZ, id=3000+i) self.Bind(wx.EVT_BUTTON, self.tzMenuPopup, self.tzButton) # Timerange timerangeLabel=wx.StaticText(bkg, -1,("Geocode picture only if time difference to nearest track point is below (seconds)=")) self.timerangeEntry=wx.TextCtrl(bkg,size=(40,-1)) self.timerangeEntry.SetValue(self.maxTimeDifference) # Log file, dateCheck (deprecated) self.logFile=wx.CheckBox(bkg,-1,("Create a log file in picture folder")) self.logFile.SetValue(self.log) self.dateCheck=wx.CheckBox(bkg,-1,("Dates must match")) self.dateCheck.SetValue(self.datesMustMatch) self.dateCheck.Hide() # Google Earth and Google Maps self.geCheck=wx.CheckBox(bkg,-1,("Create a Google Earth file")+": ") self.geCheck.SetValue(True) self.geCheck.Hide() geInfoLabel=wx.StaticText(bkg, -1," "+"[Google Earth]->") self.geTStamps=wx.CheckBox(bkg,-1,("with TimeStamp")) self.geTStamps.SetValue(self.timeStamp) self.gmCheck=wx.CheckBox(bkg,-1,("Google Maps export, folder URL=")) self.gmCheck.SetValue(self.GMaps) self.urlEntry=wx.TextCtrl(bkg,size=(500,-1)) self.urlEntry.SetValue(self.urlGMaps) # backup, interpolations mod and geonames self.backupCheck=wx.CheckBox(bkg,-1,("backup pictures")) self.backupCheck.SetValue(self.backup) self.interpolationCheck=wx.CheckBox(bkg,-1,("interpolation")) self.interpolationCheck.SetValue(self.interpolation) self.geonamesCheck=wx.CheckBox(bkg,-1,("add geonames and geotagged")) self.geonamesCheck.SetValue(self.geonamesTags) self.Bind(wx.EVT_CHECKBOX,self.geonamesMessage,self.geonamesCheck) # Main output text console self.consoleEntry=wx.TextCtrl(bkg,style=wx.TE_MULTILINE | wx.HSCROLL) ##### GUI LAYOUT / SIZERS ##### # directory and GPX choices sizer dirChoiceBox=wx.BoxSizer() dirChoiceBox.Add(dirButton,proportion=0,flag=wx.LEFT,border=5) dirChoiceBox.Add(self.dirEntry,proportion=1,flag=wx.EXPAND) gpxChoiceBox=wx.BoxSizer() gpxChoiceBox.Add(gpxButton,proportion=0,flag=wx.LEFT,border=5) gpxChoiceBox.Add(self.gpxEntry,proportion=1,flag=wx.EXPAND) # Google Earth elevation and time stamp horizontal sizer gebox=wx.BoxSizer() gebox.Add(geInfoLabel,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL,border=10) gebox.Add(iconsLabel,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL, border=10) gebox.Add(self.iconsChoice,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL, border=10) gebox.Add(eleLabel,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL, border=10) gebox.Add(self.elevationChoice,flag= wx.LEFT|wx.ALIGN_CENTER_VERTICAL, border=10) gebox.Add(self.geTStamps,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL, border=10) # Google maps export and associated URL gmbox=wx.BoxSizer() gmbox.Add(self.gmCheck,proportion=0,flag=wx.EXPAND| wx.LEFT,border=10) gmbox.Add(self.urlEntry,proportion=0,flag=wx.EXPAND| wx.ALL,border=1) # line with log check, interpolation check and backup check settingsbox=wx.BoxSizer() settingsbox.Add(self.logFile,proportion=0,flag=wx.LEFT| wx.ALL,border=10) #settingsbox.Add(self.dateCheck,proportion=0,flag=wx.LEFT| wx.ALL,border=10) settingsbox.Add(self.interpolationCheck,proportion=0,flag=wx.LEFT| wx.ALL,border=10) settingsbox.Add(self.backupCheck,proportion=0,flag=wx.EXPAND| wx.ALL,border=10) # Image preview box prebox=wx.StaticBox(bkg, -1, ("Image preview:"),size=(200,200)) previewbox=wx.StaticBoxSizer(prebox, wx.VERTICAL) self.imgWhite=wx.Image('default.jpg', wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.imgPrev=wx.StaticBitmap(bkg,-1,self.imgWhite,size=(160,160))#style=wx.SIMPLE_BORDER previewbox.Add(self.imgPrev, 0, flag= wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_CENTER_HORIZONTAL,border=10) # Geonames line gnhbox=wx.BoxSizer() gnhbox.Add(self.geonamesCheck,proportion=0,flag=wx.EXPAND| wx.LEFT,border=10) gnhbox.Add(self.gnOptChoice,proportion=0,flag=wx.EXPAND| wx.LEFT,border=10) # UTC and timezone line utcBox=wx.BoxSizer() if timezones: utcBox.Add(tzLabel,proportion=0,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL,border=10) utcBox.Add(self.tzButton,proportion=0,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL,border=10) utcBox.Add(self.utcLabel,proportion=0,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL,border=10) utcBox.Add(self.utcEntry,proportion=0,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL,border=10) # Timerange line rangeBox = wx.BoxSizer() rangeBox.Add(timerangeLabel,proportion=0,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL,border=10) rangeBox.Add(self.timerangeEntry,proportion=0,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL,border=10) # commands line commandsBox=wx.BoxSizer() commandsBox.Add(syncButton,proportion=0,flag=wx.LEFT,border=5) commandsBox.Add(stopButton,proportion=0,flag=wx.LEFT,border=5) commandsBox.Add(clearButton,proportion=0,flag=wx.LEFT,border=5) if sys.platform != 'win32': commandsBox.Add(viewInGEButton,proportion=0,flag=wx.LEFT,border=5) commandsBox.Add(quitButton,proportion=0,flag=wx.LEFT,border=5) commandsBox.Add(quitAndSaveButton,proportion=0,flag=wx.LEFT,border=5) # select picture directory and GPX box headerbox=wx.BoxSizer(wx.VERTICAL) headerbox.Add(dirChoiceBox,proportion=0,flag=wx.EXPAND | wx.ALL,border=5) headerbox.Add(gpxChoiceBox,proportion=0,flag=wx.EXPAND | wx.ALL,border=5) optionbox.Add(gebox,proportion=0,flag=wx.ALL,border=7) optionbox.Add(gmbox,proportion=0,flag=wx.ALL,border=7) optionbox.Add(settingsbox,proportion=0,flag=wx.ALL,border=7) optionbox.Add(gnhbox,proportion=0,flag=wx.ALL,border=7) # Options box + picture preview sizer middlebox=wx.BoxSizer() middlebox.Add(optionbox,proportion=1,flag=wx.LEFT,border=15) middlebox.Add(previewbox,proportion=0,flag=wx.LEFT,border=20) footerbox=wx.BoxSizer(wx.VERTICAL) footerbox.Add(utcBox,proportion=0,flag=wx.EXPAND | wx.ALL,border=5) footerbox.Add(rangeBox,proportion=0,flag=wx.EXPAND | wx.ALL,border=5) footerbox.Add(commandsBox,proportion=0,flag=wx.EXPAND | wx.ALL,border=5) footerbox.Add(self.consoleEntry,proportion=1,flag=wx.EXPAND | wx.LEFT, border=5) allBox= wx.BoxSizer(wx.VERTICAL) allBox.Add(headerbox,proportion=0,flag=wx.EXPAND | wx.ALL,border=5) allBox.Add(middlebox,proportion=0,flag=wx.EXPAND | wx.ALL,border=5) allBox.Add(footerbox,proportion=1,flag=wx.EXPAND | wx.ALL,border=5) #bkg.SetSizer(vbox) bkg.SetSizer(allBox) self.SetMenuBar(menuBar) self.Show(True) if sys.platform == 'darwin': self.SetSize(self.GetSize()+(100,50)) if sys.platform == 'win32': self.exifcmd = 'exiftool.exe' else: self.exifcmd = 'exiftool' if self.geonamesTags==True: self.geonamesMessage(None)
[ "def", "__init__", "(", "self", ",", "parent", ",", "title", ")", ":", "global", "bkg", "wx", ".", "Frame", ".", "__init__", "(", "self", ",", "parent", ",", "wx", ".", "ID_ANY", ",", "title", "=", "\"GPicSync\"", ",", "size", "=", "(", "1000", ",", "600", ")", ")", "favicon", "=", "wx", ".", "Icon", "(", "'gpicsync.ico'", ",", "wx", ".", "BITMAP_TYPE_ICO", ",", "16", ",", "16", ")", "wx", ".", "Frame", ".", "SetIcon", "(", "self", ",", "favicon", ")", "self", ".", "tcam_l", "=", "\"00:00:00\"", "self", ".", "tgps_l", "=", "\"00:00:00\"", "self", ".", "log", "=", "False", "self", ".", "stop", "=", "False", "self", ".", "interpolation", "=", "False", "self", ".", "picDir", "=", "\"\"", "self", ".", "timezone", "=", "None", "self", ".", "utcOffset", "=", "\"0\"", "self", ".", "backup", "=", "True", "self", ".", "picDirDefault", "=", "\"\"", "self", ".", "GMaps", "=", "False", "self", ".", "urlGMaps", "=", "\"\"", "self", ".", "geonames_username", "=", "\"gpicsync\"", "self", ".", "geonamesTags", "=", "False", "self", ".", "geoname_nearbyplace", "=", "True", "self", ".", "geoname_region", "=", "True", "self", ".", "geoname_country", "=", "True", "self", ".", "geoname_summary", "=", "True", "self", ".", "geoname_caption", "=", "True", "self", ".", "datesMustMatch", "=", "True", "self", ".", "geoname_userdefine", "=", "\"\"", "self", ".", "maxTimeDifference", "=", "\"300\"", "self", ".", "language", "=", "\"English\"", "self", ".", "timeStamp", "=", "False", "self", ".", "defaultLat", "=", "\"0.000000\"", "self", ".", "defaultLon", "=", "\"0.000000\"", "self", ".", "geoname_IPTCsummary", "=", "\"\"", "# Search for an eventual gpicsync.conf file", "configFile", "=", "False", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "confPath", "=", "os", ".", "environ", "[", "\"ALLUSERSPROFILE\"", "]", "+", "\"/gpicsync.conf\"", "print", "(", "\"Searching configuration file \"", "+", "confPath", ")", "if", "os", ".", "path", ".", "isfile", "(", "confPath", ")", ":", "configFile", "=", "True", "fconf", "=", "open", "(", "os", ".", "environ", "[", "\"ALLUSERSPROFILE\"", "]", "+", "\"/gpicsync.conf\"", ",", "\"r+\"", ")", "else", ":", "configFile", "=", "False", "if", "sys", ".", "platform", "in", "[", "\"linux\"", ",", "\"darwin\"", "]", ":", "confPath", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/.gpicsync.conf\"", ")", "print", "(", "\"Searching configuration file ~/.gpicsync.conf\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "confPath", ")", ":", "configFile", "=", "True", "fconf", "=", "open", "(", "os", ".", "path", ".", "expanduser", "(", "\"~/.gpicsync.conf\"", ")", ",", "\"r+\"", ")", "else", ":", "confPath", "=", "\"./gpicsync.conf\"", "if", "os", ".", "path", ".", "isfile", "(", "confPath", ")", ":", "configFile", "=", "True", "fconf", "=", "open", "(", "confPath", ",", "\"r+\"", ")", "else", ":", "configFile", "=", "False", "if", "configFile", "==", "False", ":", "print", "(", "\"Couldn't find the configuration file.\"", ")", "dialog", "=", "wx", ".", "MessageDialog", "(", "self", ",", "message", "=", "\"Couldn't find the configuration file\"", ",", "style", "=", "wx", ".", "OK", "|", "wx", ".", "CANCEL", "|", "wx", ".", "ICON_INFORMATION", ")", "dialog", ".", "ShowModal", "(", ")", "wx", ".", "CallAfter", "(", "self", ".", "consolePrint", ",", "\"\\n\"", "+", "\"Couldn't find the configuration file.\"", "+", "\"\\n\"", ")", "print", "(", "\"Attempting to read the configuration file...\"", ")", "#try: ", "if", "configFile", "!=", "False", ":", "conf", "=", "configparser", ".", "ConfigParser", "(", ")", "conf", ".", "read_file", "(", "fconf", ")", "#parse the config file", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"timezone\"", ")", "==", "True", ":", "self", ".", "timezone", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"timezone\"", ")", "if", "self", ".", "timezone", "==", "\"\"", ":", "self", ".", "timezone", "=", "None", "print", "(", "\"Timezone is :\"", "+", "str", "(", "self", ".", "timezone", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"UTCOffset\"", ")", "==", "True", ":", "self", ".", "utcOffset", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"utcoffset\"", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"backup\"", ")", "==", "True", ":", "self", ".", "backup", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"backup\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"urlGMaps\"", ")", "==", "True", ":", "self", ".", "urlGMaps", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"urlGMaps\"", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"geonamesTags\"", ")", "==", "True", ":", "self", ".", "geonamesTags", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"geonamesTags\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"interpolation\"", ")", "==", "True", ":", "self", ".", "interpolation", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"interpolation\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"datesMustMatch\"", ")", "==", "True", ":", "self", ".", "datesMustMatch", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"datesMustMatch\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"log\"", ")", "==", "True", ":", "self", ".", "log", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"log\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"GMaps\"", ")", "==", "True", ":", "self", ".", "GMaps", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"GMaps\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"UTCOffset\"", ")", "==", "True", ":", "self", ".", "utcOffset", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"UTCOffset\"", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"maxTimeDifference\"", ")", "==", "True", ":", "self", ".", "maxTimeDifference", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"maxTimeDifference\"", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"language\"", ")", "==", "True", ":", "self", ".", "language", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"language\"", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"geonames_username\"", ")", "==", "True", ":", "geonames_username_fromConf", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"geonames_username\"", ")", "print", "(", "\"reading from conf file geonames_username\"", ",", "geonames_username_fromConf", ",", "type", "(", "geonames_username_fromConf", ")", ")", "if", "geonames_username_fromConf", "not", "in", "[", "\"\"", ",", "\"gpicsync\"", "]", ":", "self", ".", "geonames_username", "=", "geonames_username_fromConf", "print", "(", "\"This unsername for geonames will be used:\"", ",", "self", ".", "geonames_username", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"geoname_nearbyplace\"", ")", "==", "True", ":", "self", ".", "geoname_nearbyplace", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"geoname_nearbyplace\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"geoname_region\"", ")", "==", "True", ":", "self", ".", "geoname_region", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"geoname_region\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"geoname_country\"", ")", "==", "True", ":", "self", ".", "geoname_country", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"geoname_country\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"geoname_summary\"", ")", "==", "True", ":", "self", ".", "geoname_summary", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"geoname_summary\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"geoname_userdefine\"", ")", "==", "True", ":", "self", ".", "geoname_userdefine", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"geoname_userdefine\"", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"geoname_caption\"", ")", "==", "True", ":", "self", ".", "geoname_caption", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"geoname_caption\"", ")", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"geoname_IPTCsummary\"", ")", "==", "True", ":", "self", ".", "geoname_IPTCsummary", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"geoname_IPTCsummary\"", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"defaultdirectory\"", ")", "==", "True", ":", "self", ".", "picDir", "=", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"defaultdirectory\"", ")", "if", "conf", ".", "has_option", "(", "\"gpicsync\"", ",", "\"getimestamp\"", ")", "==", "True", ":", "self", ".", "timeStamp", "=", "eval", "(", "conf", ".", "get", "(", "\"gpicsync\"", ",", "\"getimestamp\"", ")", ")", "fconf", ".", "close", "(", ")", "print", "(", "\"Finished reading the conf. file\"", ")", "#except:", "if", "0", ":", "wx", ".", "CallAfter", "(", "self", ".", "consolePrint", ",", "\"\\n\"", "+", "\"An error happened while reading the configuration file.\"", "+", "\"\\n\"", ")", "try", ":", "#print self.language", "locale_dir", "=", "\"locale\"", "if", "self", ".", "language", "==", "\"system\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"French\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'fr'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"Italian\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'it'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"German\"", ":", "#lang = gettext.translation('gpicsync-GUI', locale_dir, languages=['de'], codeset=codeset)", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'de'", "]", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"S.Chinese\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'zh_CN'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"T.Chinese\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'zh_TW'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"Catalan\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'ca'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"Spanish\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'es'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"Polish\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'pl'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"Dutch\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'nl'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"Portuguese\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'pt'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"Brazilian Portuguese\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'pt_BR'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"Czech\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'cs'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "elif", "self", ".", "language", "==", "\"Russian\"", ":", "lang", "=", "gettext", ".", "translation", "(", "'gpicsync-GUI'", ",", "locale_dir", ",", "languages", "=", "[", "'ru'", "]", ",", "codeset", "=", "codeset", ")", "lang", ".", "install", "(", "unicode", "=", "True", ")", "else", ":", "gettext", ".", "install", "(", "'gpicsync-GUI'", ",", "\"None\"", ",", "unicode", "=", "True", ")", "except", ":", "print", "(", "\"Couldn't load translation.\"", ")", "del", "locale_dir", "##### Menus #####", "bkg", "=", "wx", ".", "Panel", "(", "self", ")", "#bkg.SetBackgroundColour((244,180,56))", "statusBar", "=", "self", ".", "CreateStatusBar", "(", ")", "menuBar", "=", "wx", ".", "MenuBar", "(", ")", "menu1", "=", "wx", ".", "Menu", "(", ")", "menuBar", ".", "Append", "(", "menu1", ",", "(", "\"&Options\"", ")", ")", "self", ".", "_ltcID", "=", "wx", ".", "NewId", "(", ")", "self", ".", "_langID", "=", "wx", ".", "NewId", "(", ")", "timeShift", "=", "menu1", ".", "Append", "(", "self", ".", "_ltcID", ",", "\"Local time correction\"", ",", "\"Applies a local time correction\"", ")", "languageChoice", "=", "menu1", ".", "Append", "(", "self", ".", "_langID", ",", "\"Language\"", ",", "\"Choose language\"", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "self", ".", "_confID", "=", "wx", ".", "NewId", "(", ")", "configFile", "=", "menu1", ".", "Append", "(", "self", ".", "_confID", ",", "\"Configuration file\"", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "showConfig", ",", "id", "=", "self", ".", "_confID", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "localtimeFrame", ",", "id", "=", "self", ".", "_ltcID", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "languageApp", ",", "id", "=", "self", ".", "_langID", ")", "menuTools", "=", "wx", ".", "Menu", "(", ")", "menuBar", ".", "Append", "(", "menuTools", ",", "(", "\"&Tools\"", ")", ")", "self", ".", "_erID", "=", "wx", ".", "NewId", "(", ")", "self", ".", "_egwID", "=", "wx", ".", "NewId", "(", ")", "self", ".", "_rtID", "=", "wx", ".", "NewId", "(", ")", "self", ".", "_giID", "=", "wx", ".", "NewId", "(", ")", "self", ".", "_kgID", "=", "wx", ".", "NewId", "(", ")", "exifReader", "=", "menuTools", ".", "Append", "(", "self", ".", "_erID", ",", "\"EXIF reader\"", ")", "exifGeoWriter", "=", "menuTools", ".", "Append", "(", "self", ".", "_egwID", ",", "\"EXIF writer\"", ")", "renameToolMenu", "=", "menuTools", ".", "Append", "(", "self", ".", "_rtID", ",", "\"Geo-Rename pictures\"", ")", "gpxInspectorMenu", "=", "menuTools", ".", "Append", "(", "self", ".", "_giID", ",", "\"GPX Inspector\"", ")", "kmzGeneratorMenu", "=", "menuTools", ".", "Append", "(", "self", ".", "_kgID", ",", "\"KMZ Generator\"", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "exifFrame", ",", "id", "=", "self", ".", "_erID", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "geoWriterFrame", ",", "id", "=", "self", ".", "_egwID", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "renameFrame", ",", "id", "=", "self", ".", "_rtID", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "gpxInspectorFrame", ",", "id", "=", "self", ".", "_giID", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "kmzGeneratorFrame", ",", "id", "=", "self", ".", "_kgID", ")", "menu2", "=", "wx", ".", "Menu", "(", ")", "menuBar", ".", "Append", "(", "menu2", ",", "(", "\"&Help\"", ")", ")", "self", ".", "_aboutID", "=", "wx", ".", "NewId", "(", ")", "about", "=", "menu2", ".", "Append", "(", "self", ".", "_aboutID", ",", "\"About...\"", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "aboutApp", ",", "id", "=", "self", ".", "_aboutID", ")", "##### Mains panel widgets definitions #####", "# Pictures dir and Gpx search buttons", "dirButton", "=", "wx", ".", "Button", "(", "bkg", ",", "size", "=", "(", "150", ",", "-", "1", ")", ",", "label", "=", "(", "\"Pictures folder\"", ")", ")", "gpxButton", "=", "wx", ".", "Button", "(", "bkg", ",", "size", "=", "(", "150", ",", "-", "1", ")", ",", "label", "=", "(", "\"GPS file\"", ")", ")", "self", ".", "dirEntry", "=", "wx", ".", "TextCtrl", "(", "bkg", ")", "self", ".", "gpxEntry", "=", "wx", ".", "TextCtrl", "(", "bkg", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "findPictures", ",", "dirButton", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "findGpx", ",", "gpxButton", ")", "# Commands buttons (sync,quit,stop,etc)", "syncButton", "=", "wx", ".", "Button", "(", "bkg", ",", "size", "=", "(", "250", ",", "-", "1", ")", ",", "label", "=", "(", "\" Synchronise ! \"", ")", ")", "quitButton", "=", "wx", ".", "Button", "(", "bkg", ",", "label", "=", "(", "\"Quit\"", ")", ",", "size", "=", "(", "-", "1", ",", "-", "1", ")", ")", "quitAndSaveButton", "=", "wx", ".", "Button", "(", "bkg", ",", "label", "=", "(", "\"Quit and save settings\"", ")", ",", "size", "=", "(", "-", "1", ",", "-", "1", ")", ")", "stopButton", "=", "wx", ".", "Button", "(", "bkg", ",", "label", "=", "(", "\"Stop\"", ")", ",", "size", "=", "(", "-", "1", ",", "-", "1", ")", ")", "clearButton", "=", "wx", ".", "Button", "(", "bkg", ",", "label", "=", "(", "\"Clear\"", ")", ",", "size", "=", "(", "-", "1", ",", "-", "1", ")", ")", "if", "sys", ".", "platform", "!=", "'win32'", ":", "viewInGEButton", "=", "wx", ".", "Button", "(", "bkg", ",", "label", "=", "(", "\"View in Google Earth\"", ")", ",", "size", "=", "(", "-", "1", ",", "-", "1", ")", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "syncPictures", ",", "syncButton", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "exitApp", ",", "quitButton", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "exitAppSave", ",", "quitAndSaveButton", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "stopApp", ",", "stopButton", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "clearConsole", ",", "clearButton", ")", "if", "sys", ".", "platform", "!=", "'win32'", ":", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "viewInGE", ",", "viewInGEButton", ")", "# Main Options box", "optionPrebox", "=", "wx", ".", "StaticBox", "(", "bkg", ",", "-", "1", ",", "(", "\"Options:\"", ")", ")", "optionbox", "=", "wx", ".", "StaticBoxSizer", "(", "optionPrebox", ",", "wx", ".", "VERTICAL", ")", "# Elevation options", "eleLabel", "=", "wx", ".", "StaticText", "(", "bkg", ",", "-", "1", ",", "\" \"", "+", "(", "\"Elevation\"", ")", "+", "\":\"", ")", "eleList", "=", "[", "(", "\"Clamp to the ground\"", ")", ",", "(", "\"absolute value (for flights)\"", ")", ",", "(", "\"absolute value + extrude (for flights)\"", ")", "]", "self", ".", "elevationChoice", "=", "wx", ".", "Choice", "(", "bkg", ",", "-", "1", ",", "(", "-", "1", ",", "-", "1", ")", ",", "choices", "=", "eleList", ")", "self", ".", "elevationChoice", ".", "SetSelection", "(", "0", ")", "# Google Earth Icons choice", "iconsLabel", "=", "wx", ".", "StaticText", "(", "bkg", ",", "-", "1", ",", "\" \"", "+", "(", "\"Icons\"", ")", "+", "\":\"", ")", "iconsList", "=", "[", "(", "\"picture thumb\"", ")", ",", "(", "\"camera icon\"", ")", "]", "self", ".", "iconsChoice", "=", "wx", ".", "Choice", "(", "bkg", ",", "-", "1", ",", "(", "-", "1", ",", "-", "1", ")", ",", "choices", "=", "iconsList", ")", "self", ".", "iconsChoice", ".", "SetSelection", "(", "0", ")", "# Geonames options", "tmp1", "=", "(", "\"Geonames in specific IPTC fields\"", ")", "tmp2", "=", "(", "\"Geonames in XMP format\"", ")", "gnOptList", "=", "[", "(", "\"Geonames in IPTC + HTML Summary in IPTC caption\"", ")", ",", "(", "\"Geonames in IPTC\"", ")", ",", "(", "\"Geonames/geotagged in EXIF keywords + HTML summary in IPTC caption\"", ")", ",", "(", "\"Geonames/geotagged in EXIF keywords\"", ")", "]", "self", ".", "gnOptChoice", "=", "wx", ".", "Choice", "(", "bkg", ",", "-", "1", ",", "(", "-", "1", ",", "-", "1", ")", ",", "choices", "=", "gnOptList", ")", "self", ".", "gnOptChoice", ".", "SetSelection", "(", "0", ")", "# UTC value and timezone", "self", ".", "utcLabel", "=", "wx", ".", "StaticText", "(", "bkg", ",", "-", "1", ",", "(", "\"UTC Offset=\"", ")", ")", "self", ".", "utcEntry", "=", "wx", ".", "TextCtrl", "(", "bkg", ",", "size", "=", "(", "40", ",", "-", "1", ")", ")", "self", ".", "utcEntry", ".", "SetValue", "(", "self", ".", "utcOffset", ")", "if", "timezones", ":", "#if 1:", "tzLabel", "=", "wx", ".", "StaticText", "(", "bkg", ",", "-", "1", ",", "(", "\"Select time zone:\"", ")", ")", "self", ".", "tzButton", "=", "wx", ".", "Button", "(", "bkg", ",", "-", "1", ",", "(", "\"Manual UTC offset\"", ")", ",", "size", "=", "(", "150", ",", "-", "1", ")", ",", "style", "=", "wx", ".", "BU_LEFT", ")", "if", "self", ".", "timezone", ":", "self", ".", "tzButton", ".", "SetLabel", "(", "self", ".", "timezone", ")", "self", ".", "utcLabel", ".", "Disable", "(", ")", "self", ".", "utcEntry", ".", "Disable", "(", ")", "self", ".", "tzMenu", "=", "wx", ".", "Menu", "(", ")", "self", ".", "_mtzID", "=", "wx", ".", "NewId", "(", ")", "manualTZmenu", "=", "self", ".", "tzMenu", ".", "Append", "(", "self", ".", "_mtzID", ",", "\"Manual UTC offset\"", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "manualTZ", ",", "id", "=", "self", ".", "_mtzID", ")", "tz_regions", "=", "{", "}", "for", "i", ",", "item", "in", "enumerate", "(", "timezones", ")", ":", "items", "=", "item", ".", "split", "(", "'/'", ")", "reg", "=", "\"\"", "menu", "=", "self", ".", "tzMenu", "for", "r", "in", "items", "[", ":", "-", "1", "]", ":", "reg", "+=", "'/'", "+", "r", "if", "reg", "not", "in", "tz_regions", ":", "newmenu", "=", "wx", ".", "Menu", "(", ")", "menu", ".", "AppendMenu", "(", "-", "1", ",", "r", ",", "newmenu", ")", "menu", "=", "newmenu", "tz_regions", "[", "reg", "]", "=", "menu", "else", ":", "menu", "=", "tz_regions", "[", "reg", "]", "z", "=", "items", "[", "-", "1", "]", "menu", ".", "Append", "(", "3000", "+", "i", ",", "z", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_MENU", ",", "self", ".", "selectTZ", ",", "id", "=", "3000", "+", "i", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_BUTTON", ",", "self", ".", "tzMenuPopup", ",", "self", ".", "tzButton", ")", "# Timerange", "timerangeLabel", "=", "wx", ".", "StaticText", "(", "bkg", ",", "-", "1", ",", "(", "\"Geocode picture only if time difference to nearest track point is below (seconds)=\"", ")", ")", "self", ".", "timerangeEntry", "=", "wx", ".", "TextCtrl", "(", "bkg", ",", "size", "=", "(", "40", ",", "-", "1", ")", ")", "self", ".", "timerangeEntry", ".", "SetValue", "(", "self", ".", "maxTimeDifference", ")", "# Log file, dateCheck (deprecated)", "self", ".", "logFile", "=", "wx", ".", "CheckBox", "(", "bkg", ",", "-", "1", ",", "(", "\"Create a log file in picture folder\"", ")", ")", "self", ".", "logFile", ".", "SetValue", "(", "self", ".", "log", ")", "self", ".", "dateCheck", "=", "wx", ".", "CheckBox", "(", "bkg", ",", "-", "1", ",", "(", "\"Dates must match\"", ")", ")", "self", ".", "dateCheck", ".", "SetValue", "(", "self", ".", "datesMustMatch", ")", "self", ".", "dateCheck", ".", "Hide", "(", ")", "# Google Earth and Google Maps", "self", ".", "geCheck", "=", "wx", ".", "CheckBox", "(", "bkg", ",", "-", "1", ",", "(", "\"Create a Google Earth file\"", ")", "+", "\": \"", ")", "self", ".", "geCheck", ".", "SetValue", "(", "True", ")", "self", ".", "geCheck", ".", "Hide", "(", ")", "geInfoLabel", "=", "wx", ".", "StaticText", "(", "bkg", ",", "-", "1", ",", "\" \"", "+", "\"[Google Earth]->\"", ")", "self", ".", "geTStamps", "=", "wx", ".", "CheckBox", "(", "bkg", ",", "-", "1", ",", "(", "\"with TimeStamp\"", ")", ")", "self", ".", "geTStamps", ".", "SetValue", "(", "self", ".", "timeStamp", ")", "self", ".", "gmCheck", "=", "wx", ".", "CheckBox", "(", "bkg", ",", "-", "1", ",", "(", "\"Google Maps export, folder URL=\"", ")", ")", "self", ".", "gmCheck", ".", "SetValue", "(", "self", ".", "GMaps", ")", "self", ".", "urlEntry", "=", "wx", ".", "TextCtrl", "(", "bkg", ",", "size", "=", "(", "500", ",", "-", "1", ")", ")", "self", ".", "urlEntry", ".", "SetValue", "(", "self", ".", "urlGMaps", ")", "# backup, interpolations mod and geonames", "self", ".", "backupCheck", "=", "wx", ".", "CheckBox", "(", "bkg", ",", "-", "1", ",", "(", "\"backup pictures\"", ")", ")", "self", ".", "backupCheck", ".", "SetValue", "(", "self", ".", "backup", ")", "self", ".", "interpolationCheck", "=", "wx", ".", "CheckBox", "(", "bkg", ",", "-", "1", ",", "(", "\"interpolation\"", ")", ")", "self", ".", "interpolationCheck", ".", "SetValue", "(", "self", ".", "interpolation", ")", "self", ".", "geonamesCheck", "=", "wx", ".", "CheckBox", "(", "bkg", ",", "-", "1", ",", "(", "\"add geonames and geotagged\"", ")", ")", "self", ".", "geonamesCheck", ".", "SetValue", "(", "self", ".", "geonamesTags", ")", "self", ".", "Bind", "(", "wx", ".", "EVT_CHECKBOX", ",", "self", ".", "geonamesMessage", ",", "self", ".", "geonamesCheck", ")", "# Main output text console", "self", ".", "consoleEntry", "=", "wx", ".", "TextCtrl", "(", "bkg", ",", "style", "=", "wx", ".", "TE_MULTILINE", "|", "wx", ".", "HSCROLL", ")", "##### GUI LAYOUT / SIZERS #####", "# directory and GPX choices sizer", "dirChoiceBox", "=", "wx", ".", "BoxSizer", "(", ")", "dirChoiceBox", ".", "Add", "(", "dirButton", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "5", ")", "dirChoiceBox", ".", "Add", "(", "self", ".", "dirEntry", ",", "proportion", "=", "1", ",", "flag", "=", "wx", ".", "EXPAND", ")", "gpxChoiceBox", "=", "wx", ".", "BoxSizer", "(", ")", "gpxChoiceBox", ".", "Add", "(", "gpxButton", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "5", ")", "gpxChoiceBox", ".", "Add", "(", "self", ".", "gpxEntry", ",", "proportion", "=", "1", ",", "flag", "=", "wx", ".", "EXPAND", ")", "# Google Earth elevation and time stamp horizontal sizer", "gebox", "=", "wx", ".", "BoxSizer", "(", ")", "gebox", ".", "Add", "(", "geInfoLabel", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "gebox", ".", "Add", "(", "iconsLabel", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "gebox", ".", "Add", "(", "self", ".", "iconsChoice", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "gebox", ".", "Add", "(", "eleLabel", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "gebox", ".", "Add", "(", "self", ".", "elevationChoice", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "gebox", ".", "Add", "(", "self", ".", "geTStamps", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "# Google maps export and associated URL", "gmbox", "=", "wx", ".", "BoxSizer", "(", ")", "gmbox", ".", "Add", "(", "self", ".", "gmCheck", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "LEFT", ",", "border", "=", "10", ")", "gmbox", ".", "Add", "(", "self", ".", "urlEntry", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "1", ")", "# line with log check, interpolation check and backup check", "settingsbox", "=", "wx", ".", "BoxSizer", "(", ")", "settingsbox", ".", "Add", "(", "self", ".", "logFile", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALL", ",", "border", "=", "10", ")", "#settingsbox.Add(self.dateCheck,proportion=0,flag=wx.LEFT| wx.ALL,border=10)", "settingsbox", ".", "Add", "(", "self", ".", "interpolationCheck", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALL", ",", "border", "=", "10", ")", "settingsbox", ".", "Add", "(", "self", ".", "backupCheck", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "10", ")", "# Image preview box", "prebox", "=", "wx", ".", "StaticBox", "(", "bkg", ",", "-", "1", ",", "(", "\"Image preview:\"", ")", ",", "size", "=", "(", "200", ",", "200", ")", ")", "previewbox", "=", "wx", ".", "StaticBoxSizer", "(", "prebox", ",", "wx", ".", "VERTICAL", ")", "self", ".", "imgWhite", "=", "wx", ".", "Image", "(", "'default.jpg'", ",", "wx", ".", "BITMAP_TYPE_ANY", ")", ".", "ConvertToBitmap", "(", ")", "self", ".", "imgPrev", "=", "wx", ".", "StaticBitmap", "(", "bkg", ",", "-", "1", ",", "self", ".", "imgWhite", ",", "size", "=", "(", "160", ",", "160", ")", ")", "#style=wx.SIMPLE_BORDER", "previewbox", ".", "Add", "(", "self", ".", "imgPrev", ",", "0", ",", "flag", "=", "wx", ".", "ALIGN_CENTER_VERTICAL", "|", "wx", ".", "ALIGN_CENTER_HORIZONTAL", ",", "border", "=", "10", ")", "# Geonames line", "gnhbox", "=", "wx", ".", "BoxSizer", "(", ")", "gnhbox", ".", "Add", "(", "self", ".", "geonamesCheck", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "LEFT", ",", "border", "=", "10", ")", "gnhbox", ".", "Add", "(", "self", ".", "gnOptChoice", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "LEFT", ",", "border", "=", "10", ")", "# UTC and timezone line", "utcBox", "=", "wx", ".", "BoxSizer", "(", ")", "if", "timezones", ":", "utcBox", ".", "Add", "(", "tzLabel", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "utcBox", ".", "Add", "(", "self", ".", "tzButton", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "utcBox", ".", "Add", "(", "self", ".", "utcLabel", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "utcBox", ".", "Add", "(", "self", ".", "utcEntry", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "# Timerange line", "rangeBox", "=", "wx", ".", "BoxSizer", "(", ")", "rangeBox", ".", "Add", "(", "timerangeLabel", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "rangeBox", ".", "Add", "(", "self", ".", "timerangeEntry", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", "|", "wx", ".", "ALIGN_CENTER_VERTICAL", ",", "border", "=", "10", ")", "# commands line", "commandsBox", "=", "wx", ".", "BoxSizer", "(", ")", "commandsBox", ".", "Add", "(", "syncButton", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "5", ")", "commandsBox", ".", "Add", "(", "stopButton", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "5", ")", "commandsBox", ".", "Add", "(", "clearButton", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "5", ")", "if", "sys", ".", "platform", "!=", "'win32'", ":", "commandsBox", ".", "Add", "(", "viewInGEButton", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "5", ")", "commandsBox", ".", "Add", "(", "quitButton", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "5", ")", "commandsBox", ".", "Add", "(", "quitAndSaveButton", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "5", ")", "# select picture directory and GPX box", "headerbox", "=", "wx", ".", "BoxSizer", "(", "wx", ".", "VERTICAL", ")", "headerbox", ".", "Add", "(", "dirChoiceBox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "5", ")", "headerbox", ".", "Add", "(", "gpxChoiceBox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "5", ")", "optionbox", ".", "Add", "(", "gebox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "ALL", ",", "border", "=", "7", ")", "optionbox", ".", "Add", "(", "gmbox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "ALL", ",", "border", "=", "7", ")", "optionbox", ".", "Add", "(", "settingsbox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "ALL", ",", "border", "=", "7", ")", "optionbox", ".", "Add", "(", "gnhbox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "ALL", ",", "border", "=", "7", ")", "# Options box + picture preview sizer", "middlebox", "=", "wx", ".", "BoxSizer", "(", ")", "middlebox", ".", "Add", "(", "optionbox", ",", "proportion", "=", "1", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "15", ")", "middlebox", ".", "Add", "(", "previewbox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "LEFT", ",", "border", "=", "20", ")", "footerbox", "=", "wx", ".", "BoxSizer", "(", "wx", ".", "VERTICAL", ")", "footerbox", ".", "Add", "(", "utcBox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "5", ")", "footerbox", ".", "Add", "(", "rangeBox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "5", ")", "footerbox", ".", "Add", "(", "commandsBox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "5", ")", "footerbox", ".", "Add", "(", "self", ".", "consoleEntry", ",", "proportion", "=", "1", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "LEFT", ",", "border", "=", "5", ")", "allBox", "=", "wx", ".", "BoxSizer", "(", "wx", ".", "VERTICAL", ")", "allBox", ".", "Add", "(", "headerbox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "5", ")", "allBox", ".", "Add", "(", "middlebox", ",", "proportion", "=", "0", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "5", ")", "allBox", ".", "Add", "(", "footerbox", ",", "proportion", "=", "1", ",", "flag", "=", "wx", ".", "EXPAND", "|", "wx", ".", "ALL", ",", "border", "=", "5", ")", "#bkg.SetSizer(vbox)", "bkg", ".", "SetSizer", "(", "allBox", ")", "self", ".", "SetMenuBar", "(", "menuBar", ")", "self", ".", "Show", "(", "True", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "self", ".", "SetSize", "(", "self", ".", "GetSize", "(", ")", "+", "(", "100", ",", "50", ")", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "self", ".", "exifcmd", "=", "'exiftool.exe'", "else", ":", "self", ".", "exifcmd", "=", "'exiftool'", "if", "self", ".", "geonamesTags", "==", "True", ":", "self", ".", "geonamesMessage", "(", "None", ")" ]
https://github.com/FrancoisSchnell/GPicSync/blob/07d7c4b7da44e4e6665abb94bbb9ef6da0e779d1/src/gpicsync-GUI.py#L84-L534
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
apache/datadog_checks/apache/config_models/defaults.py
python
instance_auth_type
(field, value)
return 'basic'
[]
def instance_auth_type(field, value): return 'basic'
[ "def", "instance_auth_type", "(", "field", ",", "value", ")", ":", "return", "'basic'" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/apache/datadog_checks/apache/config_models/defaults.py#L37-L38
AndrewAnnex/SpiceyPy
9f8b626338f119bacd39ef2ba94a6f71bd6341c0
src/spiceypy/spiceypy.py
python
pjelpl
(elin: Ellipse, plane: Plane)
return elout
Project an ellipse onto a plane, orthogonally. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pjelpl_c.html :param elin: A SPICE ellipse to be projected. :param plane: A plane onto which elin is to be projected. :return: A SPICE ellipse resulting from the projection.
Project an ellipse onto a plane, orthogonally.
[ "Project", "an", "ellipse", "onto", "a", "plane", "orthogonally", "." ]
def pjelpl(elin: Ellipse, plane: Plane) -> Ellipse: """ Project an ellipse onto a plane, orthogonally. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pjelpl_c.html :param elin: A SPICE ellipse to be projected. :param plane: A plane onto which elin is to be projected. :return: A SPICE ellipse resulting from the projection. """ assert isinstance(elin, stypes.Ellipse) assert isinstance(plane, stypes.Plane) elout = stypes.Ellipse() libspice.pjelpl_c(ctypes.byref(elin), ctypes.byref(plane), ctypes.byref(elout)) return elout
[ "def", "pjelpl", "(", "elin", ":", "Ellipse", ",", "plane", ":", "Plane", ")", "->", "Ellipse", ":", "assert", "isinstance", "(", "elin", ",", "stypes", ".", "Ellipse", ")", "assert", "isinstance", "(", "plane", ",", "stypes", ".", "Plane", ")", "elout", "=", "stypes", ".", "Ellipse", "(", ")", "libspice", ".", "pjelpl_c", "(", "ctypes", ".", "byref", "(", "elin", ")", ",", "ctypes", ".", "byref", "(", "plane", ")", ",", "ctypes", ".", "byref", "(", "elout", ")", ")", "return", "elout" ]
https://github.com/AndrewAnnex/SpiceyPy/blob/9f8b626338f119bacd39ef2ba94a6f71bd6341c0/src/spiceypy/spiceypy.py#L9760-L9774
openai/iaf
ad33fe4872bf6e4b4f387e709a625376bb8b0d9d
tf_train.py
python
run
(hps)
[]
def run(hps): with tf.variable_scope("model") as vs: x = get_inputs(hps.dataset, "train", hps.batch_size * FLAGS.num_gpus, hps.image_size) hps.num_gpus = 1 init_x = x[:hps.batch_size, :, :, :] init_model = CVAE1(hps, "init", init_x) vs.reuse_variables() hps.num_gpus = FLAGS.num_gpus model = CVAE1(hps, "train", x) saver = tf.train.Saver() total_size = 0 for v in tf.trainable_variables(): total_size += np.prod([int(s) for s in v.get_shape()]) print("Num trainable variables: %d" % total_size) init_op = tf.initialize_all_variables() def init_fn(ses): print("Initializing parameters.") # XXX(rafal): TensorFlow bug?? Default initializer should handle things well.. ses.run(init_model.h_top.initializer) ses.run(init_op) print("Initialized!") sv = NotBuggySupervisor(is_chief=True, logdir=FLAGS.logdir + "/train", summary_op=None, # Automatic summaries don"t work with placeholders. saver=saver, global_step=model.global_step, save_summaries_secs=30, save_model_secs=0, init_op=None, init_fn=init_fn) print("starting training") local_step = 0 begin = time.time() config = tf.ConfigProto(allow_soft_placement=True) with sv.managed_session(config=config) as sess: print("Running first iteration!") while not sv.should_stop(): fetches = [model.bits_per_dim, model.global_step, model.dec_log_stdv, model.train_op] should_compute_summary = (local_step % 20 == 19) if should_compute_summary: fetches += [model.summary_op] fetched = sess.run(fetches) if should_compute_summary: sv.summary_computed(sess, fetched[-1]) if local_step < 10 or should_compute_summary: print("Iteration %d, time = %.2fs, train bits_per_dim = %.4f, dec_log_stdv = %.4f" % ( fetched[1], time.time() - begin, fetched[0], fetched[2])) begin = time.time() if np.isnan(fetched[0]): print("NAN detected!") break if local_step % 100 == 0: saver.save(sess, sv.save_path, global_step=sv.global_step, write_meta_graph=False) local_step += 1 sv.stop()
[ "def", "run", "(", "hps", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"model\"", ")", "as", "vs", ":", "x", "=", "get_inputs", "(", "hps", ".", "dataset", ",", "\"train\"", ",", "hps", ".", "batch_size", "*", "FLAGS", ".", "num_gpus", ",", "hps", ".", "image_size", ")", "hps", ".", "num_gpus", "=", "1", "init_x", "=", "x", "[", ":", "hps", ".", "batch_size", ",", ":", ",", ":", ",", ":", "]", "init_model", "=", "CVAE1", "(", "hps", ",", "\"init\"", ",", "init_x", ")", "vs", ".", "reuse_variables", "(", ")", "hps", ".", "num_gpus", "=", "FLAGS", ".", "num_gpus", "model", "=", "CVAE1", "(", "hps", ",", "\"train\"", ",", "x", ")", "saver", "=", "tf", ".", "train", ".", "Saver", "(", ")", "total_size", "=", "0", "for", "v", "in", "tf", ".", "trainable_variables", "(", ")", ":", "total_size", "+=", "np", ".", "prod", "(", "[", "int", "(", "s", ")", "for", "s", "in", "v", ".", "get_shape", "(", ")", "]", ")", "print", "(", "\"Num trainable variables: %d\"", "%", "total_size", ")", "init_op", "=", "tf", ".", "initialize_all_variables", "(", ")", "def", "init_fn", "(", "ses", ")", ":", "print", "(", "\"Initializing parameters.\"", ")", "# XXX(rafal): TensorFlow bug?? Default initializer should handle things well..", "ses", ".", "run", "(", "init_model", ".", "h_top", ".", "initializer", ")", "ses", ".", "run", "(", "init_op", ")", "print", "(", "\"Initialized!\"", ")", "sv", "=", "NotBuggySupervisor", "(", "is_chief", "=", "True", ",", "logdir", "=", "FLAGS", ".", "logdir", "+", "\"/train\"", ",", "summary_op", "=", "None", ",", "# Automatic summaries don\"t work with placeholders.", "saver", "=", "saver", ",", "global_step", "=", "model", ".", "global_step", ",", "save_summaries_secs", "=", "30", ",", "save_model_secs", "=", "0", ",", "init_op", "=", "None", ",", "init_fn", "=", "init_fn", ")", "print", "(", "\"starting training\"", ")", "local_step", "=", "0", "begin", "=", "time", ".", "time", "(", ")", "config", "=", "tf", ".", "ConfigProto", "(", "allow_soft_placement", "=", "True", ")", "with", "sv", ".", "managed_session", "(", "config", "=", "config", ")", "as", "sess", ":", "print", "(", "\"Running first iteration!\"", ")", "while", "not", "sv", ".", "should_stop", "(", ")", ":", "fetches", "=", "[", "model", ".", "bits_per_dim", ",", "model", ".", "global_step", ",", "model", ".", "dec_log_stdv", ",", "model", ".", "train_op", "]", "should_compute_summary", "=", "(", "local_step", "%", "20", "==", "19", ")", "if", "should_compute_summary", ":", "fetches", "+=", "[", "model", ".", "summary_op", "]", "fetched", "=", "sess", ".", "run", "(", "fetches", ")", "if", "should_compute_summary", ":", "sv", ".", "summary_computed", "(", "sess", ",", "fetched", "[", "-", "1", "]", ")", "if", "local_step", "<", "10", "or", "should_compute_summary", ":", "print", "(", "\"Iteration %d, time = %.2fs, train bits_per_dim = %.4f, dec_log_stdv = %.4f\"", "%", "(", "fetched", "[", "1", "]", ",", "time", ".", "time", "(", ")", "-", "begin", ",", "fetched", "[", "0", "]", ",", "fetched", "[", "2", "]", ")", ")", "begin", "=", "time", ".", "time", "(", ")", "if", "np", ".", "isnan", "(", "fetched", "[", "0", "]", ")", ":", "print", "(", "\"NAN detected!\"", ")", "break", "if", "local_step", "%", "100", "==", "0", ":", "saver", ".", "save", "(", "sess", ",", "sv", ".", "save_path", ",", "global_step", "=", "sv", ".", "global_step", ",", "write_meta_graph", "=", "False", ")", "local_step", "+=", "1", "sv", ".", "stop", "(", ")" ]
https://github.com/openai/iaf/blob/ad33fe4872bf6e4b4f387e709a625376bb8b0d9d/tf_train.py#L222-L290
deepgully/me
f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0
libs/sqlalchemy/sql/compiler.py
python
Compiled.__init__
(self, dialect, statement, bind=None, compile_kwargs=util.immutabledict())
Construct a new ``Compiled`` object. :param dialect: ``Dialect`` to compile against. :param statement: ``ClauseElement`` to be compiled. :param bind: Optional Engine or Connection to compile this statement against. :param compile_kwargs: additional kwargs that will be passed to the initial call to :meth:`.Compiled.process`. .. versionadded:: 0.8
Construct a new ``Compiled`` object.
[ "Construct", "a", "new", "Compiled", "object", "." ]
def __init__(self, dialect, statement, bind=None, compile_kwargs=util.immutabledict()): """Construct a new ``Compiled`` object. :param dialect: ``Dialect`` to compile against. :param statement: ``ClauseElement`` to be compiled. :param bind: Optional Engine or Connection to compile this statement against. :param compile_kwargs: additional kwargs that will be passed to the initial call to :meth:`.Compiled.process`. .. versionadded:: 0.8 """ self.dialect = dialect self.bind = bind if statement is not None: self.statement = statement self.can_execute = statement.supports_execution self.string = self.process(self.statement, **compile_kwargs)
[ "def", "__init__", "(", "self", ",", "dialect", ",", "statement", ",", "bind", "=", "None", ",", "compile_kwargs", "=", "util", ".", "immutabledict", "(", ")", ")", ":", "self", ".", "dialect", "=", "dialect", "self", ".", "bind", "=", "bind", "if", "statement", "is", "not", "None", ":", "self", ".", "statement", "=", "statement", "self", ".", "can_execute", "=", "statement", ".", "supports_execution", "self", ".", "string", "=", "self", ".", "process", "(", "self", ".", "statement", ",", "*", "*", "compile_kwargs", ")" ]
https://github.com/deepgully/me/blob/f7ad65edc2fe435310c6676bc2e322cfe5d4c8f0/libs/sqlalchemy/sql/compiler.py#L174-L197
NervanaSystems/ngraph-python
ac032c83c7152b615a9ad129d54d350f9d6a2986
ngraph/transformers/gpu/float_ew2.py
python
_generate_kernel_args
(ops, axes_mapping, dims, ctx)
return (args, arg_desc, params)
Generates a list of parameters which need to be passed to the CUDA kernel at runtime along with strings to represent them in C Argument order for kernels is standardized: 1. Tensor shape (max shape) 2. Tensor inputs/outputs pointers in the order op1_arg1, op1_arg2, op1_out, op2_arg1,... 2a. First value for each input/output is a pointer 2b. Second value for each input/output is strides 2c. (Optional) flex scale for and/or flex stats for flex output Arguments: ops (list): List of op descriptions for which to generate kernel axes_mapping (list): Mapping between tensor axes and kernel block dimensions dims (int): Number of dimensions used by the kernel ctx (GenerationContext): Context containing kernel specific data structures for register mapping, etc Returns: List of parameters and arguments and descriptor string for pycuda kernel compiler
Generates a list of parameters which need to be passed to the CUDA kernel at runtime along with strings to represent them in C
[ "Generates", "a", "list", "of", "parameters", "which", "need", "to", "be", "passed", "to", "the", "CUDA", "kernel", "at", "runtime", "along", "with", "strings", "to", "represent", "them", "in", "C" ]
def _generate_kernel_args(ops, axes_mapping, dims, ctx): """ Generates a list of parameters which need to be passed to the CUDA kernel at runtime along with strings to represent them in C Argument order for kernels is standardized: 1. Tensor shape (max shape) 2. Tensor inputs/outputs pointers in the order op1_arg1, op1_arg2, op1_out, op2_arg1,... 2a. First value for each input/output is a pointer 2b. Second value for each input/output is strides 2c. (Optional) flex scale for and/or flex stats for flex output Arguments: ops (list): List of op descriptions for which to generate kernel axes_mapping (list): Mapping between tensor axes and kernel block dimensions dims (int): Number of dimensions used by the kernel ctx (GenerationContext): Context containing kernel specific data structures for register mapping, etc Returns: List of parameters and arguments and descriptor string for pycuda kernel compiler """ # List arguments to kernel args = ["unsigned int shapea"] arg_desc = "I" params = [axes_mapping[0][4]] if dims == 2: args.append("unsigned int shapeb") arg_desc = arg_desc + "I" params.append(axes_mapping[1][4]) elif dims == 3: args.extend(["unsigned int shapeb", "unsigned int shapec"]) arg_desc = arg_desc + "II" params.extend([axes_mapping[1][4], axes_mapping[2][4]]) num_constants = 0 processed_tensors = set() for op in ops: for tensor in op[1:4]: from ngraph.transformers.gputransform import GPURegister if tensor is None or isinstance(tensor, GPURegister): continue if isinstance(tensor, TensorDescriptionWrapper) and tensor not in processed_tensors: # Tensor is buffer in memory regname = ctx.register_mapping[tensor] bufname = ctx.buffers[tensor] args.append(_get_register_type(tensor.dtype, True) + "* " + bufname) args.append("unsigned int stridea_" + bufname) arg_desc = arg_desc + "PI" params.append(tensor.td) params.append(tensor.strides[0]) if dims == 2: args.append("unsigned int strideb_" + bufname) arg_desc = arg_desc + "I" params.append(tensor.strides[1]) elif dims == 3: args.append("unsigned int strideb_" + bufname) args.append("unsigned int stridec_" + bufname) arg_desc = arg_desc + "II" params.append(tensor.strides[1]) params.append(tensor.strides[2]) if isinstance(tensor, TensorDescriptionWrapper) and tensor.is_flex(): argname, flex_entry, is_output = ctx.flex_scale[regname] args.append("float " + argname) arg_desc = arg_desc + "f" # create description of flex scale parameters that will be bound later params.append(FlexScaleDescription(flex_entry, is_output)) if tensor is op[3]: # This is an output so we also need flex stats args.append("int* flex_stats") arg_desc = arg_desc + "P" params.append(ctx.flex_stats_ptr) else: # Must be a constant value regname = "constant" + str(num_constants) regtype = ctx.register_types[regname] num_constants += 1 args.append(regtype + " " + regname) if regtype == "float": arg_desc = arg_desc + "f" else: arg_desc = arg_desc + "i" params.append(tensor) return (args, arg_desc, params)
[ "def", "_generate_kernel_args", "(", "ops", ",", "axes_mapping", ",", "dims", ",", "ctx", ")", ":", "# List arguments to kernel", "args", "=", "[", "\"unsigned int shapea\"", "]", "arg_desc", "=", "\"I\"", "params", "=", "[", "axes_mapping", "[", "0", "]", "[", "4", "]", "]", "if", "dims", "==", "2", ":", "args", ".", "append", "(", "\"unsigned int shapeb\"", ")", "arg_desc", "=", "arg_desc", "+", "\"I\"", "params", ".", "append", "(", "axes_mapping", "[", "1", "]", "[", "4", "]", ")", "elif", "dims", "==", "3", ":", "args", ".", "extend", "(", "[", "\"unsigned int shapeb\"", ",", "\"unsigned int shapec\"", "]", ")", "arg_desc", "=", "arg_desc", "+", "\"II\"", "params", ".", "extend", "(", "[", "axes_mapping", "[", "1", "]", "[", "4", "]", ",", "axes_mapping", "[", "2", "]", "[", "4", "]", "]", ")", "num_constants", "=", "0", "processed_tensors", "=", "set", "(", ")", "for", "op", "in", "ops", ":", "for", "tensor", "in", "op", "[", "1", ":", "4", "]", ":", "from", "ngraph", ".", "transformers", ".", "gputransform", "import", "GPURegister", "if", "tensor", "is", "None", "or", "isinstance", "(", "tensor", ",", "GPURegister", ")", ":", "continue", "if", "isinstance", "(", "tensor", ",", "TensorDescriptionWrapper", ")", "and", "tensor", "not", "in", "processed_tensors", ":", "# Tensor is buffer in memory", "regname", "=", "ctx", ".", "register_mapping", "[", "tensor", "]", "bufname", "=", "ctx", ".", "buffers", "[", "tensor", "]", "args", ".", "append", "(", "_get_register_type", "(", "tensor", ".", "dtype", ",", "True", ")", "+", "\"* \"", "+", "bufname", ")", "args", ".", "append", "(", "\"unsigned int stridea_\"", "+", "bufname", ")", "arg_desc", "=", "arg_desc", "+", "\"PI\"", "params", ".", "append", "(", "tensor", ".", "td", ")", "params", ".", "append", "(", "tensor", ".", "strides", "[", "0", "]", ")", "if", "dims", "==", "2", ":", "args", ".", "append", "(", "\"unsigned int strideb_\"", "+", "bufname", ")", "arg_desc", "=", "arg_desc", "+", "\"I\"", "params", ".", "append", "(", "tensor", ".", "strides", "[", "1", "]", ")", "elif", "dims", "==", "3", ":", "args", ".", "append", "(", "\"unsigned int strideb_\"", "+", "bufname", ")", "args", ".", "append", "(", "\"unsigned int stridec_\"", "+", "bufname", ")", "arg_desc", "=", "arg_desc", "+", "\"II\"", "params", ".", "append", "(", "tensor", ".", "strides", "[", "1", "]", ")", "params", ".", "append", "(", "tensor", ".", "strides", "[", "2", "]", ")", "if", "isinstance", "(", "tensor", ",", "TensorDescriptionWrapper", ")", "and", "tensor", ".", "is_flex", "(", ")", ":", "argname", ",", "flex_entry", ",", "is_output", "=", "ctx", ".", "flex_scale", "[", "regname", "]", "args", ".", "append", "(", "\"float \"", "+", "argname", ")", "arg_desc", "=", "arg_desc", "+", "\"f\"", "# create description of flex scale parameters that will be bound later", "params", ".", "append", "(", "FlexScaleDescription", "(", "flex_entry", ",", "is_output", ")", ")", "if", "tensor", "is", "op", "[", "3", "]", ":", "# This is an output so we also need flex stats", "args", ".", "append", "(", "\"int* flex_stats\"", ")", "arg_desc", "=", "arg_desc", "+", "\"P\"", "params", ".", "append", "(", "ctx", ".", "flex_stats_ptr", ")", "else", ":", "# Must be a constant value", "regname", "=", "\"constant\"", "+", "str", "(", "num_constants", ")", "regtype", "=", "ctx", ".", "register_types", "[", "regname", "]", "num_constants", "+=", "1", "args", ".", "append", "(", "regtype", "+", "\" \"", "+", "regname", ")", "if", "regtype", "==", "\"float\"", ":", "arg_desc", "=", "arg_desc", "+", "\"f\"", "else", ":", "arg_desc", "=", "arg_desc", "+", "\"i\"", "params", ".", "append", "(", "tensor", ")", "return", "(", "args", ",", "arg_desc", ",", "params", ")" ]
https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/transformers/gpu/float_ew2.py#L987-L1079
robinhood/faust
01b4c0ad8390221db71751d80001b0fd879291e2
faust/types/settings/settings.py
python
Settings.producer_request_timeout
(self)
Producer request timeout. Timeout for producer operations. This is set high by default, as this is also the time when producer batches expire and will no longer be retried.
Producer request timeout.
[ "Producer", "request", "timeout", "." ]
def producer_request_timeout(self) -> float: """Producer request timeout. Timeout for producer operations. This is set high by default, as this is also the time when producer batches expire and will no longer be retried. """
[ "def", "producer_request_timeout", "(", "self", ")", "->", "float", ":" ]
https://github.com/robinhood/faust/blob/01b4c0ad8390221db71751d80001b0fd879291e2/faust/types/settings/settings.py#L1326-L1332
turicas/brasil.io
f1c371fe828a090510259a5027b49e2e651936b4
traffic_control/models.py
python
BlockRequestQuerySet.from_hours_ago
(self, hours)
return self.filter(created_at__gte=timezone.now() - datetime.timedelta(hours=hours))
[]
def from_hours_ago(self, hours): return self.filter(created_at__gte=timezone.now() - datetime.timedelta(hours=hours))
[ "def", "from_hours_ago", "(", "self", ",", "hours", ")", ":", "return", "self", ".", "filter", "(", "created_at__gte", "=", "timezone", ".", "now", "(", ")", "-", "datetime", ".", "timedelta", "(", "hours", "=", "hours", ")", ")" ]
https://github.com/turicas/brasil.io/blob/f1c371fe828a090510259a5027b49e2e651936b4/traffic_control/models.py#L10-L11
RiotGames/cloud-inquisitor
29a26c705381fdba3538b4efedb25b9e09b387ed
backend/cloud_inquisitor/schema/base.py
python
AuditLog.log
(cls, event=None, actor=None, data=None)
Generate and insert a new event Args: event (str): Action performed actor (str): Actor (user or subsystem) triggering the event data (dict): Any extra data necessary for describing the event Returns: `None`
Generate and insert a new event
[ "Generate", "and", "insert", "a", "new", "event" ]
def log(cls, event=None, actor=None, data=None): """Generate and insert a new event Args: event (str): Action performed actor (str): Actor (user or subsystem) triggering the event data (dict): Any extra data necessary for describing the event Returns: `None` """ from cloud_inquisitor.log import auditlog auditlog(event=event, actor=actor, data=data)
[ "def", "log", "(", "cls", ",", "event", "=", "None", ",", "actor", "=", "None", ",", "data", "=", "None", ")", ":", "from", "cloud_inquisitor", ".", "log", "import", "auditlog", "auditlog", "(", "event", "=", "event", ",", "actor", "=", "actor", ",", "data", "=", "data", ")" ]
https://github.com/RiotGames/cloud-inquisitor/blob/29a26c705381fdba3538b4efedb25b9e09b387ed/backend/cloud_inquisitor/schema/base.py#L422-L435
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/_abcoll.py
python
Sequence.__reversed__
(self)
[]
def __reversed__(self): for i in reversed(range(len(self))): yield self[i]
[ "def", "__reversed__", "(", "self", ")", ":", "for", "i", "in", "reversed", "(", "range", "(", "len", "(", "self", ")", ")", ")", ":", "yield", "self", "[", "i", "]" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/_abcoll.py#L555-L557
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/calendar.py
python
Calendar.itermonthdates
(self, year, month)
Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month.
Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month.
[ "Return", "an", "iterator", "for", "one", "month", ".", "The", "iterator", "will", "yield", "datetime", ".", "date", "values", "and", "will", "always", "iterate", "through", "complete", "weeks", "so", "it", "will", "yield", "dates", "outside", "the", "specified", "month", "." ]
def itermonthdates(self, year, month): """ Return an iterator for one month. The iterator will yield datetime.date values and will always iterate through complete weeks, so it will yield dates outside the specified month. """ for y, m, d in self.itermonthdays3(year, month): yield datetime.date(y, m, d)
[ "def", "itermonthdates", "(", "self", ",", "year", ",", "month", ")", ":", "for", "y", ",", "m", ",", "d", "in", "self", ".", "itermonthdays3", "(", "year", ",", "month", ")", ":", "yield", "datetime", ".", "date", "(", "y", ",", "m", ",", "d", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/calendar.py#L173-L180
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/nodes/data/structure.py
python
StructureData.get_cell_volume
(self)
return calc_cell_volume(self.cell)
Returns the cell volume in Angstrom^3. :return: a float.
Returns the cell volume in Angstrom^3.
[ "Returns", "the", "cell", "volume", "in", "Angstrom^3", "." ]
def get_cell_volume(self): """ Returns the cell volume in Angstrom^3. :return: a float. """ return calc_cell_volume(self.cell)
[ "def", "get_cell_volume", "(", "self", ")", ":", "return", "calc_cell_volume", "(", "self", ".", "cell", ")" ]
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/nodes/data/structure.py#L1755-L1761
zaxlct/imooc-django
daf1ced745d3d21989e8191b658c293a511b37fd
extra_apps/xadmin/plugins/xversion.py
python
RecoverView.init_request
(self, version_id)
[]
def init_request(self, version_id): if not self.has_change_permission() and not self.has_add_permission(): raise PermissionDenied self.version = get_object_or_404(Version, pk=version_id) self.org_obj = self.version._object_version.object self.prepare_form()
[ "def", "init_request", "(", "self", ",", "version_id", ")", ":", "if", "not", "self", ".", "has_change_permission", "(", ")", "and", "not", "self", ".", "has_add_permission", "(", ")", ":", "raise", "PermissionDenied", "self", ".", "version", "=", "get_object_or_404", "(", "Version", ",", "pk", "=", "version_id", ")", "self", ".", "org_obj", "=", "self", ".", "version", ".", "_object_version", ".", "object", "self", ".", "prepare_form", "(", ")" ]
https://github.com/zaxlct/imooc-django/blob/daf1ced745d3d21989e8191b658c293a511b37fd/extra_apps/xadmin/plugins/xversion.py#L450-L457
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
dist/lib/python2.7/logging/__init__.py
python
getLoggerClass
()
return _loggerClass
Return the class to be used when instantiating a logger.
Return the class to be used when instantiating a logger.
[ "Return", "the", "class", "to", "be", "used", "when", "instantiating", "a", "logger", "." ]
def getLoggerClass(): """ Return the class to be used when instantiating a logger. """ return _loggerClass
[ "def", "getLoggerClass", "(", ")", ":", "return", "_loggerClass" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/logging/__init__.py#L972-L977
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/templatetags/l10n.py
python
LocalizeNode.__repr__
(self)
return "<LocalizeNode>"
[]
def __repr__(self): return "<LocalizeNode>"
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"<LocalizeNode>\"" ]
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/templatetags/l10n.py#L31-L32
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-35/fabmetheus_utilities/miscellaneous/nophead/vector3.py
python
Vector3.__rmul__
(self, other)
return Vector3( self.x * other, self.y * other, self.z * other )
Get a new Vector3 by multiplying each component of this one.
Get a new Vector3 by multiplying each component of this one.
[ "Get", "a", "new", "Vector3", "by", "multiplying", "each", "component", "of", "this", "one", "." ]
def __rmul__(self, other): "Get a new Vector3 by multiplying each component of this one." return Vector3( self.x * other, self.y * other, self.z * other )
[ "def", "__rmul__", "(", "self", ",", "other", ")", ":", "return", "Vector3", "(", "self", ".", "x", "*", "other", ",", "self", ".", "y", "*", "other", ",", "self", ".", "z", "*", "other", ")" ]
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-35/fabmetheus_utilities/miscellaneous/nophead/vector3.py#L157-L159
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/expressions/matexpr.py
python
MatrixExpr.rows
(self)
return self.shape[0]
[]
def rows(self): return self.shape[0]
[ "def", "rows", "(", "self", ")", ":", "return", "self", ".", "shape", "[", "0", "]" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/expressions/matexpr.py#L140-L141
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/numpy-1.16.0-py3.7-macosx-10.9-x86_64.egg/numpy/polynomial/legendre.py
python
legdiv
(c1, c2)
Divide one Legendre series by another. Returns the quotient-with-remainder of two Legendre series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Legendre series coefficients ordered from low to high. Returns ------- quo, rem : ndarrays Of Legendre series coefficients representing the quotient and remainder. See Also -------- legadd, legsub, legmulx, legmul, legpow Notes ----- In general, the (polynomial) division of one Legendre series by another results in quotient and remainder terms that are not in the Legendre polynomial basis set. Thus, to express these results as a Legendre series, it is necessary to "reproject" the results onto the Legendre basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> L.legdiv(c1,c2) # quotient "intuitive," remainder not (array([ 3.]), array([-8., -4.])) >>> c2 = (0,1,2,3) >>> L.legdiv(c2,c1) # neither "intuitive" (array([-0.07407407, 1.66666667]), array([-1.03703704, -2.51851852]))
Divide one Legendre series by another.
[ "Divide", "one", "Legendre", "series", "by", "another", "." ]
def legdiv(c1, c2): """ Divide one Legendre series by another. Returns the quotient-with-remainder of two Legendre series `c1` / `c2`. The arguments are sequences of coefficients from lowest order "term" to highest, e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``. Parameters ---------- c1, c2 : array_like 1-D arrays of Legendre series coefficients ordered from low to high. Returns ------- quo, rem : ndarrays Of Legendre series coefficients representing the quotient and remainder. See Also -------- legadd, legsub, legmulx, legmul, legpow Notes ----- In general, the (polynomial) division of one Legendre series by another results in quotient and remainder terms that are not in the Legendre polynomial basis set. Thus, to express these results as a Legendre series, it is necessary to "reproject" the results onto the Legendre basis set, which may produce "unintuitive" (but correct) results; see Examples section below. Examples -------- >>> from numpy.polynomial import legendre as L >>> c1 = (1,2,3) >>> c2 = (3,2,1) >>> L.legdiv(c1,c2) # quotient "intuitive," remainder not (array([ 3.]), array([-8., -4.])) >>> c2 = (0,1,2,3) >>> L.legdiv(c2,c1) # neither "intuitive" (array([-0.07407407, 1.66666667]), array([-1.03703704, -2.51851852])) """ # c1, c2 are trimmed copies [c1, c2] = pu.as_series([c1, c2]) if c2[-1] == 0: raise ZeroDivisionError() lc1 = len(c1) lc2 = len(c2) if lc1 < lc2: return c1[:1]*0, c1 elif lc2 == 1: return c1/c2[-1], c1[:1]*0 else: quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype) rem = c1 for i in range(lc1 - lc2, - 1, -1): p = legmul([0]*i + [1], c2) q = rem[-1]/p[-1] rem = rem[:-1] - q*p[:-1] quo[i] = q return quo, pu.trimseq(rem)
[ "def", "legdiv", "(", "c1", ",", "c2", ")", ":", "# c1, c2 are trimmed copies", "[", "c1", ",", "c2", "]", "=", "pu", ".", "as_series", "(", "[", "c1", ",", "c2", "]", ")", "if", "c2", "[", "-", "1", "]", "==", "0", ":", "raise", "ZeroDivisionError", "(", ")", "lc1", "=", "len", "(", "c1", ")", "lc2", "=", "len", "(", "c2", ")", "if", "lc1", "<", "lc2", ":", "return", "c1", "[", ":", "1", "]", "*", "0", ",", "c1", "elif", "lc2", "==", "1", ":", "return", "c1", "/", "c2", "[", "-", "1", "]", ",", "c1", "[", ":", "1", "]", "*", "0", "else", ":", "quo", "=", "np", ".", "empty", "(", "lc1", "-", "lc2", "+", "1", ",", "dtype", "=", "c1", ".", "dtype", ")", "rem", "=", "c1", "for", "i", "in", "range", "(", "lc1", "-", "lc2", ",", "-", "1", ",", "-", "1", ")", ":", "p", "=", "legmul", "(", "[", "0", "]", "*", "i", "+", "[", "1", "]", ",", "c2", ")", "q", "=", "rem", "[", "-", "1", "]", "/", "p", "[", "-", "1", "]", "rem", "=", "rem", "[", ":", "-", "1", "]", "-", "q", "*", "p", "[", ":", "-", "1", "]", "quo", "[", "i", "]", "=", "q", "return", "quo", ",", "pu", ".", "trimseq", "(", "rem", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/numpy-1.16.0-py3.7-macosx-10.9-x86_64.egg/numpy/polynomial/legendre.py#L560-L625
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/ultimatelistctrl.py
python
UltimateListItem.IsFooterChecked
(self)
return self._footerChecked
Returns whether the footer item is checked or not.
Returns whether the footer item is checked or not.
[ "Returns", "whether", "the", "footer", "item", "is", "checked", "or", "not", "." ]
def IsFooterChecked(self): """ Returns whether the footer item is checked or not. """ return self._footerChecked
[ "def", "IsFooterChecked", "(", "self", ")", ":", "return", "self", ".", "_footerChecked" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/ultimatelistctrl.py#L2134-L2137
scikit-learn-contrib/DESlib
64260ae7c6dd745ef0003cc6322c9f829c807708
deslib/des/des_clustering.py
python
DESClustering._preprocess_clusters
(self)
Preprocess the competence as well as the average diversity of each base classifier for each specific cluster. This process makes the test routines faster, since the ensemble of classifiers of each cluster is already predefined. The class attributes Accuracy_cluster_ and diversity_cluster_ stores the accuracy and diversity information respectively of each base classifier for each cluster. The attribute indices_ stores the pre-selected base classifiers for each cluster.
Preprocess the competence as well as the average diversity of each base classifier for each specific cluster.
[ "Preprocess", "the", "competence", "as", "well", "as", "the", "average", "diversity", "of", "each", "base", "classifier", "for", "each", "specific", "cluster", "." ]
def _preprocess_clusters(self): """Preprocess the competence as well as the average diversity of each base classifier for each specific cluster. This process makes the test routines faster, since the ensemble of classifiers of each cluster is already predefined. The class attributes Accuracy_cluster_ and diversity_cluster_ stores the accuracy and diversity information respectively of each base classifier for each cluster. The attribute indices_ stores the pre-selected base classifiers for each cluster. """ labels = self.clustering_.predict(self.DSEL_data_) for cluster_index in range(self.clustering_.n_clusters): # Get the indices_ of the samples in the corresponding cluster. sample_indices = np.where(labels == cluster_index)[0] # Compute performance metric of each classifier in this cluster score_classifier = self.get_scores_(sample_indices) self.performance_cluster_[cluster_index, :] = score_classifier # Get the N_ most accurate classifiers in the cluster performance_indices = np.argsort(score_classifier)[::-1][0:self.N_] # Get the target labels for the samples in the corresponding # cluster for the diversity calculation. targets = self.DSEL_target_[sample_indices] self.diversity_cluster_[cluster_index, :] = \ compute_pairwise_diversity(targets, self.BKS_DSEL_[sample_indices, :], self.diversity_func_) diversity_of_selected = self.diversity_cluster_[ cluster_index, performance_indices] if self.more_diverse: diversity_indices = np.argsort(diversity_of_selected)[::-1][ 0:self.J_] else: diversity_indices = np.argsort(diversity_of_selected)[ 0:self.J_] self.indices_[cluster_index, :] = performance_indices[ diversity_indices]
[ "def", "_preprocess_clusters", "(", "self", ")", ":", "labels", "=", "self", ".", "clustering_", ".", "predict", "(", "self", ".", "DSEL_data_", ")", "for", "cluster_index", "in", "range", "(", "self", ".", "clustering_", ".", "n_clusters", ")", ":", "# Get the indices_ of the samples in the corresponding cluster.", "sample_indices", "=", "np", ".", "where", "(", "labels", "==", "cluster_index", ")", "[", "0", "]", "# Compute performance metric of each classifier in this cluster", "score_classifier", "=", "self", ".", "get_scores_", "(", "sample_indices", ")", "self", ".", "performance_cluster_", "[", "cluster_index", ",", ":", "]", "=", "score_classifier", "# Get the N_ most accurate classifiers in the cluster", "performance_indices", "=", "np", ".", "argsort", "(", "score_classifier", ")", "[", ":", ":", "-", "1", "]", "[", "0", ":", "self", ".", "N_", "]", "# Get the target labels for the samples in the corresponding", "# cluster for the diversity calculation.", "targets", "=", "self", ".", "DSEL_target_", "[", "sample_indices", "]", "self", ".", "diversity_cluster_", "[", "cluster_index", ",", ":", "]", "=", "compute_pairwise_diversity", "(", "targets", ",", "self", ".", "BKS_DSEL_", "[", "sample_indices", ",", ":", "]", ",", "self", ".", "diversity_func_", ")", "diversity_of_selected", "=", "self", ".", "diversity_cluster_", "[", "cluster_index", ",", "performance_indices", "]", "if", "self", ".", "more_diverse", ":", "diversity_indices", "=", "np", ".", "argsort", "(", "diversity_of_selected", ")", "[", ":", ":", "-", "1", "]", "[", "0", ":", "self", ".", "J_", "]", "else", ":", "diversity_indices", "=", "np", ".", "argsort", "(", "diversity_of_selected", ")", "[", "0", ":", "self", ".", "J_", "]", "self", ".", "indices_", "[", "cluster_index", ",", ":", "]", "=", "performance_indices", "[", "diversity_indices", "]" ]
https://github.com/scikit-learn-contrib/DESlib/blob/64260ae7c6dd745ef0003cc6322c9f829c807708/deslib/des/des_clustering.py#L187-L234
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/compiler/transformer.py
python
Transformer.if_stmt
(self, nodelist)
return If(tests, elseNode, lineno=nodelist[0][2])
[]
def if_stmt(self, nodelist): # if: test ':' suite ('elif' test ':' suite)* ['else' ':' suite] tests = [] for i in range(0, len(nodelist) - 3, 4): testNode = self.com_node(nodelist[i + 1]) suiteNode = self.com_node(nodelist[i + 3]) tests.append((testNode, suiteNode)) if len(nodelist) % 4 == 3: elseNode = self.com_node(nodelist[-1]) ## elseNode.lineno = nodelist[-1][1][2] else: elseNode = None return If(tests, elseNode, lineno=nodelist[0][2])
[ "def", "if_stmt", "(", "self", ",", "nodelist", ")", ":", "# if: test ':' suite ('elif' test ':' suite)* ['else' ':' suite]", "tests", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "nodelist", ")", "-", "3", ",", "4", ")", ":", "testNode", "=", "self", ".", "com_node", "(", "nodelist", "[", "i", "+", "1", "]", ")", "suiteNode", "=", "self", ".", "com_node", "(", "nodelist", "[", "i", "+", "3", "]", ")", "tests", ".", "append", "(", "(", "testNode", ",", "suiteNode", ")", ")", "if", "len", "(", "nodelist", ")", "%", "4", "==", "3", ":", "elseNode", "=", "self", ".", "com_node", "(", "nodelist", "[", "-", "1", "]", ")", "## elseNode.lineno = nodelist[-1][1][2]", "else", ":", "elseNode", "=", "None", "return", "If", "(", "tests", ",", "elseNode", ",", "lineno", "=", "nodelist", "[", "0", "]", "[", "2", "]", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/compiler/transformer.py#L506-L519
linkedin/kafka-tools
0d98bbefc1105851b7b7203de4f6c68d9c097730
kafka/tools/client.py
python
Client._send_all_brokers
(self, request)
return self._send_some_brokers(requests)
Sends a request to all brokers. The responses are returned mapped to the broker that they were retrieved from Args: request (BaseRequest): A valid request object that inherits from BaseRequest Returns: dict (int -> BaseResponse): A map of broker IDs to response instances (inherited from BaseResponse). Failed requests are represented with a value of None
Sends a request to all brokers. The responses are returned mapped to the broker that they were retrieved from
[ "Sends", "a", "request", "to", "all", "brokers", ".", "The", "responses", "are", "returned", "mapped", "to", "the", "broker", "that", "they", "were", "retrieved", "from" ]
def _send_all_brokers(self, request): """ Sends a request to all brokers. The responses are returned mapped to the broker that they were retrieved from Args: request (BaseRequest): A valid request object that inherits from BaseRequest Returns: dict (int -> BaseResponse): A map of broker IDs to response instances (inherited from BaseResponse). Failed requests are represented with a value of None """ requests = {} for broker_id in self.cluster.brokers: if self.cluster.brokers[broker_id].hostname is not None: requests[broker_id] = request return self._send_some_brokers(requests)
[ "def", "_send_all_brokers", "(", "self", ",", "request", ")", ":", "requests", "=", "{", "}", "for", "broker_id", "in", "self", ".", "cluster", ".", "brokers", ":", "if", "self", ".", "cluster", ".", "brokers", "[", "broker_id", "]", ".", "hostname", "is", "not", "None", ":", "requests", "[", "broker_id", "]", "=", "request", "return", "self", ".", "_send_some_brokers", "(", "requests", ")" ]
https://github.com/linkedin/kafka-tools/blob/0d98bbefc1105851b7b7203de4f6c68d9c097730/kafka/tools/client.py#L490-L506
pypa/setuptools
9f37366aab9cd8f6baa23e6a77cfdb8daf97757e
setuptools/dist.py
python
Distribution._finalize_setup_keywords
(self)
[]
def _finalize_setup_keywords(self): for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'): value = getattr(self, ep.name, None) if value is not None: ep.require(installer=self.fetch_build_egg) ep.load()(self, ep.name, value)
[ "def", "_finalize_setup_keywords", "(", "self", ")", ":", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "'distutils.setup_keywords'", ")", ":", "value", "=", "getattr", "(", "self", ",", "ep", ".", "name", ",", "None", ")", "if", "value", "is", "not", "None", ":", "ep", ".", "require", "(", "installer", "=", "self", ".", "fetch_build_egg", ")", "ep", ".", "load", "(", ")", "(", "self", ",", "ep", ".", "name", ",", "value", ")" ]
https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/dist.py#L853-L858
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/_vendor/distlib/manifest.py
python
Manifest._exclude_pattern
(self, pattern, anchor=True, prefix=None, is_regex=False)
return found
Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found. This API is public to allow e.g. exclusion of SCM subdirs, e.g. when packaging source distributions
Remove strings (presumably filenames) from 'files' that match 'pattern'.
[ "Remove", "strings", "(", "presumably", "filenames", ")", "from", "files", "that", "match", "pattern", "." ]
def _exclude_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found. This API is public to allow e.g. exclusion of SCM subdirs, e.g. when packaging source distributions """ found = False pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex) for f in list(self.files): if pattern_re.search(f): self.files.remove(f) found = True return found
[ "def", "_exclude_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "True", ",", "prefix", "=", "None", ",", "is_regex", "=", "False", ")", ":", "found", "=", "False", "pattern_re", "=", "self", ".", "_translate_pattern", "(", "pattern", ",", "anchor", ",", "prefix", ",", "is_regex", ")", "for", "f", "in", "list", "(", "self", ".", "files", ")", ":", "if", "pattern_re", ".", "search", "(", "f", ")", ":", "self", ".", "files", ".", "remove", "(", "f", ")", "found", "=", "True", "return", "found" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/_vendor/distlib/manifest.py#L290-L308
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/stringold.py
python
upper
(s)
return s.upper()
upper(s) -> string Return a copy of the string s converted to uppercase.
upper(s) -> string
[ "upper", "(", "s", ")", "-", ">", "string" ]
def upper(s): """upper(s) -> string Return a copy of the string s converted to uppercase. """ return s.upper()
[ "def", "upper", "(", "s", ")", ":", "return", "s", ".", "upper", "(", ")" ]
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/stringold.py#L55-L61
python-zk/kazoo
f585d605eea0a37a08aae95a8cc259b80da2ecf0
kazoo/client.py
python
KazooClient.connected
(self)
return self._live.is_set()
Returns whether the Zookeeper connection has been established.
Returns whether the Zookeeper connection has been established.
[ "Returns", "whether", "the", "Zookeeper", "connection", "has", "been", "established", "." ]
def connected(self): """Returns whether the Zookeeper connection has been established.""" return self._live.is_set()
[ "def", "connected", "(", "self", ")", ":", "return", "self", ".", "_live", ".", "is_set", "(", ")" ]
https://github.com/python-zk/kazoo/blob/f585d605eea0a37a08aae95a8cc259b80da2ecf0/kazoo/client.py#L426-L429
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/tools/jarfile.py
python
ReadManifest
(jar_file_name)
Read and parse the manifest out of the given jar. Args: jar_file_name: the name of the jar from which the manifest is to be read. Returns: A parsed Manifest object, or None if the jar has no manifest. Raises: IOError: if the jar does not exist or cannot be read.
Read and parse the manifest out of the given jar.
[ "Read", "and", "parse", "the", "manifest", "out", "of", "the", "given", "jar", "." ]
def ReadManifest(jar_file_name): """Read and parse the manifest out of the given jar. Args: jar_file_name: the name of the jar from which the manifest is to be read. Returns: A parsed Manifest object, or None if the jar has no manifest. Raises: IOError: if the jar does not exist or cannot be read. """ with zipfile.ZipFile(jar_file_name) as jar: try: manifest_string = jar.read(_MANIFEST_NAME) except KeyError: return None return _ParseManifest(manifest_string, jar_file_name)
[ "def", "ReadManifest", "(", "jar_file_name", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "jar_file_name", ")", "as", "jar", ":", "try", ":", "manifest_string", "=", "jar", ".", "read", "(", "_MANIFEST_NAME", ")", "except", "KeyError", ":", "return", "None", "return", "_ParseManifest", "(", "manifest_string", ",", "jar_file_name", ")" ]
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/gae_proxy/server/lib/google/appengine/tools/jarfile.py#L70-L87
entropy1337/infernal-twin
10995cd03312e39a48ade0f114ebb0ae3a711bb8
Modules/build/pip/pip/_vendor/distlib/resources.py
python
finder
(package)
return result
Return a resource finder for a package. :param package: The name of the package. :return: A :class:`ResourceFinder` instance for the package.
Return a resource finder for a package. :param package: The name of the package. :return: A :class:`ResourceFinder` instance for the package.
[ "Return", "a", "resource", "finder", "for", "a", "package", ".", ":", "param", "package", ":", "The", "name", "of", "the", "package", ".", ":", "return", ":", "A", ":", "class", ":", "ResourceFinder", "instance", "for", "the", "package", "." ]
def finder(package): """ Return a resource finder for a package. :param package: The name of the package. :return: A :class:`ResourceFinder` instance for the package. """ if package in _finder_cache: result = _finder_cache[package] else: if package not in sys.modules: __import__(package) module = sys.modules[package] path = getattr(module, '__path__', None) if path is None: raise DistlibException('You cannot get a finder for a module, ' 'only for a package') loader = getattr(module, '__loader__', None) finder_maker = _finder_registry.get(type(loader)) if finder_maker is None: raise DistlibException('Unable to locate finder for %r' % package) result = finder_maker(module) _finder_cache[package] = result return result
[ "def", "finder", "(", "package", ")", ":", "if", "package", "in", "_finder_cache", ":", "result", "=", "_finder_cache", "[", "package", "]", "else", ":", "if", "package", "not", "in", "sys", ".", "modules", ":", "__import__", "(", "package", ")", "module", "=", "sys", ".", "modules", "[", "package", "]", "path", "=", "getattr", "(", "module", ",", "'__path__'", ",", "None", ")", "if", "path", "is", "None", ":", "raise", "DistlibException", "(", "'You cannot get a finder for a module, '", "'only for a package'", ")", "loader", "=", "getattr", "(", "module", ",", "'__loader__'", ",", "None", ")", "finder_maker", "=", "_finder_registry", ".", "get", "(", "type", "(", "loader", ")", ")", "if", "finder_maker", "is", "None", ":", "raise", "DistlibException", "(", "'Unable to locate finder for %r'", "%", "package", ")", "result", "=", "finder_maker", "(", "module", ")", "_finder_cache", "[", "package", "]", "=", "result", "return", "result" ]
https://github.com/entropy1337/infernal-twin/blob/10995cd03312e39a48ade0f114ebb0ae3a711bb8/Modules/build/pip/pip/_vendor/distlib/resources.py#L305-L327
cheind/pytorch-blender
ef35c5b3eec884515d4f343671a8a3337b8aa1fb
pkg_blender/blendtorch/btb/signal.py
python
Signal.invoke
(self, *args, **kwargs)
Invoke the signal. Params ------ *args: optional Positional arguments to send to all callbacks **kwargs: optional Keyword arguments to send to all callbacks
Invoke the signal.
[ "Invoke", "the", "signal", "." ]
def invoke(self, *args, **kwargs): '''Invoke the signal. Params ------ *args: optional Positional arguments to send to all callbacks **kwargs: optional Keyword arguments to send to all callbacks ''' for s in self.slots: s(*args, **kwargs)
[ "def", "invoke", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "s", "in", "self", ".", "slots", ":", "s", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/cheind/pytorch-blender/blob/ef35c5b3eec884515d4f343671a8a3337b8aa1fb/pkg_blender/blendtorch/btb/signal.py#L43-L54
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/distro.py
python
LinuxDistribution._parse_os_release_content
(lines)
return props
Parse the lines of an os-release file. Parameters: * lines: Iterable through the lines in the os-release file. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items.
Parse the lines of an os-release file.
[ "Parse", "the", "lines", "of", "an", "os", "-", "release", "file", "." ]
def _parse_os_release_content(lines): """ Parse the lines of an os-release file. Parameters: * lines: Iterable through the lines in the os-release file. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items. """ props = {} lexer = shlex.shlex(lines, posix=True) lexer.whitespace_split = True # The shlex module defines its `wordchars` variable using literals, # making it dependent on the encoding of the Python source file. # In Python 2.6 and 2.7, the shlex source file is encoded in # 'iso-8859-1', and the `wordchars` variable is defined as a byte # string. This causes a UnicodeDecodeError to be raised when the # parsed content is a unicode object. The following fix resolves that # (... but it should be fixed in shlex...): if sys.version_info[0] == 2 and isinstance(lexer.wordchars, bytes): lexer.wordchars = lexer.wordchars.decode('iso-8859-1') tokens = list(lexer) for token in tokens: # At this point, all shell-like parsing has been done (i.e. # comments processed, quotes and backslash escape sequences # processed, multi-line values assembled, trailing newlines # stripped, etc.), so the tokens are now either: # * variable assignments: var=value # * commands or their arguments (not allowed in os-release) if '=' in token: k, v = token.split('=', 1) if isinstance(v, bytes): v = v.decode('utf-8') props[k.lower()] = v if k == 'VERSION': # this handles cases in which the codename is in # the `(CODENAME)` (rhel, centos, fedora) format # or in the `, CODENAME` format (Ubuntu). codename = re.search(r'(\(\D+\))|,(\s+)?\D+', v) if codename: codename = codename.group() codename = codename.strip('()') codename = codename.strip(',') codename = codename.strip() # codename appears within paranthese. props['codename'] = codename else: props['codename'] = '' else: # Ignore any tokens that are not variable assignments pass return props
[ "def", "_parse_os_release_content", "(", "lines", ")", ":", "props", "=", "{", "}", "lexer", "=", "shlex", ".", "shlex", "(", "lines", ",", "posix", "=", "True", ")", "lexer", ".", "whitespace_split", "=", "True", "# The shlex module defines its `wordchars` variable using literals,", "# making it dependent on the encoding of the Python source file.", "# In Python 2.6 and 2.7, the shlex source file is encoded in", "# 'iso-8859-1', and the `wordchars` variable is defined as a byte", "# string. This causes a UnicodeDecodeError to be raised when the", "# parsed content is a unicode object. The following fix resolves that", "# (... but it should be fixed in shlex...):", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", "and", "isinstance", "(", "lexer", ".", "wordchars", ",", "bytes", ")", ":", "lexer", ".", "wordchars", "=", "lexer", ".", "wordchars", ".", "decode", "(", "'iso-8859-1'", ")", "tokens", "=", "list", "(", "lexer", ")", "for", "token", "in", "tokens", ":", "# At this point, all shell-like parsing has been done (i.e.", "# comments processed, quotes and backslash escape sequences", "# processed, multi-line values assembled, trailing newlines", "# stripped, etc.), so the tokens are now either:", "# * variable assignments: var=value", "# * commands or their arguments (not allowed in os-release)", "if", "'='", "in", "token", ":", "k", ",", "v", "=", "token", ".", "split", "(", "'='", ",", "1", ")", "if", "isinstance", "(", "v", ",", "bytes", ")", ":", "v", "=", "v", ".", "decode", "(", "'utf-8'", ")", "props", "[", "k", ".", "lower", "(", ")", "]", "=", "v", "if", "k", "==", "'VERSION'", ":", "# this handles cases in which the codename is in", "# the `(CODENAME)` (rhel, centos, fedora) format", "# or in the `, CODENAME` format (Ubuntu).", "codename", "=", "re", ".", "search", "(", "r'(\\(\\D+\\))|,(\\s+)?\\D+'", ",", "v", ")", "if", "codename", ":", "codename", "=", "codename", ".", "group", "(", ")", "codename", "=", "codename", ".", "strip", "(", "'()'", ")", "codename", "=", "codename", ".", "strip", "(", "','", ")", "codename", "=", "codename", ".", "strip", "(", ")", "# codename appears within paranthese.", "props", "[", "'codename'", "]", "=", "codename", "else", ":", "props", "[", "'codename'", "]", "=", "''", "else", ":", "# Ignore any tokens that are not variable assignments", "pass", "return", "props" ]
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pip/_vendor/distro.py#L849-L906
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_internal/vcs/git.py
python
Git.__init__
(self, url=None, *args, **kwargs)
[]
def __init__(self, url=None, *args, **kwargs): # Works around an apparent Git bug # (see https://article.gmane.org/gmane.comp.version-control.git/146500) if url: scheme, netloc, path, query, fragment = urlsplit(url) if scheme.endswith('file'): initial_slashes = path[:-len(path.lstrip('/'))] newpath = ( initial_slashes + urllib_request.url2pathname(path) .replace('\\', '/').lstrip('/') ) url = urlunsplit((scheme, netloc, newpath, query, fragment)) after_plus = scheme.find('+') + 1 url = scheme[:after_plus] + urlunsplit( (scheme[after_plus:], netloc, newpath, query, fragment), ) super(Git, self).__init__(url, *args, **kwargs)
[ "def", "__init__", "(", "self", ",", "url", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Works around an apparent Git bug", "# (see https://article.gmane.org/gmane.comp.version-control.git/146500)", "if", "url", ":", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urlsplit", "(", "url", ")", "if", "scheme", ".", "endswith", "(", "'file'", ")", ":", "initial_slashes", "=", "path", "[", ":", "-", "len", "(", "path", ".", "lstrip", "(", "'/'", ")", ")", "]", "newpath", "=", "(", "initial_slashes", "+", "urllib_request", ".", "url2pathname", "(", "path", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", ".", "lstrip", "(", "'/'", ")", ")", "url", "=", "urlunsplit", "(", "(", "scheme", ",", "netloc", ",", "newpath", ",", "query", ",", "fragment", ")", ")", "after_plus", "=", "scheme", ".", "find", "(", "'+'", ")", "+", "1", "url", "=", "scheme", "[", ":", "after_plus", "]", "+", "urlunsplit", "(", "(", "scheme", "[", "after_plus", ":", "]", ",", "netloc", ",", "newpath", ",", "query", ",", "fragment", ")", ",", ")", "super", "(", "Git", ",", "self", ")", ".", "__init__", "(", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_internal/vcs/git.py#L43-L62
pyeve/cerberus
8765b317442c002a84e556bd5d9677b868e6deb2
cerberus/errors.py
python
BaseErrorHandler.__init__
(self, *args, **kwargs)
Optionally initialize a new instance.
Optionally initialize a new instance.
[ "Optionally", "initialize", "a", "new", "instance", "." ]
def __init__(self, *args, **kwargs): """Optionally initialize a new instance.""" pass
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass" ]
https://github.com/pyeve/cerberus/blob/8765b317442c002a84e556bd5d9677b868e6deb2/cerberus/errors.py#L372-L374
datacenter/acitoolkit
629b84887dd0f0183b81efc8adb16817f985541a
applications/cableplan/cableplan.py
python
CpPort.__eq__
(self, other)
compares the content of the port list and returns true if they are the same. The comparison is case insensitive.
compares the content of the port list and returns true if they are the same. The comparison is case insensitive.
[ "compares", "the", "content", "of", "the", "port", "list", "and", "returns", "true", "if", "they", "are", "the", "same", ".", "The", "comparison", "is", "case", "insensitive", "." ]
def __eq__(self, other): """ compares the content of the port list and returns true if they are the same. The comparison is case insensitive. """ if not self.ports and not other.ports: return True elif not self.ports and other.ports: return False elif self.ports and not other.ports: return False my_ports = set() for port in self.ports: my_ports.add(port.lower()) other_ports = set() for port in other.ports: other_ports.add(port.lower()) if len(my_ports ^ other_ports) == 0: return True else: return False
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "self", ".", "ports", "and", "not", "other", ".", "ports", ":", "return", "True", "elif", "not", "self", ".", "ports", "and", "other", ".", "ports", ":", "return", "False", "elif", "self", ".", "ports", "and", "not", "other", ".", "ports", ":", "return", "False", "my_ports", "=", "set", "(", ")", "for", "port", "in", "self", ".", "ports", ":", "my_ports", ".", "add", "(", "port", ".", "lower", "(", ")", ")", "other_ports", "=", "set", "(", ")", "for", "port", "in", "other", ".", "ports", ":", "other_ports", ".", "add", "(", "port", ".", "lower", "(", ")", ")", "if", "len", "(", "my_ports", "^", "other_ports", ")", "==", "0", ":", "return", "True", "else", ":", "return", "False" ]
https://github.com/datacenter/acitoolkit/blob/629b84887dd0f0183b81efc8adb16817f985541a/applications/cableplan/cableplan.py#L770-L792
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
managerClientDatabase/lib/globalData/systemData.py
python
SystemData.get_managers_by_node_id
(self, node_id: int)
return result
Gets Manager objects corresponding to given node id. :param node_id: :return:
Gets Manager objects corresponding to given node id. :param node_id: :return:
[ "Gets", "Manager", "objects", "corresponding", "to", "given", "node", "id", ".", ":", "param", "node_id", ":", ":", "return", ":" ]
def get_managers_by_node_id(self, node_id: int) -> List[ManagerObjManager]: """ Gets Manager objects corresponding to given node id. :param node_id: :return: """ result = [] node = self.get_node_by_id(node_id) if node is None or node.nodeType != "manager": return result with self._data_lock: for _, manager in self._managers.items(): if manager.nodeId == node_id: result.append(manager) return result
[ "def", "get_managers_by_node_id", "(", "self", ",", "node_id", ":", "int", ")", "->", "List", "[", "ManagerObjManager", "]", ":", "result", "=", "[", "]", "node", "=", "self", ".", "get_node_by_id", "(", "node_id", ")", "if", "node", "is", "None", "or", "node", ".", "nodeType", "!=", "\"manager\"", ":", "return", "result", "with", "self", ".", "_data_lock", ":", "for", "_", ",", "manager", "in", "self", ".", "_managers", ".", "items", "(", ")", ":", "if", "manager", ".", "nodeId", "==", "node_id", ":", "result", ".", "append", "(", "manager", ")", "return", "result" ]
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/managerClientDatabase/lib/globalData/systemData.py#L457-L472
vericast/spylon-kernel
2d0ddf2aca1b91738f938b72a500c20293e3156c
versioneer.py
python
render_pep440_post
(pieces)
return rendered
TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]
TAG[.postDISTANCE[.dev0]+gHEX] .
[ "TAG", "[", ".", "postDISTANCE", "[", ".", "dev0", "]", "+", "gHEX", "]", "." ]
def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered
[ "def", "render_pep440_post", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", "or", "pieces", "[", "\"dirty\"", "]", ":", "rendered", "+=", "\".post%d\"", "%", "pieces", "[", "\"distance\"", "]", "if", "pieces", "[", "\"dirty\"", "]", ":", "rendered", "+=", "\".dev0\"", "rendered", "+=", "plus_or_dot", "(", "pieces", ")", "rendered", "+=", "\"g%s\"", "%", "pieces", "[", "\"short\"", "]", "else", ":", "# exception #1", "rendered", "=", "\"0.post%d\"", "%", "pieces", "[", "\"distance\"", "]", "if", "pieces", "[", "\"dirty\"", "]", ":", "rendered", "+=", "\".dev0\"", "rendered", "+=", "\"+g%s\"", "%", "pieces", "[", "\"short\"", "]", "return", "rendered" ]
https://github.com/vericast/spylon-kernel/blob/2d0ddf2aca1b91738f938b72a500c20293e3156c/versioneer.py#L1273-L1297
KhronosGroup/NNEF-Tools
c913758ca687dab8cb7b49e8f1556819a2d0ca25
nnef_tools/model/graph.py
python
Graph.__repr__
(self)
return self.name if self.name is not None else _hex_id(self)
[]
def __repr__(self): return self.name if self.name is not None else _hex_id(self)
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "name", "if", "self", ".", "name", "is", "not", "None", "else", "_hex_id", "(", "self", ")" ]
https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/model/graph.py#L428-L429
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_service.py
python
OCService.get
(self)
return result
return service information
return service information
[ "return", "service", "information" ]
def get(self): '''return service information ''' result = self._get(self.kind, self.config.name) if result['returncode'] == 0: self.service = Service(content=result['results'][0]) result['clusterip'] = self.service.get('spec.clusterIP') elif 'services \"%s\" not found' % self.config.name in result['stderr']: result['clusterip'] = '' result['returncode'] = 0 elif 'namespaces \"%s\" not found' % self.config.namespace in result['stderr']: result['clusterip'] = '' result['returncode'] = 0 return result
[ "def", "get", "(", "self", ")", ":", "result", "=", "self", ".", "_get", "(", "self", ".", "kind", ",", "self", ".", "config", ".", "name", ")", "if", "result", "[", "'returncode'", "]", "==", "0", ":", "self", ".", "service", "=", "Service", "(", "content", "=", "result", "[", "'results'", "]", "[", "0", "]", ")", "result", "[", "'clusterip'", "]", "=", "self", ".", "service", ".", "get", "(", "'spec.clusterIP'", ")", "elif", "'services \\\"%s\\\" not found'", "%", "self", ".", "config", ".", "name", "in", "result", "[", "'stderr'", "]", ":", "result", "[", "'clusterip'", "]", "=", "''", "result", "[", "'returncode'", "]", "=", "0", "elif", "'namespaces \\\"%s\\\" not found'", "%", "self", ".", "config", ".", "namespace", "in", "result", "[", "'stderr'", "]", ":", "result", "[", "'clusterip'", "]", "=", "''", "result", "[", "'returncode'", "]", "=", "0", "return", "result" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_service.py#L1769-L1782
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/symmetry/analyzer.py
python
SpacegroupAnalyzer.__init__
(self, structure, symprec=0.01, angle_tolerance=5.0)
Args: structure (Structure/IStructure): Structure to find symmetry symprec (float): Tolerance for symmetry finding. Defaults to 0.01, which is fairly strict and works well for properly refined structures with atoms in the proper symmetry coordinates. For structures with slight deviations from their proper atomic positions (e.g., structures relaxed with electronic structure codes), a looser tolerance of 0.1 (the value used in Materials Project) is often needed. angle_tolerance (float): Angle tolerance for symmetry finding.
Args: structure (Structure/IStructure): Structure to find symmetry symprec (float): Tolerance for symmetry finding. Defaults to 0.01, which is fairly strict and works well for properly refined structures with atoms in the proper symmetry coordinates. For structures with slight deviations from their proper atomic positions (e.g., structures relaxed with electronic structure codes), a looser tolerance of 0.1 (the value used in Materials Project) is often needed. angle_tolerance (float): Angle tolerance for symmetry finding.
[ "Args", ":", "structure", "(", "Structure", "/", "IStructure", ")", ":", "Structure", "to", "find", "symmetry", "symprec", "(", "float", ")", ":", "Tolerance", "for", "symmetry", "finding", ".", "Defaults", "to", "0", ".", "01", "which", "is", "fairly", "strict", "and", "works", "well", "for", "properly", "refined", "structures", "with", "atoms", "in", "the", "proper", "symmetry", "coordinates", ".", "For", "structures", "with", "slight", "deviations", "from", "their", "proper", "atomic", "positions", "(", "e", ".", "g", ".", "structures", "relaxed", "with", "electronic", "structure", "codes", ")", "a", "looser", "tolerance", "of", "0", ".", "1", "(", "the", "value", "used", "in", "Materials", "Project", ")", "is", "often", "needed", ".", "angle_tolerance", "(", "float", ")", ":", "Angle", "tolerance", "for", "symmetry", "finding", "." ]
def __init__(self, structure, symprec=0.01, angle_tolerance=5.0): """ Args: structure (Structure/IStructure): Structure to find symmetry symprec (float): Tolerance for symmetry finding. Defaults to 0.01, which is fairly strict and works well for properly refined structures with atoms in the proper symmetry coordinates. For structures with slight deviations from their proper atomic positions (e.g., structures relaxed with electronic structure codes), a looser tolerance of 0.1 (the value used in Materials Project) is often needed. angle_tolerance (float): Angle tolerance for symmetry finding. """ self._symprec = symprec self._angle_tol = angle_tolerance self._structure = structure self._siteprops = structure.site_properties latt = structure.lattice.matrix positions = structure.frac_coords unique_species = [] zs = [] magmoms = [] for species, g in itertools.groupby(structure, key=lambda s: s.species): if species in unique_species: ind = unique_species.index(species) zs.extend([ind + 1] * len(tuple(g))) else: unique_species.append(species) zs.extend([len(unique_species)] * len(tuple(g))) for site in structure: if hasattr(site, "magmom"): magmoms.append(site.magmom) elif site.is_ordered and hasattr(site.specie, "spin"): magmoms.append(site.specie.spin) else: magmoms.append(0) # needed for spglib self._unique_species = unique_species self._numbers = zs self._cell = latt, positions, zs, magmoms self._space_group_data = spglib.get_symmetry_dataset( self._cell, symprec=self._symprec, angle_tolerance=angle_tolerance )
[ "def", "__init__", "(", "self", ",", "structure", ",", "symprec", "=", "0.01", ",", "angle_tolerance", "=", "5.0", ")", ":", "self", ".", "_symprec", "=", "symprec", "self", ".", "_angle_tol", "=", "angle_tolerance", "self", ".", "_structure", "=", "structure", "self", ".", "_siteprops", "=", "structure", ".", "site_properties", "latt", "=", "structure", ".", "lattice", ".", "matrix", "positions", "=", "structure", ".", "frac_coords", "unique_species", "=", "[", "]", "zs", "=", "[", "]", "magmoms", "=", "[", "]", "for", "species", ",", "g", "in", "itertools", ".", "groupby", "(", "structure", ",", "key", "=", "lambda", "s", ":", "s", ".", "species", ")", ":", "if", "species", "in", "unique_species", ":", "ind", "=", "unique_species", ".", "index", "(", "species", ")", "zs", ".", "extend", "(", "[", "ind", "+", "1", "]", "*", "len", "(", "tuple", "(", "g", ")", ")", ")", "else", ":", "unique_species", ".", "append", "(", "species", ")", "zs", ".", "extend", "(", "[", "len", "(", "unique_species", ")", "]", "*", "len", "(", "tuple", "(", "g", ")", ")", ")", "for", "site", "in", "structure", ":", "if", "hasattr", "(", "site", ",", "\"magmom\"", ")", ":", "magmoms", ".", "append", "(", "site", ".", "magmom", ")", "elif", "site", ".", "is_ordered", "and", "hasattr", "(", "site", ".", "specie", ",", "\"spin\"", ")", ":", "magmoms", ".", "append", "(", "site", ".", "specie", ".", "spin", ")", "else", ":", "magmoms", ".", "append", "(", "0", ")", "# needed for spglib", "self", ".", "_unique_species", "=", "unique_species", "self", ".", "_numbers", "=", "zs", "self", ".", "_cell", "=", "latt", ",", "positions", ",", "zs", ",", "magmoms", "self", ".", "_space_group_data", "=", "spglib", ".", "get_symmetry_dataset", "(", "self", ".", "_cell", ",", "symprec", "=", "self", ".", "_symprec", ",", "angle_tolerance", "=", "angle_tolerance", ")" ]
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/symmetry/analyzer.py#L42-L87
amanusk/s-tui
d7a9ee4efbfc6f56b373a16dcd578881c534b2ce
s_tui/sources/freq_source.py
python
FreqSource.__init__
(self)
[]
def __init__(self): self.is_available = True if (not hasattr(psutil, "cpu_freq") and psutil.cpu_freq()): self.is_available = False logging.debug("cpu_freq is not available from psutil") return Source.__init__(self) self.name = 'Frequency' self.measurement_unit = 'MHz' self.pallet = ('freq light', 'freq dark', 'freq light smooth', 'freq dark smooth') # Check if psutil.cpu_freq is available. # +1 for average frequency self.last_measurement = [0] * len(psutil.cpu_freq(True)) if psutil.cpu_freq(False): self.last_measurement.append(0) self.top_freq = psutil.cpu_freq().max self.max_freq = self.top_freq if self.top_freq == 0.0: # If top freq not available, take the current as top if max(self.last_measurement) >= 0: self.max_freq = max(self.last_measurement) self.available_sensors = ['Avg'] for core_id, _ in enumerate(psutil.cpu_freq(True)): self.available_sensors.append("Core " + str(core_id))
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "is_available", "=", "True", "if", "(", "not", "hasattr", "(", "psutil", ",", "\"cpu_freq\"", ")", "and", "psutil", ".", "cpu_freq", "(", ")", ")", ":", "self", ".", "is_available", "=", "False", "logging", ".", "debug", "(", "\"cpu_freq is not available from psutil\"", ")", "return", "Source", ".", "__init__", "(", "self", ")", "self", ".", "name", "=", "'Frequency'", "self", ".", "measurement_unit", "=", "'MHz'", "self", ".", "pallet", "=", "(", "'freq light'", ",", "'freq dark'", ",", "'freq light smooth'", ",", "'freq dark smooth'", ")", "# Check if psutil.cpu_freq is available.", "# +1 for average frequency", "self", ".", "last_measurement", "=", "[", "0", "]", "*", "len", "(", "psutil", ".", "cpu_freq", "(", "True", ")", ")", "if", "psutil", ".", "cpu_freq", "(", "False", ")", ":", "self", ".", "last_measurement", ".", "append", "(", "0", ")", "self", ".", "top_freq", "=", "psutil", ".", "cpu_freq", "(", ")", ".", "max", "self", ".", "max_freq", "=", "self", ".", "top_freq", "if", "self", ".", "top_freq", "==", "0.0", ":", "# If top freq not available, take the current as top", "if", "max", "(", "self", ".", "last_measurement", ")", ">=", "0", ":", "self", ".", "max_freq", "=", "max", "(", "self", ".", "last_measurement", ")", "self", ".", "available_sensors", "=", "[", "'Avg'", "]", "for", "core_id", ",", "_", "in", "enumerate", "(", "psutil", ".", "cpu_freq", "(", "True", ")", ")", ":", "self", ".", "available_sensors", ".", "append", "(", "\"Core \"", "+", "str", "(", "core_id", ")", ")" ]
https://github.com/amanusk/s-tui/blob/d7a9ee4efbfc6f56b373a16dcd578881c534b2ce/s_tui/sources/freq_source.py#L29-L60
zhang-can/ECO-pytorch
355c3866b35cdaa5d451263c1f3291c150e22eeb
tf_model_zoo/models/neural_gpu/neural_gpu_trainer.py
python
multi_test
(l, model, sess, task, nprint, batch_size, offset=None, ensemble=None)
return errors, seq_err
Run multiple tests at lower batch size to save memory.
Run multiple tests at lower batch size to save memory.
[ "Run", "multiple", "tests", "at", "lower", "batch", "size", "to", "save", "memory", "." ]
def multi_test(l, model, sess, task, nprint, batch_size, offset=None, ensemble=None): """Run multiple tests at lower batch size to save memory.""" errors, seq_err = 0.0, 0.0 to_print = nprint low_batch = FLAGS.low_batch_size low_batch = min(low_batch, batch_size) for mstep in xrange(batch_size / low_batch): cur_offset = None if offset is None else offset + mstep * low_batch err, sq_err, _ = single_test(l, model, sess, task, to_print, low_batch, False, cur_offset, ensemble=ensemble) to_print = max(0, to_print - low_batch) errors += err seq_err += sq_err if FLAGS.mode > 0: cur_errors = float(low_batch * errors) / ((mstep+1) * low_batch) cur_seq_err = float(low_batch * seq_err) / ((mstep+1) * low_batch) data.print_out(" %s multitest current errors %.2f sequence-errors %.2f" % (task, 100*cur_errors, 100*cur_seq_err)) errors = float(low_batch) * float(errors) / batch_size seq_err = float(low_batch) * float(seq_err) / batch_size data.print_out(" %s len %d errors %.2f sequence-errors %.2f" % (task, l, 100*errors, 100*seq_err)) return errors, seq_err
[ "def", "multi_test", "(", "l", ",", "model", ",", "sess", ",", "task", ",", "nprint", ",", "batch_size", ",", "offset", "=", "None", ",", "ensemble", "=", "None", ")", ":", "errors", ",", "seq_err", "=", "0.0", ",", "0.0", "to_print", "=", "nprint", "low_batch", "=", "FLAGS", ".", "low_batch_size", "low_batch", "=", "min", "(", "low_batch", ",", "batch_size", ")", "for", "mstep", "in", "xrange", "(", "batch_size", "/", "low_batch", ")", ":", "cur_offset", "=", "None", "if", "offset", "is", "None", "else", "offset", "+", "mstep", "*", "low_batch", "err", ",", "sq_err", ",", "_", "=", "single_test", "(", "l", ",", "model", ",", "sess", ",", "task", ",", "to_print", ",", "low_batch", ",", "False", ",", "cur_offset", ",", "ensemble", "=", "ensemble", ")", "to_print", "=", "max", "(", "0", ",", "to_print", "-", "low_batch", ")", "errors", "+=", "err", "seq_err", "+=", "sq_err", "if", "FLAGS", ".", "mode", ">", "0", ":", "cur_errors", "=", "float", "(", "low_batch", "*", "errors", ")", "/", "(", "(", "mstep", "+", "1", ")", "*", "low_batch", ")", "cur_seq_err", "=", "float", "(", "low_batch", "*", "seq_err", ")", "/", "(", "(", "mstep", "+", "1", ")", "*", "low_batch", ")", "data", ".", "print_out", "(", "\" %s multitest current errors %.2f sequence-errors %.2f\"", "%", "(", "task", ",", "100", "*", "cur_errors", ",", "100", "*", "cur_seq_err", ")", ")", "errors", "=", "float", "(", "low_batch", ")", "*", "float", "(", "errors", ")", "/", "batch_size", "seq_err", "=", "float", "(", "low_batch", ")", "*", "float", "(", "seq_err", ")", "/", "batch_size", "data", ".", "print_out", "(", "\" %s len %d errors %.2f sequence-errors %.2f\"", "%", "(", "task", ",", "l", ",", "100", "*", "errors", ",", "100", "*", "seq_err", ")", ")", "return", "errors", ",", "seq_err" ]
https://github.com/zhang-can/ECO-pytorch/blob/355c3866b35cdaa5d451263c1f3291c150e22eeb/tf_model_zoo/models/neural_gpu/neural_gpu_trainer.py#L192-L215
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/taskrouter/v1/workspace/activity.py
python
ActivityInstance._proxy
(self)
return self._context
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ActivityContext for this ActivityInstance :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context
[ "Generate", "an", "instance", "context", "for", "the", "instance", "the", "context", "is", "capable", "of", "performing", "various", "actions", ".", "All", "instance", "actions", "are", "proxied", "to", "the", "context" ]
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ActivityContext for this ActivityInstance :rtype: twilio.rest.taskrouter.v1.workspace.activity.ActivityContext """ if self._context is None: self._context = ActivityContext( self._version, workspace_sid=self._solution['workspace_sid'], sid=self._solution['sid'], ) return self._context
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "ActivityContext", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace_sid'", "]", ",", "sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ",", ")", "return", "self", ".", "_context" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/taskrouter/v1/workspace/activity.py#L323-L337
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pywin/Lib/pkgutil.py
python
get_importer
(path_item)
return importer
Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary.
Retrieve a PEP 302 importer for the given path item
[ "Retrieve", "a", "PEP", "302", "importer", "for", "the", "given", "path", "item" ]
def get_importer(path_item): """Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary. """ try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) break except ImportError: pass else: importer = None sys.path_importer_cache.setdefault(path_item, importer) if importer is None: try: importer = ImpImporter(path_item) except ImportError: importer = None return importer
[ "def", "get_importer", "(", "path_item", ")", ":", "try", ":", "importer", "=", "sys", ".", "path_importer_cache", "[", "path_item", "]", "except", "KeyError", ":", "for", "path_hook", "in", "sys", ".", "path_hooks", ":", "try", ":", "importer", "=", "path_hook", "(", "path_item", ")", "break", "except", "ImportError", ":", "pass", "else", ":", "importer", "=", "None", "sys", ".", "path_importer_cache", ".", "setdefault", "(", "path_item", ",", "importer", ")", "if", "importer", "is", "None", ":", "try", ":", "importer", "=", "ImpImporter", "(", "path_item", ")", "except", "ImportError", ":", "importer", "=", "None", "return", "importer" ]
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/pkgutil.py#L366-L397
dark-lbp/isf
5228865757fd48f26970da5217a4c88d81f6597e
icssploit/clients/base.py
python
Base.get_description
(self)
return type(self).__name__
:rtype: str :return: the description of the object. by default only prints the object type.
:rtype: str :return: the description of the object. by default only prints the object type.
[ ":", "rtype", ":", "str", ":", "return", ":", "the", "description", "of", "the", "object", ".", "by", "default", "only", "prints", "the", "object", "type", "." ]
def get_description(self): ''' :rtype: str :return: the description of the object. by default only prints the object type. ''' return type(self).__name__
[ "def", "get_description", "(", "self", ")", ":", "return", "type", "(", "self", ")", ".", "__name__" ]
https://github.com/dark-lbp/isf/blob/5228865757fd48f26970da5217a4c88d81f6597e/icssploit/clients/base.py#L60-L65
21dotco/two1-python
4e833300fd5a58363e3104ed4c097631e5d296d3
two1/wallet/two1_wallet.py
python
Two1Wallet.spread_utxos
(self, threshold, num_addresses, accounts=[])
return txids
Spreads out UTXOs >= threshold satoshis to a set of new change addresses. Args: threshold (int): UTXO value must be >= to this value (in satoshis). num_addresses (int): Number of addresses to spread out the matching UTXOs over. This must be > 1 and <= 100. accounts (list): List of accounts to use. If not provided, all discovered accounts will be done.
Spreads out UTXOs >= threshold satoshis to a set of new change addresses.
[ "Spreads", "out", "UTXOs", ">", "=", "threshold", "satoshis", "to", "a", "set", "of", "new", "change", "addresses", "." ]
def spread_utxos(self, threshold, num_addresses, accounts=[]): """ Spreads out UTXOs >= threshold satoshis to a set of new change addresses. Args: threshold (int): UTXO value must be >= to this value (in satoshis). num_addresses (int): Number of addresses to spread out the matching UTXOs over. This must be > 1 and <= 100. accounts (list): List of accounts to use. If not provided, all discovered accounts will be done. """ # Limit the number of spreading addresses so that we don't # create unnecessarily large transactions if num_addresses < 1 or num_addresses > 100: raise ValueError("num_addresses must be > 0 and <= 100.") if not isinstance(threshold, int): raise exceptions.SatoshiUnitsError( "Can't send a non-integer amount of satoshis %s. Did you forget to convert from BTC?" % (threshold,)) if not accounts: accts = self._accounts else: accts = self._check_and_get_accounts(accounts) txids = [] for acct in accts: utxos_by_addr, num_conf = self.get_utxos_above_threshold(threshold, False, [acct]) # Total up the value total_value, num_utxos = self._sum_utxos(utxos_by_addr) if num_utxos == 0: self.logger.error("No matching UTXOs for account %s (%d confirmed UTXOs). Not spreading." % (acct.name, num_conf)) break # Get the next num_addresses change addresses # We force address discovery here to make sure change # address generation doesn't end up violating the GAP # limit acct._sync_txns(check_all=True) change_addresses = [acct.get_address(True) for i in range(num_addresses)] # Compute an approximate fee fee_amounts = txn_fees.get_fees() fees = num_utxos * fee_amounts['per_input'] + \ num_addresses * fee_amounts['per_output'] spread_amount = total_value - fees per_addr_amount = int(spread_amount / num_addresses) if per_addr_amount <= txn_fees.DUST_LIMIT: self.logger.error( "Amount to each address (%d satoshis) would be less than the dust limit. " "Choose a smaller number of addresses." % per_addr_amount) break curr_utxo_selector = self.utxo_selector def s(utxos_by_addr, amount, num_outputs, fees): return (utxos_by_addr, fees) self.utxo_selector = s addresses_and_amounts = {} for c in change_addresses: addresses_and_amounts[c] = per_addr_amount txids += self.send_to_multiple(addresses_and_amounts=addresses_and_amounts, use_unconfirmed=False, fees=fees, accounts=[acct]) self.utxo_selector = curr_utxo_selector return txids
[ "def", "spread_utxos", "(", "self", ",", "threshold", ",", "num_addresses", ",", "accounts", "=", "[", "]", ")", ":", "# Limit the number of spreading addresses so that we don't", "# create unnecessarily large transactions", "if", "num_addresses", "<", "1", "or", "num_addresses", ">", "100", ":", "raise", "ValueError", "(", "\"num_addresses must be > 0 and <= 100.\"", ")", "if", "not", "isinstance", "(", "threshold", ",", "int", ")", ":", "raise", "exceptions", ".", "SatoshiUnitsError", "(", "\"Can't send a non-integer amount of satoshis %s. Did you forget to convert from BTC?\"", "%", "(", "threshold", ",", ")", ")", "if", "not", "accounts", ":", "accts", "=", "self", ".", "_accounts", "else", ":", "accts", "=", "self", ".", "_check_and_get_accounts", "(", "accounts", ")", "txids", "=", "[", "]", "for", "acct", "in", "accts", ":", "utxos_by_addr", ",", "num_conf", "=", "self", ".", "get_utxos_above_threshold", "(", "threshold", ",", "False", ",", "[", "acct", "]", ")", "# Total up the value", "total_value", ",", "num_utxos", "=", "self", ".", "_sum_utxos", "(", "utxos_by_addr", ")", "if", "num_utxos", "==", "0", ":", "self", ".", "logger", ".", "error", "(", "\"No matching UTXOs for account %s (%d confirmed UTXOs). Not spreading.\"", "%", "(", "acct", ".", "name", ",", "num_conf", ")", ")", "break", "# Get the next num_addresses change addresses", "# We force address discovery here to make sure change", "# address generation doesn't end up violating the GAP", "# limit", "acct", ".", "_sync_txns", "(", "check_all", "=", "True", ")", "change_addresses", "=", "[", "acct", ".", "get_address", "(", "True", ")", "for", "i", "in", "range", "(", "num_addresses", ")", "]", "# Compute an approximate fee", "fee_amounts", "=", "txn_fees", ".", "get_fees", "(", ")", "fees", "=", "num_utxos", "*", "fee_amounts", "[", "'per_input'", "]", "+", "num_addresses", "*", "fee_amounts", "[", "'per_output'", "]", "spread_amount", "=", "total_value", "-", "fees", "per_addr_amount", "=", "int", "(", "spread_amount", "/", "num_addresses", ")", "if", "per_addr_amount", "<=", "txn_fees", ".", "DUST_LIMIT", ":", "self", ".", "logger", ".", "error", "(", "\"Amount to each address (%d satoshis) would be less than the dust limit. \"", "\"Choose a smaller number of addresses.\"", "%", "per_addr_amount", ")", "break", "curr_utxo_selector", "=", "self", ".", "utxo_selector", "def", "s", "(", "utxos_by_addr", ",", "amount", ",", "num_outputs", ",", "fees", ")", ":", "return", "(", "utxos_by_addr", ",", "fees", ")", "self", ".", "utxo_selector", "=", "s", "addresses_and_amounts", "=", "{", "}", "for", "c", "in", "change_addresses", ":", "addresses_and_amounts", "[", "c", "]", "=", "per_addr_amount", "txids", "+=", "self", ".", "send_to_multiple", "(", "addresses_and_amounts", "=", "addresses_and_amounts", ",", "use_unconfirmed", "=", "False", ",", "fees", "=", "fees", ",", "accounts", "=", "[", "acct", "]", ")", "self", ".", "utxo_selector", "=", "curr_utxo_selector", "return", "txids" ]
https://github.com/21dotco/two1-python/blob/4e833300fd5a58363e3104ed4c097631e5d296d3/two1/wallet/two1_wallet.py#L1511-L1590
nate-parrott/Flashlight
c3a7c7278a1cccf8918e7543faffc68e863ff5ab
PluginDirectories/1/calendar.bundle/jinja2/filters.py
python
do_title
(s)
return ''.join(rv)
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
[ "Return", "a", "titlecased", "version", "of", "the", "value", ".", "I", ".", "e", ".", "words", "will", "start", "with", "uppercase", "letters", "all", "remaining", "characters", "are", "lowercase", "." ]
def do_title(s): """Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase. """ rv = [] for item in re.compile(r'([-\s]+)(?u)').split(s): if not item: continue rv.append(item[0].upper() + item[1:].lower()) return ''.join(rv)
[ "def", "do_title", "(", "s", ")", ":", "rv", "=", "[", "]", "for", "item", "in", "re", ".", "compile", "(", "r'([-\\s]+)(?u)'", ")", ".", "split", "(", "s", ")", ":", "if", "not", "item", ":", "continue", "rv", ".", "append", "(", "item", "[", "0", "]", ".", "upper", "(", ")", "+", "item", "[", "1", ":", "]", ".", "lower", "(", ")", ")", "return", "''", ".", "join", "(", "rv", ")" ]
https://github.com/nate-parrott/Flashlight/blob/c3a7c7278a1cccf8918e7543faffc68e863ff5ab/PluginDirectories/1/calendar.bundle/jinja2/filters.py#L181-L190
equalitie/learn2ban
d45420c9d2eea2c81972c778a96a2ca42b318b6f
src/train2ban.py
python
Train2Ban.add_to_malicious_ips
(self, bad_ip_list)
Get a list of ips that the user knows they are malicious and add them to _malicious_ip_list INPUT: bad_ip_list: the ip list of strs to be indicated as 1 in training target
Get a list of ips that the user knows they are malicious and add them to _malicious_ip_list
[ "Get", "a", "list", "of", "ips", "that", "the", "user", "knows", "they", "are", "malicious", "and", "add", "them", "to", "_malicious_ip_list" ]
def add_to_malicious_ips(self, bad_ip_list): """ Get a list of ips that the user knows they are malicious and add them to _malicious_ip_list INPUT: bad_ip_list: the ip list of strs to be indicated as 1 in training target """ self._malicious_ip_list.extend(bad_ip_list)
[ "def", "add_to_malicious_ips", "(", "self", ",", "bad_ip_list", ")", ":", "self", ".", "_malicious_ip_list", ".", "extend", "(", "bad_ip_list", ")" ]
https://github.com/equalitie/learn2ban/blob/d45420c9d2eea2c81972c778a96a2ca42b318b6f/src/train2ban.py#L259-L268
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/analysis/eos.py
python
EOSBase._initial_guess
(self)
return e0, b0, b1, v0
Quadratic fit to get an initial guess for the parameters. Returns: tuple: (e0, b0, b1, v0)
Quadratic fit to get an initial guess for the parameters.
[ "Quadratic", "fit", "to", "get", "an", "initial", "guess", "for", "the", "parameters", "." ]
def _initial_guess(self): """ Quadratic fit to get an initial guess for the parameters. Returns: tuple: (e0, b0, b1, v0) """ a, b, c = np.polyfit(self.volumes, self.energies, 2) self.eos_params = [a, b, c] v0 = -b / (2 * a) e0 = a * (v0 ** 2) + b * v0 + c b0 = 2 * a * v0 b1 = 4 # b1 is usually a small number like 4 vmin, vmax = min(self.volumes), max(self.volumes) if not vmin < v0 and v0 < vmax: raise EOSError("The minimum volume of a fitted parabola is not in the input volumes\n.") return e0, b0, b1, v0
[ "def", "_initial_guess", "(", "self", ")", ":", "a", ",", "b", ",", "c", "=", "np", ".", "polyfit", "(", "self", ".", "volumes", ",", "self", ".", "energies", ",", "2", ")", "self", ".", "eos_params", "=", "[", "a", ",", "b", ",", "c", "]", "v0", "=", "-", "b", "/", "(", "2", "*", "a", ")", "e0", "=", "a", "*", "(", "v0", "**", "2", ")", "+", "b", "*", "v0", "+", "c", "b0", "=", "2", "*", "a", "*", "v0", "b1", "=", "4", "# b1 is usually a small number like 4", "vmin", ",", "vmax", "=", "min", "(", "self", ".", "volumes", ")", ",", "max", "(", "self", ".", "volumes", ")", "if", "not", "vmin", "<", "v0", "and", "v0", "<", "vmax", ":", "raise", "EOSError", "(", "\"The minimum volume of a fitted parabola is not in the input volumes\\n.\"", ")", "return", "e0", ",", "b0", ",", "b1", ",", "v0" ]
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/analysis/eos.py#L51-L71
dbrgn/RPLCD
e651d9cfc0e24e1ad47fe63cf50d3fec0d751c61
RPLCD/lcd.py
python
BaseCharLCD.cr
(self)
Write a carriage return (``\\r``) character to the LCD.
Write a carriage return (``\\r``) character to the LCD.
[ "Write", "a", "carriage", "return", "(", "\\\\", "r", ")", "character", "to", "the", "LCD", "." ]
def cr(self): # type: () -> None """Write a carriage return (``\\r``) character to the LCD.""" self.write_string('\r')
[ "def", "cr", "(", "self", ")", ":", "# type: () -> None", "self", ".", "write_string", "(", "'\\r'", ")" ]
https://github.com/dbrgn/RPLCD/blob/e651d9cfc0e24e1ad47fe63cf50d3fec0d751c61/RPLCD/lcd.py#L438-L440
althonos/pronto
6f778cd90b120a26e67eac2b94cc5b8694c4d517
pronto/entity/__init__.py
python
Entity.add_synonym
( self, description: str, scope: Optional[str] = None, type: Optional[SynonymType] = None, xrefs: Optional[Iterable[Xref]] = None, )
return Synonym(self._ontology(), data)
Add a new synonym to the current entity. Arguments: description (`str`): The alternate definition of the entity, or a related human-readable synonym. scope (`str` or `None`): An optional synonym scope. Must be either **EXACT**, **RELATED**, **BROAD** or **NARROW** if given. type (`~pronto.SynonymType` or `None`): An optional synonym type. Must be declared in the header of the current ontology. xrefs (iterable of `Xref`, or `None`): A collections of database cross-references backing the origin of the synonym. Raises: ValueError: when given an invalid synonym type or scope. Returns: `~pronto.Synonym`: A new synonym for the terms. The synonym is already added to the `Entity.synonyms` collection.
Add a new synonym to the current entity.
[ "Add", "a", "new", "synonym", "to", "the", "current", "entity", "." ]
def add_synonym( self, description: str, scope: Optional[str] = None, type: Optional[SynonymType] = None, xrefs: Optional[Iterable[Xref]] = None, ) -> Synonym: """Add a new synonym to the current entity. Arguments: description (`str`): The alternate definition of the entity, or a related human-readable synonym. scope (`str` or `None`): An optional synonym scope. Must be either **EXACT**, **RELATED**, **BROAD** or **NARROW** if given. type (`~pronto.SynonymType` or `None`): An optional synonym type. Must be declared in the header of the current ontology. xrefs (iterable of `Xref`, or `None`): A collections of database cross-references backing the origin of the synonym. Raises: ValueError: when given an invalid synonym type or scope. Returns: `~pronto.Synonym`: A new synonym for the terms. The synonym is already added to the `Entity.synonyms` collection. """ # check the type is declared in the current ontology if type is None: type_id: Optional[str] = None else: try: type_id = self._ontology().get_synonym_type(type.id).id except KeyError as ke: raise ValueError(f"undeclared synonym type {type.id!r}") from ke data = SynonymData(description, scope, type_id, xrefs=xrefs) self._data().synonyms.add(data) return Synonym(self._ontology(), data)
[ "def", "add_synonym", "(", "self", ",", "description", ":", "str", ",", "scope", ":", "Optional", "[", "str", "]", "=", "None", ",", "type", ":", "Optional", "[", "SynonymType", "]", "=", "None", ",", "xrefs", ":", "Optional", "[", "Iterable", "[", "Xref", "]", "]", "=", "None", ",", ")", "->", "Synonym", ":", "# check the type is declared in the current ontology", "if", "type", "is", "None", ":", "type_id", ":", "Optional", "[", "str", "]", "=", "None", "else", ":", "try", ":", "type_id", "=", "self", ".", "_ontology", "(", ")", ".", "get_synonym_type", "(", "type", ".", "id", ")", ".", "id", "except", "KeyError", "as", "ke", ":", "raise", "ValueError", "(", "f\"undeclared synonym type {type.id!r}\"", ")", "from", "ke", "data", "=", "SynonymData", "(", "description", ",", "scope", ",", "type_id", ",", "xrefs", "=", "xrefs", ")", "self", ".", "_data", "(", ")", ".", "synonyms", ".", "add", "(", "data", ")", "return", "Synonym", "(", "self", ".", "_ontology", "(", ")", ",", "data", ")" ]
https://github.com/althonos/pronto/blob/6f778cd90b120a26e67eac2b94cc5b8694c4d517/pronto/entity/__init__.py#L510-L548
scrapinghub/frontera
84f9e1034d2868447db88e865596c0fbb32e70f6
frontera/utils/url.py
python
parse_domain_from_url_fast
(url)
return result.netloc, result.hostname, result.scheme, "", "", ""
Extract domain info from a passed url, without analyzing subdomains and tld
Extract domain info from a passed url, without analyzing subdomains and tld
[ "Extract", "domain", "info", "from", "a", "passed", "url", "without", "analyzing", "subdomains", "and", "tld" ]
def parse_domain_from_url_fast(url): """ Extract domain info from a passed url, without analyzing subdomains and tld """ result = parse_url(url) return result.netloc, result.hostname, result.scheme, "", "", ""
[ "def", "parse_domain_from_url_fast", "(", "url", ")", ":", "result", "=", "parse_url", "(", "url", ")", "return", "result", ".", "netloc", ",", "result", ".", "hostname", ",", "result", ".", "scheme", ",", "\"\"", ",", "\"\"", ",", "\"\"" ]
https://github.com/scrapinghub/frontera/blob/84f9e1034d2868447db88e865596c0fbb32e70f6/frontera/utils/url.py#L39-L44
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/idlelib/ColorDelegator.py
python
ColorDelegator.delete
(self, index1, index2=None)
[]
def delete(self, index1, index2=None): index1 = self.index(index1) self.delegate.delete(index1, index2) self.notify_range(index1)
[ "def", "delete", "(", "self", ",", "index1", ",", "index2", "=", "None", ")", ":", "index1", "=", "self", ".", "index", "(", "index1", ")", "self", ".", "delegate", ".", "delete", "(", "index1", ",", "index2", ")", "self", ".", "notify_range", "(", "index1", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/idlelib/ColorDelegator.py#L83-L86
sahana/eden
1696fa50e90ce967df69f66b571af45356cc18da
modules/templates/SHARE/config.py
python
NeedResponseLineReportRepresent.__call__
(self, record_ids)
return output
Represent record_ids (custom) Args: record_ids: need_response_line record IDs Returns: JSON-serializable dict {recordID: representation}
Represent record_ids (custom)
[ "Represent", "record_ids", "(", "custom", ")" ]
def __call__(self, record_ids): """ Represent record_ids (custom) Args: record_ids: need_response_line record IDs Returns: JSON-serializable dict {recordID: representation} """ # Represent the location IDs resource = current.s3db.resource("need_response_line", id = record_ids, ) rows = resource.select(["id", "coarse_location_id", "location_id"], represent = True, raw_data = True, limit = None, ).rows output = {} for row in rows: raw = row["_row"] if raw["need_response_line.location_id"]: repr_str = row["need_response_line.location_id"] else: # Fall back to coarse_location_id if no GN available repr_str = row["need_response_line.coarse_location_id"] output[raw["need_response_line.id"]] = repr_str return output
[ "def", "__call__", "(", "self", ",", "record_ids", ")", ":", "# Represent the location IDs", "resource", "=", "current", ".", "s3db", ".", "resource", "(", "\"need_response_line\"", ",", "id", "=", "record_ids", ",", ")", "rows", "=", "resource", ".", "select", "(", "[", "\"id\"", ",", "\"coarse_location_id\"", ",", "\"location_id\"", "]", ",", "represent", "=", "True", ",", "raw_data", "=", "True", ",", "limit", "=", "None", ",", ")", ".", "rows", "output", "=", "{", "}", "for", "row", "in", "rows", ":", "raw", "=", "row", "[", "\"_row\"", "]", "if", "raw", "[", "\"need_response_line.location_id\"", "]", ":", "repr_str", "=", "row", "[", "\"need_response_line.location_id\"", "]", "else", ":", "# Fall back to coarse_location_id if no GN available", "repr_str", "=", "row", "[", "\"need_response_line.coarse_location_id\"", "]", "output", "[", "raw", "[", "\"need_response_line.id\"", "]", "]", "=", "repr_str", "return", "output" ]
https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/templates/SHARE/config.py#L2504-L2536
google/yapf
b49a261870870e91fe693b1b871a4afbd7af7bd6
yapf/yapflib/reformatter.py
python
_LineContainsPylintDisableLineTooLong
(line)
return re.search(r'\bpylint:\s+disable=line-too-long\b', line.last.value)
Return true if there is a "pylint: disable=line-too-long" comment.
Return true if there is a "pylint: disable=line-too-long" comment.
[ "Return", "true", "if", "there", "is", "a", "pylint", ":", "disable", "=", "line", "-", "too", "-", "long", "comment", "." ]
def _LineContainsPylintDisableLineTooLong(line): """Return true if there is a "pylint: disable=line-too-long" comment.""" return re.search(r'\bpylint:\s+disable=line-too-long\b', line.last.value)
[ "def", "_LineContainsPylintDisableLineTooLong", "(", "line", ")", ":", "return", "re", ".", "search", "(", "r'\\bpylint:\\s+disable=line-too-long\\b'", ",", "line", ".", "last", ".", "value", ")" ]
https://github.com/google/yapf/blob/b49a261870870e91fe693b1b871a4afbd7af7bd6/yapf/yapflib/reformatter.py#L232-L234
largelymfs/topical_word_embeddings
1ae3d15d0afcd3fcd39cc81eec4ad9463413a9f6
TWE-3/gensim/corpora/indexedcorpus.py
python
IndexedCorpus.__init__
(self, fname, index_fname=None)
Initialize this abstract base class, by loading a previously saved index from `index_fname` (or `fname.index` if `index_fname` is not set). This index will allow subclasses to support the `corpus[docno]` syntax (random access to document #`docno` in O(1)). >>> # save corpus in SvmLightCorpus format with an index >>> corpus = [[(1, 0.5)], [(0, 1.0), (1, 2.0)]] >>> gensim.corpora.SvmLightCorpus.serialize('testfile.svmlight', corpus) >>> # load back as a document stream (*not* plain Python list) >>> corpus_with_random_access = gensim.corpora.SvmLightCorpus('tstfile.svmlight') >>> print(corpus_with_random_access[1]) [(0, 1.0), (1, 2.0)]
Initialize this abstract base class, by loading a previously saved index from `index_fname` (or `fname.index` if `index_fname` is not set). This index will allow subclasses to support the `corpus[docno]` syntax (random access to document #`docno` in O(1)).
[ "Initialize", "this", "abstract", "base", "class", "by", "loading", "a", "previously", "saved", "index", "from", "index_fname", "(", "or", "fname", ".", "index", "if", "index_fname", "is", "not", "set", ")", ".", "This", "index", "will", "allow", "subclasses", "to", "support", "the", "corpus", "[", "docno", "]", "syntax", "(", "random", "access", "to", "document", "#", "docno", "in", "O", "(", "1", "))", "." ]
def __init__(self, fname, index_fname=None): """ Initialize this abstract base class, by loading a previously saved index from `index_fname` (or `fname.index` if `index_fname` is not set). This index will allow subclasses to support the `corpus[docno]` syntax (random access to document #`docno` in O(1)). >>> # save corpus in SvmLightCorpus format with an index >>> corpus = [[(1, 0.5)], [(0, 1.0), (1, 2.0)]] >>> gensim.corpora.SvmLightCorpus.serialize('testfile.svmlight', corpus) >>> # load back as a document stream (*not* plain Python list) >>> corpus_with_random_access = gensim.corpora.SvmLightCorpus('tstfile.svmlight') >>> print(corpus_with_random_access[1]) [(0, 1.0), (1, 2.0)] """ try: if index_fname is None: index_fname = fname + '.index' self.index = utils.unpickle(index_fname) logger.info("loaded corpus index from %s" % index_fname) except: self.index = None self.length = None
[ "def", "__init__", "(", "self", ",", "fname", ",", "index_fname", "=", "None", ")", ":", "try", ":", "if", "index_fname", "is", "None", ":", "index_fname", "=", "fname", "+", "'.index'", "self", ".", "index", "=", "utils", ".", "unpickle", "(", "index_fname", ")", "logger", ".", "info", "(", "\"loaded corpus index from %s\"", "%", "index_fname", ")", "except", ":", "self", ".", "index", "=", "None", "self", ".", "length", "=", "None" ]
https://github.com/largelymfs/topical_word_embeddings/blob/1ae3d15d0afcd3fcd39cc81eec4ad9463413a9f6/TWE-3/gensim/corpora/indexedcorpus.py#L29-L52
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/qark/qark/lib/blessings/__init__.py
python
Terminal.location
(self, x=None, y=None)
Return a context manager for temporarily moving the cursor. Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:: term = Terminal() with term.location(2, 5): print 'Hello, world!' for x in xrange(10): print 'I can do it %i times!' % x Specify ``x`` to move to a certain column, ``y`` to move to a certain row, both, or neither. If you specify neither, only the saving and restoration of cursor position will happen. This can be useful if you simply want to restore your place after doing some manual cursor movement.
Return a context manager for temporarily moving the cursor.
[ "Return", "a", "context", "manager", "for", "temporarily", "moving", "the", "cursor", "." ]
def location(self, x=None, y=None): """Return a context manager for temporarily moving the cursor. Move the cursor to a certain position on entry, let you print stuff there, then return the cursor to its original position:: term = Terminal() with term.location(2, 5): print 'Hello, world!' for x in xrange(10): print 'I can do it %i times!' % x Specify ``x`` to move to a certain column, ``y`` to move to a certain row, both, or neither. If you specify neither, only the saving and restoration of cursor position will happen. This can be useful if you simply want to restore your place after doing some manual cursor movement. """ # Save position and move to the requested column, row, or both: self.stream.write(self.save) if x is not None and y is not None: self.stream.write(self.move(y, x)) elif x is not None: self.stream.write(self.move_x(x)) elif y is not None: self.stream.write(self.move_y(y)) try: yield finally: # Restore original cursor position: self.stream.write(self.restore)
[ "def", "location", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ")", ":", "# Save position and move to the requested column, row, or both:", "self", ".", "stream", ".", "write", "(", "self", ".", "save", ")", "if", "x", "is", "not", "None", "and", "y", "is", "not", "None", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "move", "(", "y", ",", "x", ")", ")", "elif", "x", "is", "not", "None", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "move_x", "(", "x", ")", ")", "elif", "y", "is", "not", "None", ":", "self", ".", "stream", ".", "write", "(", "self", ".", "move_y", "(", "y", ")", ")", "try", ":", "yield", "finally", ":", "# Restore original cursor position:", "self", ".", "stream", ".", "write", "(", "self", ".", "restore", ")" ]
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/qark/qark/lib/blessings/__init__.py#L244-L275
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/returns/estimators.py
python
AdvantageEstimator._evaluate
(self)
return self.returns
Evaluate the estimator / return. Returns: torch.Tensor: the computed returns.
Evaluate the estimator / return.
[ "Evaluate", "the", "estimator", "/", "return", "." ]
def _evaluate(self): """Evaluate the estimator / return. Returns: torch.Tensor: the computed returns. """ # get values from storage if present. If not, evaluate the value based on the states. if self._value in self.storage: values = self.storage[self._value] else: values = self._value(self.states) # get Q-values/estimators from storage if present. If not, evaluate the Q-values based on the states and # actions. if self._q_value in self.storage: q_values = self.storage[self._q_value] else: if isinstance(self._q_value, Estimator): # evaluate the estimator self._q_value.evaluate() # get the returns q_values = self.storage[self._q_value] else: q_values = self._q_value(self.states, self.actions) # compute the advantage estimates returns = q_values - values # standardize the advantage estimates if self._standardize: returns = (returns - returns.mean()) / (returns.std() + 1.e-5) # set the returns self.returns[:] = returns return self.returns
[ "def", "_evaluate", "(", "self", ")", ":", "# get values from storage if present. If not, evaluate the value based on the states.", "if", "self", ".", "_value", "in", "self", ".", "storage", ":", "values", "=", "self", ".", "storage", "[", "self", ".", "_value", "]", "else", ":", "values", "=", "self", ".", "_value", "(", "self", ".", "states", ")", "# get Q-values/estimators from storage if present. If not, evaluate the Q-values based on the states and", "# actions.", "if", "self", ".", "_q_value", "in", "self", ".", "storage", ":", "q_values", "=", "self", ".", "storage", "[", "self", ".", "_q_value", "]", "else", ":", "if", "isinstance", "(", "self", ".", "_q_value", ",", "Estimator", ")", ":", "# evaluate the estimator", "self", ".", "_q_value", ".", "evaluate", "(", ")", "# get the returns", "q_values", "=", "self", ".", "storage", "[", "self", ".", "_q_value", "]", "else", ":", "q_values", "=", "self", ".", "_q_value", "(", "self", ".", "states", ",", "self", ".", "actions", ")", "# compute the advantage estimates", "returns", "=", "q_values", "-", "values", "# standardize the advantage estimates", "if", "self", ".", "_standardize", ":", "returns", "=", "(", "returns", "-", "returns", ".", "mean", "(", ")", ")", "/", "(", "returns", ".", "std", "(", ")", "+", "1.e-5", ")", "# set the returns", "self", ".", "returns", "[", ":", "]", "=", "returns", "return", "self", ".", "returns" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/returns/estimators.py#L468-L503
matrix-org/synapse
8e57584a5859a9002759963eb546d523d2498a01
synapse/config/password_auth_providers.py
python
PasswordAuthProviderConfig.read_config
(self, config, **kwargs)
Parses the old password auth providers config. The config format looks like this: password_providers: # Example config for an LDAP auth provider - module: "ldap_auth_provider.LdapAuthProvider" config: enabled: true uri: "ldap://ldap.example.com:389" start_tls: true base: "ou=users,dc=example,dc=com" attributes: uid: "cn" mail: "email" name: "givenName" #bind_dn: #bind_password: #filter: "(objectClass=posixAccount)" We expect admins to use modules for this feature (which is why it doesn't appear in the sample config file), but we want to keep support for it around for a bit for backwards compatibility.
Parses the old password auth providers config. The config format looks like this:
[ "Parses", "the", "old", "password", "auth", "providers", "config", ".", "The", "config", "format", "looks", "like", "this", ":" ]
def read_config(self, config, **kwargs): """Parses the old password auth providers config. The config format looks like this: password_providers: # Example config for an LDAP auth provider - module: "ldap_auth_provider.LdapAuthProvider" config: enabled: true uri: "ldap://ldap.example.com:389" start_tls: true base: "ou=users,dc=example,dc=com" attributes: uid: "cn" mail: "email" name: "givenName" #bind_dn: #bind_password: #filter: "(objectClass=posixAccount)" We expect admins to use modules for this feature (which is why it doesn't appear in the sample config file), but we want to keep support for it around for a bit for backwards compatibility. """ self.password_providers: List[Tuple[Type, Any]] = [] providers = [] # We want to be backwards compatible with the old `ldap_config` # param. ldap_config = config.get("ldap_config", {}) if ldap_config.get("enabled", False): providers.append({"module": LDAP_PROVIDER, "config": ldap_config}) providers.extend(config.get("password_providers") or []) for i, provider in enumerate(providers): mod_name = provider["module"] # This is for backwards compat when the ldap auth provider resided # in this package. if mod_name == "synapse.util.ldap_auth_provider.LdapAuthProvider": mod_name = LDAP_PROVIDER (provider_class, provider_config) = load_module( {"module": mod_name, "config": provider["config"]}, ("password_providers", "<item %i>" % i), ) self.password_providers.append((provider_class, provider_config))
[ "def", "read_config", "(", "self", ",", "config", ",", "*", "*", "kwargs", ")", ":", "self", ".", "password_providers", ":", "List", "[", "Tuple", "[", "Type", ",", "Any", "]", "]", "=", "[", "]", "providers", "=", "[", "]", "# We want to be backwards compatible with the old `ldap_config`", "# param.", "ldap_config", "=", "config", ".", "get", "(", "\"ldap_config\"", ",", "{", "}", ")", "if", "ldap_config", ".", "get", "(", "\"enabled\"", ",", "False", ")", ":", "providers", ".", "append", "(", "{", "\"module\"", ":", "LDAP_PROVIDER", ",", "\"config\"", ":", "ldap_config", "}", ")", "providers", ".", "extend", "(", "config", ".", "get", "(", "\"password_providers\"", ")", "or", "[", "]", ")", "for", "i", ",", "provider", "in", "enumerate", "(", "providers", ")", ":", "mod_name", "=", "provider", "[", "\"module\"", "]", "# This is for backwards compat when the ldap auth provider resided", "# in this package.", "if", "mod_name", "==", "\"synapse.util.ldap_auth_provider.LdapAuthProvider\"", ":", "mod_name", "=", "LDAP_PROVIDER", "(", "provider_class", ",", "provider_config", ")", "=", "load_module", "(", "{", "\"module\"", ":", "mod_name", ",", "\"config\"", ":", "provider", "[", "\"config\"", "]", "}", ",", "(", "\"password_providers\"", ",", "\"<item %i>\"", "%", "i", ")", ",", ")", "self", ".", "password_providers", ".", "append", "(", "(", "provider_class", ",", "provider_config", ")", ")" ]
https://github.com/matrix-org/synapse/blob/8e57584a5859a9002759963eb546d523d2498a01/synapse/config/password_auth_providers.py#L27-L74
bmuller/kademlia
cf55e658cf4bb162041be8f9d465602723a387ad
kademlia/network.py
python
Server.save_state
(self, fname)
Save the state of this node (the alpha/ksize/id/immediate neighbors) to a cache file with the given fname.
Save the state of this node (the alpha/ksize/id/immediate neighbors) to a cache file with the given fname.
[ "Save", "the", "state", "of", "this", "node", "(", "the", "alpha", "/", "ksize", "/", "id", "/", "immediate", "neighbors", ")", "to", "a", "cache", "file", "with", "the", "given", "fname", "." ]
def save_state(self, fname): """ Save the state of this node (the alpha/ksize/id/immediate neighbors) to a cache file with the given fname. """ log.info("Saving state to %s", fname) data = { 'ksize': self.ksize, 'alpha': self.alpha, 'id': self.node.id, 'neighbors': self.bootstrappable_neighbors() } if not data['neighbors']: log.warning("No known neighbors, so not writing to cache.") return with open(fname, 'wb') as file: pickle.dump(data, file)
[ "def", "save_state", "(", "self", ",", "fname", ")", ":", "log", ".", "info", "(", "\"Saving state to %s\"", ",", "fname", ")", "data", "=", "{", "'ksize'", ":", "self", ".", "ksize", ",", "'alpha'", ":", "self", ".", "alpha", ",", "'id'", ":", "self", ".", "node", ".", "id", ",", "'neighbors'", ":", "self", ".", "bootstrappable_neighbors", "(", ")", "}", "if", "not", "data", "[", "'neighbors'", "]", ":", "log", ".", "warning", "(", "\"No known neighbors, so not writing to cache.\"", ")", "return", "with", "open", "(", "fname", ",", "'wb'", ")", "as", "file", ":", "pickle", ".", "dump", "(", "data", ",", "file", ")" ]
https://github.com/bmuller/kademlia/blob/cf55e658cf4bb162041be8f9d465602723a387ad/kademlia/network.py#L195-L211