repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
chrisspen/dtree
dtree.py
Forest.best_oob_mae_weight
def best_oob_mae_weight(trees): """ Returns weights so that the tree with smallest out-of-bag mean absolute error """ best = (+1e999999, None) for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: cont...
python
def best_oob_mae_weight(trees): """ Returns weights so that the tree with smallest out-of-bag mean absolute error """ best = (+1e999999, None) for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: cont...
[ "def", "best_oob_mae_weight", "(", "trees", ")", ":", "best", "=", "(", "+", "1e999999", ",", "None", ")", "for", "tree", "in", "trees", ":", "oob_mae", "=", "tree", ".", "out_of_bag_mae", "if", "oob_mae", "is", "None", "or", "oob_mae", ".", "mean", "i...
Returns weights so that the tree with smallest out-of-bag mean absolute error
[ "Returns", "weights", "so", "that", "the", "tree", "with", "smallest", "out", "-", "of", "-", "bag", "mean", "absolute", "error" ]
train
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1492-L1505
chrisspen/dtree
dtree.py
Forest.mean_oob_mae_weight
def mean_oob_mae_weight(trees): """ Returns weights proportional to the out-of-bag mean absolute error for each tree. """ weights = [] active_trees = [] for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: ...
python
def mean_oob_mae_weight(trees): """ Returns weights proportional to the out-of-bag mean absolute error for each tree. """ weights = [] active_trees = [] for tree in trees: oob_mae = tree.out_of_bag_mae if oob_mae is None or oob_mae.mean is None: ...
[ "def", "mean_oob_mae_weight", "(", "trees", ")", ":", "weights", "=", "[", "]", "active_trees", "=", "[", "]", "for", "tree", "in", "trees", ":", "oob_mae", "=", "tree", ".", "out_of_bag_mae", "if", "oob_mae", "is", "None", "or", "oob_mae", ".", "mean", ...
Returns weights proportional to the out-of-bag mean absolute error for each tree.
[ "Returns", "weights", "proportional", "to", "the", "out", "-", "of", "-", "bag", "mean", "absolute", "error", "for", "each", "tree", "." ]
train
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1508-L1523
chrisspen/dtree
dtree.py
Forest._grow_trees
def _grow_trees(self): """ Adds new trees to the forest according to the specified growth method. """ if self.grow_method == GROW_AUTO_INCREMENTAL: self.tree_kwargs['auto_grow'] = True while len(self.trees) < self.size: self.trees.append(Tree(data...
python
def _grow_trees(self): """ Adds new trees to the forest according to the specified growth method. """ if self.grow_method == GROW_AUTO_INCREMENTAL: self.tree_kwargs['auto_grow'] = True while len(self.trees) < self.size: self.trees.append(Tree(data...
[ "def", "_grow_trees", "(", "self", ")", ":", "if", "self", ".", "grow_method", "==", "GROW_AUTO_INCREMENTAL", ":", "self", ".", "tree_kwargs", "[", "'auto_grow'", "]", "=", "True", "while", "len", "(", "self", ".", "trees", ")", "<", "self", ".", "size",...
Adds new trees to the forest according to the specified growth method.
[ "Adds", "new", "trees", "to", "the", "forest", "according", "to", "the", "specified", "growth", "method", "." ]
train
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1525-L1533
chrisspen/dtree
dtree.py
Forest.predict
def predict(self, record): """ Attempts to predict the value of the class attribute by aggregating the predictions of each tree. Parameters: weighting_formula := a callable that takes a list of trees and returns a list of weights. """ ...
python
def predict(self, record): """ Attempts to predict the value of the class attribute by aggregating the predictions of each tree. Parameters: weighting_formula := a callable that takes a list of trees and returns a list of weights. """ ...
[ "def", "predict", "(", "self", ",", "record", ")", ":", "# Get raw predictions.", "# {tree:raw prediction}", "predictions", "=", "{", "}", "for", "tree", "in", "self", ".", "trees", ":", "_p", "=", "tree", ".", "predict", "(", "record", ")", "if", "_p", ...
Attempts to predict the value of the class attribute by aggregating the predictions of each tree. Parameters: weighting_formula := a callable that takes a list of trees and returns a list of weights.
[ "Attempts", "to", "predict", "the", "value", "of", "the", "class", "attribute", "by", "aggregating", "the", "predictions", "of", "each", "tree", ".", "Parameters", ":", "weighting_formula", ":", "=", "a", "callable", "that", "takes", "a", "list", "of", "tree...
train
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1539-L1582
chrisspen/dtree
dtree.py
Forest.train
def train(self, record): """ Updates the trees with the given training record. """ self._fell_trees() self._grow_trees() for tree in self.trees: if random.random() < self.sample_ratio: tree.train(record) else: tree.o...
python
def train(self, record): """ Updates the trees with the given training record. """ self._fell_trees() self._grow_trees() for tree in self.trees: if random.random() < self.sample_ratio: tree.train(record) else: tree.o...
[ "def", "train", "(", "self", ",", "record", ")", ":", "self", ".", "_fell_trees", "(", ")", "self", ".", "_grow_trees", "(", ")", "for", "tree", "in", "self", ".", "trees", ":", "if", "random", ".", "random", "(", ")", "<", "self", ".", "sample_rat...
Updates the trees with the given training record.
[ "Updates", "the", "trees", "with", "the", "given", "training", "record", "." ]
train
https://github.com/chrisspen/dtree/blob/9e9c9992b22ad9a7e296af7e6837666b05db43ef/dtree.py#L1613-L1625
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
get_configfile_paths
def get_configfile_paths(system=True, user=True, local=True, only_existing=True): """Return a list of local configuration file paths. Search paths for configuration files on the local system are based on homebase_ and depend on operating system; for example, for Linux systems these might include ``dwav...
python
def get_configfile_paths(system=True, user=True, local=True, only_existing=True): """Return a list of local configuration file paths. Search paths for configuration files on the local system are based on homebase_ and depend on operating system; for example, for Linux systems these might include ``dwav...
[ "def", "get_configfile_paths", "(", "system", "=", "True", ",", "user", "=", "True", ",", "local", "=", "True", ",", "only_existing", "=", "True", ")", ":", "candidates", "=", "[", "]", "# system-wide has the lowest priority, `/etc/dwave/dwave.conf`", "if", "syste...
Return a list of local configuration file paths. Search paths for configuration files on the local system are based on homebase_ and depend on operating system; for example, for Linux systems these might include ``dwave.conf`` in the current working directory (CWD), user-local ``.config/dwave/``, and s...
[ "Return", "a", "list", "of", "local", "configuration", "file", "paths", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L239-L304
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
get_default_configfile_path
def get_default_configfile_path(): """Return the default configuration-file path. Typically returns a user-local configuration file; e.g: ``~/.config/dwave/dwave.conf``. Returns: str: Configuration file path. Examples: This example displays the default configuration fi...
python
def get_default_configfile_path(): """Return the default configuration-file path. Typically returns a user-local configuration file; e.g: ``~/.config/dwave/dwave.conf``. Returns: str: Configuration file path. Examples: This example displays the default configuration fi...
[ "def", "get_default_configfile_path", "(", ")", ":", "base", "=", "homebase", ".", "user_config_dir", "(", "app_author", "=", "CONF_AUTHOR", ",", "app_name", "=", "CONF_APP", ",", "roaming", "=", "False", ",", "use_virtualenv", "=", "False", ",", "create", "="...
Return the default configuration-file path. Typically returns a user-local configuration file; e.g: ``~/.config/dwave/dwave.conf``. Returns: str: Configuration file path. Examples: This example displays the default configuration file on an Ubuntu Unix system runnin...
[ "Return", "the", "default", "configuration", "-", "file", "path", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L336-L367
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
load_config_from_files
def load_config_from_files(filenames=None): """Load D-Wave Cloud Client configuration from a list of files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. ...
python
def load_config_from_files(filenames=None): """Load D-Wave Cloud Client configuration from a list of files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. ...
[ "def", "load_config_from_files", "(", "filenames", "=", "None", ")", ":", "if", "filenames", "is", "None", ":", "filenames", "=", "get_configfile_paths", "(", ")", "config", "=", "configparser", ".", "ConfigParser", "(", "default_section", "=", "\"defaults\"", "...
Load D-Wave Cloud Client configuration from a list of files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standard Windows ...
[ "Load", "D", "-", "Wave", "Cloud", "Client", "configuration", "from", "a", "list", "of", "files", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L370-L468
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
load_profile_from_files
def load_profile_from_files(filenames=None, profile=None): """Load a profile from a list of D-Wave Cloud Client configuration files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config....
python
def load_profile_from_files(filenames=None, profile=None): """Load a profile from a list of D-Wave Cloud Client configuration files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config....
[ "def", "load_profile_from_files", "(", "filenames", "=", "None", ",", "profile", "=", "None", ")", ":", "# progressively build config from a file, or a list of auto-detected files", "# raises ConfigFileReadError/ConfigFileParseError on error", "config", "=", "load_config_from_files",...
Load a profile from a list of D-Wave Cloud Client configuration files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config.load_config` instead. Configuration files comply with standar...
[ "Load", "a", "profile", "from", "a", "list", "of", "D", "-", "Wave", "Cloud", "Client", "configuration", "files", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L471-L584
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
load_config
def load_config(config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None): """Load D-Wave Cloud Client configuration based on a configuration file. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highes...
python
def load_config(config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None): """Load D-Wave Cloud Client configuration based on a configuration file. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highes...
[ "def", "load_config", "(", "config_file", "=", "None", ",", "profile", "=", "None", ",", "client", "=", "None", ",", "endpoint", "=", "None", ",", "token", "=", "None", ",", "solver", "=", "None", ",", "proxy", "=", "None", ")", ":", "if", "profile",...
Load D-Wave Cloud Client configuration based on a configuration file. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`load_config()`. These values replace values read from a configu...
[ "Load", "D", "-", "Wave", "Cloud", "Client", "configuration", "based", "on", "a", "configuration", "file", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L619-L778
dwavesystems/dwave-cloud-client
dwave/cloud/config.py
legacy_load_config
def legacy_load_config(profile=None, endpoint=None, token=None, solver=None, proxy=None, **kwargs): """Load configured URLs and token for the SAPI server. .. warning:: Included only for backward compatibility. Please use :func:`load_config` or the client factory :meth:`~d...
python
def legacy_load_config(profile=None, endpoint=None, token=None, solver=None, proxy=None, **kwargs): """Load configured URLs and token for the SAPI server. .. warning:: Included only for backward compatibility. Please use :func:`load_config` or the client factory :meth:`~d...
[ "def", "legacy_load_config", "(", "profile", "=", "None", ",", "endpoint", "=", "None", ",", "token", "=", "None", ",", "solver", "=", "None", ",", "proxy", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "_parse_config", "(", "fp", ",", "file...
Load configured URLs and token for the SAPI server. .. warning:: Included only for backward compatibility. Please use :func:`load_config` or the client factory :meth:`~dwave.cloud.client.Client.from_config` instead. This method tries to load a legacy configuration file from ``~/.dwrc``, select...
[ "Load", "configured", "URLs", "and", "token", "for", "the", "SAPI", "server", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/config.py#L781-L925
tuxu/python-samplerate
samplerate/lowlevel.py
_check_data
def _check_data(data): """Check whether `data` is a valid input/output for libsamplerate. Returns ------- num_frames Number of frames in `data`. channels Number of channels in `data`. Raises ------ ValueError: If invalid data is supplied. """ if not (data.dt...
python
def _check_data(data): """Check whether `data` is a valid input/output for libsamplerate. Returns ------- num_frames Number of frames in `data`. channels Number of channels in `data`. Raises ------ ValueError: If invalid data is supplied. """ if not (data.dt...
[ "def", "_check_data", "(", "data", ")", ":", "if", "not", "(", "data", ".", "dtype", "==", "_np", ".", "float32", "and", "data", ".", "flags", ".", "c_contiguous", ")", ":", "raise", "ValueError", "(", "'supplied data must be float32 and C contiguous'", ")", ...
Check whether `data` is a valid input/output for libsamplerate. Returns ------- num_frames Number of frames in `data`. channels Number of channels in `data`. Raises ------ ValueError: If invalid data is supplied.
[ "Check", "whether", "data", "is", "a", "valid", "input", "/", "output", "for", "libsamplerate", "." ]
train
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L41-L63
tuxu/python-samplerate
samplerate/lowlevel.py
src_simple
def src_simple(input_data, output_data, ratio, converter_type, channels): """Perform a single conversion from an input buffer to an output buffer. Simple interface for performing a single conversion from input buffer to output buffer at a fixed conversion ratio. Simple interface does not require initia...
python
def src_simple(input_data, output_data, ratio, converter_type, channels): """Perform a single conversion from an input buffer to an output buffer. Simple interface for performing a single conversion from input buffer to output buffer at a fixed conversion ratio. Simple interface does not require initia...
[ "def", "src_simple", "(", "input_data", ",", "output_data", ",", "ratio", ",", "converter_type", ",", "channels", ")", ":", "input_frames", ",", "_", "=", "_check_data", "(", "input_data", ")", "output_frames", ",", "_", "=", "_check_data", "(", "output_data",...
Perform a single conversion from an input buffer to an output buffer. Simple interface for performing a single conversion from input buffer to output buffer at a fixed conversion ratio. Simple interface does not require initialisation as it can only operate on a single buffer worth of audio.
[ "Perform", "a", "single", "conversion", "from", "an", "input", "buffer", "to", "an", "output", "buffer", "." ]
train
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L86-L102
tuxu/python-samplerate
samplerate/lowlevel.py
src_new
def src_new(converter_type, channels): """Initialise a new sample rate converter. Parameters ---------- converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converte...
python
def src_new(converter_type, channels): """Initialise a new sample rate converter. Parameters ---------- converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converte...
[ "def", "src_new", "(", "converter_type", ",", "channels", ")", ":", "error", "=", "ffi", ".", "new", "(", "'int*'", ")", "state", "=", "_lib", ".", "src_new", "(", "converter_type", ",", "channels", ",", "error", ")", "return", "state", ",", "error", "...
Initialise a new sample rate converter. Parameters ---------- converter_type : int Converter to be used. channels : int Number of channels. Returns ------- state An anonymous pointer to the internal state of the converter. error : int Error code.
[ "Initialise", "a", "new", "sample", "rate", "converter", "." ]
train
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L105-L124
tuxu/python-samplerate
samplerate/lowlevel.py
src_process
def src_process(state, input_data, output_data, ratio, end_of_input=0): """Standard processing function. Returns non zero on error. """ input_frames, _ = _check_data(input_data) output_frames, _ = _check_data(output_data) data = ffi.new('SRC_DATA*') data.input_frames = input_frames data...
python
def src_process(state, input_data, output_data, ratio, end_of_input=0): """Standard processing function. Returns non zero on error. """ input_frames, _ = _check_data(input_data) output_frames, _ = _check_data(output_data) data = ffi.new('SRC_DATA*') data.input_frames = input_frames data...
[ "def", "src_process", "(", "state", ",", "input_data", ",", "output_data", ",", "ratio", ",", "end_of_input", "=", "0", ")", ":", "input_frames", ",", "_", "=", "_check_data", "(", "input_data", ")", "output_frames", ",", "_", "=", "_check_data", "(", "out...
Standard processing function. Returns non zero on error.
[ "Standard", "processing", "function", "." ]
train
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L135-L150
tuxu/python-samplerate
samplerate/lowlevel.py
_src_input_callback
def _src_input_callback(cb_data, data): """Internal callback function to be used with the callback API. Pulls the Python callback function from the handle contained in `cb_data` and calls it to fetch frames. Frames are converted to the format required by the API (float, interleaved channels). A referen...
python
def _src_input_callback(cb_data, data): """Internal callback function to be used with the callback API. Pulls the Python callback function from the handle contained in `cb_data` and calls it to fetch frames. Frames are converted to the format required by the API (float, interleaved channels). A referen...
[ "def", "_src_input_callback", "(", "cb_data", ",", "data", ")", ":", "cb_data", "=", "ffi", ".", "from_handle", "(", "cb_data", ")", "ret", "=", "cb_data", "[", "'callback'", "]", "(", ")", "if", "ret", "is", "None", ":", "cb_data", "[", "'last_input'", ...
Internal callback function to be used with the callback API. Pulls the Python callback function from the handle contained in `cb_data` and calls it to fetch frames. Frames are converted to the format required by the API (float, interleaved channels). A reference to these data is kept internally. R...
[ "Internal", "callback", "function", "to", "be", "used", "with", "the", "callback", "API", "." ]
train
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L184-L214
tuxu/python-samplerate
samplerate/lowlevel.py
src_callback_new
def src_callback_new(callback, converter_type, channels): """Initialisation for the callback based API. Parameters ---------- callback : function Called whenever new frames are to be read. Must return a NumPy array of shape (num_frames, channels). converter_type : int Conver...
python
def src_callback_new(callback, converter_type, channels): """Initialisation for the callback based API. Parameters ---------- callback : function Called whenever new frames are to be read. Must return a NumPy array of shape (num_frames, channels). converter_type : int Conver...
[ "def", "src_callback_new", "(", "callback", ",", "converter_type", ",", "channels", ")", ":", "cb_data", "=", "{", "'callback'", ":", "callback", ",", "'channels'", ":", "channels", "}", "handle", "=", "ffi", ".", "new_handle", "(", "cb_data", ")", "error", ...
Initialisation for the callback based API. Parameters ---------- callback : function Called whenever new frames are to be read. Must return a NumPy array of shape (num_frames, channels). converter_type : int Converter to be used. channels : int Number of channels. ...
[ "Initialisation", "for", "the", "callback", "based", "API", "." ]
train
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L217-L247
tuxu/python-samplerate
samplerate/lowlevel.py
src_callback_read
def src_callback_read(state, ratio, frames, data): """Read up to `frames` worth of data using the callback API. Returns ------- frames : int Number of frames read or -1 on error. """ data_ptr = ffi.cast('float*f', ffi.from_buffer(data)) return _lib.src_callback_read(state, ratio, fr...
python
def src_callback_read(state, ratio, frames, data): """Read up to `frames` worth of data using the callback API. Returns ------- frames : int Number of frames read or -1 on error. """ data_ptr = ffi.cast('float*f', ffi.from_buffer(data)) return _lib.src_callback_read(state, ratio, fr...
[ "def", "src_callback_read", "(", "state", ",", "ratio", ",", "frames", ",", "data", ")", ":", "data_ptr", "=", "ffi", ".", "cast", "(", "'float*f'", ",", "ffi", ".", "from_buffer", "(", "data", ")", ")", "return", "_lib", ".", "src_callback_read", "(", ...
Read up to `frames` worth of data using the callback API. Returns ------- frames : int Number of frames read or -1 on error.
[ "Read", "up", "to", "frames", "worth", "of", "data", "using", "the", "callback", "API", "." ]
train
https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L250-L259
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client.from_config
def from_config(cls, config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None, legacy_config_fallback=False, **kwargs): """Client factory method to instantiate a client instance from configuration. Configuration values can b...
python
def from_config(cls, config_file=None, profile=None, client=None, endpoint=None, token=None, solver=None, proxy=None, legacy_config_fallback=False, **kwargs): """Client factory method to instantiate a client instance from configuration. Configuration values can b...
[ "def", "from_config", "(", "cls", ",", "config_file", "=", "None", ",", "profile", "=", "None", ",", "client", "=", "None", ",", "endpoint", "=", "None", ",", "token", "=", "None", ",", "solver", "=", "None", ",", "proxy", "=", "None", ",", "legacy_c...
Client factory method to instantiate a client instance from configuration. Configuration values can be specified in multiple ways, ranked in the following order (with 1 the highest ranked): 1. Values specified as keyword arguments in :func:`from_config()` 2. Values specified as environ...
[ "Client", "factory", "method", "to", "instantiate", "a", "client", "instance", "from", "configuration", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L168-L318
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client.close
def close(self): """Perform a clean shutdown. Waits for all the currently scheduled work to finish, kills the workers, and closes the connection pool. .. note:: Ensure your code does not submit new work while the connection is closing. Where possible, it is recommended you use...
python
def close(self): """Perform a clean shutdown. Waits for all the currently scheduled work to finish, kills the workers, and closes the connection pool. .. note:: Ensure your code does not submit new work while the connection is closing. Where possible, it is recommended you use...
[ "def", "close", "(", "self", ")", ":", "# Finish all the work that requires the connection", "_LOGGER", ".", "debug", "(", "\"Joining submission queue\"", ")", "self", ".", "_submission_queue", ".", "join", "(", ")", "_LOGGER", ".", "debug", "(", "\"Joining cancel que...
Perform a clean shutdown. Waits for all the currently scheduled work to finish, kills the workers, and closes the connection pool. .. note:: Ensure your code does not submit new work while the connection is closing. Where possible, it is recommended you use a context manager (a :code:...
[ "Perform", "a", "clean", "shutdown", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L427-L476
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client.get_solvers
def get_solvers(self, refresh=False, order_by='avg_load', **filters): """Return a filtered list of solvers handled by this client. Args: refresh (bool, default=False): Force refresh of cached list of solvers/properties. order_by (callable/str/None, default='avg_...
python
def get_solvers(self, refresh=False, order_by='avg_load', **filters): """Return a filtered list of solvers handled by this client. Args: refresh (bool, default=False): Force refresh of cached list of solvers/properties. order_by (callable/str/None, default='avg_...
[ "def", "get_solvers", "(", "self", ",", "refresh", "=", "False", ",", "order_by", "=", "'avg_load'", ",", "*", "*", "filters", ")", ":", "def", "covers_op", "(", "prop", ",", "val", ")", ":", "\"\"\"Does LHS `prop` (range) fully cover RHS `val` (range or item)?\"\...
Return a filtered list of solvers handled by this client. Args: refresh (bool, default=False): Force refresh of cached list of solvers/properties. order_by (callable/str/None, default='avg_load'): Solver sorting key function (or :class:`Solver` attribute...
[ "Return", "a", "filtered", "list", "of", "solvers", "handled", "by", "this", "client", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L553-L885
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client.solvers
def solvers(self, refresh=False, **filters): """Deprecated in favor of :meth:`.get_solvers`.""" warnings.warn("'solvers' is deprecated in favor of 'get_solvers'.", DeprecationWarning) return self.get_solvers(refresh=refresh, **filters)
python
def solvers(self, refresh=False, **filters): """Deprecated in favor of :meth:`.get_solvers`.""" warnings.warn("'solvers' is deprecated in favor of 'get_solvers'.", DeprecationWarning) return self.get_solvers(refresh=refresh, **filters)
[ "def", "solvers", "(", "self", ",", "refresh", "=", "False", ",", "*", "*", "filters", ")", ":", "warnings", ".", "warn", "(", "\"'solvers' is deprecated in favor of 'get_solvers'.\"", ",", "DeprecationWarning", ")", "return", "self", ".", "get_solvers", "(", "r...
Deprecated in favor of :meth:`.get_solvers`.
[ "Deprecated", "in", "favor", "of", ":", "meth", ":", ".", "get_solvers", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L887-L890
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client.get_solver
def get_solver(self, name=None, refresh=False, **filters): """Load the configuration for a single solver. Makes a blocking web call to `{endpoint}/solvers/remote/{solver_name}/`, where `{endpoint}` is a URL configured for the client, and returns a :class:`.Solver` instance that can be u...
python
def get_solver(self, name=None, refresh=False, **filters): """Load the configuration for a single solver. Makes a blocking web call to `{endpoint}/solvers/remote/{solver_name}/`, where `{endpoint}` is a URL configured for the client, and returns a :class:`.Solver` instance that can be u...
[ "def", "get_solver", "(", "self", ",", "name", "=", "None", ",", "refresh", "=", "False", ",", "*", "*", "filters", ")", ":", "_LOGGER", ".", "debug", "(", "\"Requested a solver that best matches feature filters=%r\"", ",", "filters", ")", "# backward compatibilit...
Load the configuration for a single solver. Makes a blocking web call to `{endpoint}/solvers/remote/{solver_name}/`, where `{endpoint}` is a URL configured for the client, and returns a :class:`.Solver` instance that can be used to submit sampling problems to the D-Wave API and retrieve results...
[ "Load", "the", "configuration", "for", "a", "single", "solver", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L892-L955
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client._submit
def _submit(self, body, future): """Enqueue a problem for submission to the server. This method is thread safe. """ self._submission_queue.put(self._submit.Message(body, future))
python
def _submit(self, body, future): """Enqueue a problem for submission to the server. This method is thread safe. """ self._submission_queue.put(self._submit.Message(body, future))
[ "def", "_submit", "(", "self", ",", "body", ",", "future", ")", ":", "self", ".", "_submission_queue", ".", "put", "(", "self", ".", "_submit", ".", "Message", "(", "body", ",", "future", ")", ")" ]
Enqueue a problem for submission to the server. This method is thread safe.
[ "Enqueue", "a", "problem", "for", "submission", "to", "the", "server", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L957-L962
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client._do_submit_problems
def _do_submit_problems(self): """Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread. """ try: while True: # Pull as many problems as we can, block on the first one, #...
python
def _do_submit_problems(self): """Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread. """ try: while True: # Pull as many problems as we can, block on the first one, #...
[ "def", "_do_submit_problems", "(", "self", ")", ":", "try", ":", "while", "True", ":", "# Pull as many problems as we can, block on the first one,", "# but once we have one problem, switch to non-blocking then", "# submit without blocking again.", "# `None` task is used to signal thread ...
Pull problems from the submission queue and submit them. Note: This method is always run inside of a daemon thread.
[ "Pull", "problems", "from", "the", "submission", "queue", "and", "submit", "them", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L965-L1025
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client._handle_problem_status
def _handle_problem_status(self, message, future): """Handle the results of a problem submission or results request. This method checks the status of the problem and puts it in the correct queue. Args: message (dict): Update message from the SAPI server wrt. this problem. ...
python
def _handle_problem_status(self, message, future): """Handle the results of a problem submission or results request. This method checks the status of the problem and puts it in the correct queue. Args: message (dict): Update message from the SAPI server wrt. this problem. ...
[ "def", "_handle_problem_status", "(", "self", ",", "message", ",", "future", ")", ":", "try", ":", "_LOGGER", ".", "trace", "(", "\"Handling response: %r\"", ",", "message", ")", "_LOGGER", ".", "debug", "(", "\"Handling response for %s with status %s\"", ",", "me...
Handle the results of a problem submission or results request. This method checks the status of the problem and puts it in the correct queue. Args: message (dict): Update message from the SAPI server wrt. this problem. future `Future`: future corresponding to the problem ...
[ "Handle", "the", "results", "of", "a", "problem", "submission", "or", "results", "request", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1027-L1109
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client._do_cancel_problems
def _do_cancel_problems(self): """Pull ids from the cancel queue and submit them. Note: This method is always run inside of a daemon thread. """ try: while True: # Pull as many problems as we can, block when none are available. # ...
python
def _do_cancel_problems(self): """Pull ids from the cancel queue and submit them. Note: This method is always run inside of a daemon thread. """ try: while True: # Pull as many problems as we can, block when none are available. # ...
[ "def", "_do_cancel_problems", "(", "self", ")", ":", "try", ":", "while", "True", ":", "# Pull as many problems as we can, block when none are available.", "# `None` task is used to signal thread termination", "item", "=", "self", ".", "_cancel_queue", ".", "get", "(", ")",...
Pull ids from the cancel queue and submit them. Note: This method is always run inside of a daemon thread.
[ "Pull", "ids", "from", "the", "cancel", "queue", "and", "submit", "them", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1118-L1162
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client._poll
def _poll(self, future): """Enqueue a problem to poll the server for status.""" if future._poll_backoff is None: # on first poll, start with minimal back-off future._poll_backoff = self._POLL_BACKOFF_MIN # if we have ETA of results, schedule the first poll for then ...
python
def _poll(self, future): """Enqueue a problem to poll the server for status.""" if future._poll_backoff is None: # on first poll, start with minimal back-off future._poll_backoff = self._POLL_BACKOFF_MIN # if we have ETA of results, schedule the first poll for then ...
[ "def", "_poll", "(", "self", ",", "future", ")", ":", "if", "future", ".", "_poll_backoff", "is", "None", ":", "# on first poll, start with minimal back-off", "future", ".", "_poll_backoff", "=", "self", ".", "_POLL_BACKOFF_MIN", "# if we have ETA of results, schedule t...
Enqueue a problem to poll the server for status.
[ "Enqueue", "a", "problem", "to", "poll", "the", "server", "for", "status", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1174-L1212
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client._do_poll_problems
def _do_poll_problems(self): """Poll the server for the status of a set of problems. Note: This method is always run inside of a daemon thread. """ try: # grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME) frame_futures = {} def...
python
def _do_poll_problems(self): """Poll the server for the status of a set of problems. Note: This method is always run inside of a daemon thread. """ try: # grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME) frame_futures = {} def...
[ "def", "_do_poll_problems", "(", "self", ")", ":", "try", ":", "# grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME)", "frame_futures", "=", "{", "}", "def", "task_done", "(", ")", ":", "self", ".", "_poll_queue", ".", "task_done", "(", ")", "def", "add"...
Poll the server for the status of a set of problems. Note: This method is always run inside of a daemon thread.
[ "Poll", "the", "server", "for", "the", "status", "of", "a", "set", "of", "problems", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1214-L1313
dwavesystems/dwave-cloud-client
dwave/cloud/client.py
Client._do_load_results
def _do_load_results(self): """Submit a query asking for the results for a particular problem. To request the results of a problem: ``GET /problems/{problem_id}/`` Note: This method is always run inside of a daemon thread. """ try: while True: ...
python
def _do_load_results(self): """Submit a query asking for the results for a particular problem. To request the results of a problem: ``GET /problems/{problem_id}/`` Note: This method is always run inside of a daemon thread. """ try: while True: ...
[ "def", "_do_load_results", "(", "self", ")", ":", "try", ":", "while", "True", ":", "# Select a problem", "future", "=", "self", ".", "_load_queue", ".", "get", "(", ")", "# `None` task signifies thread termination", "if", "future", "is", "None", ":", "break", ...
Submit a query asking for the results for a particular problem. To request the results of a problem: ``GET /problems/{problem_id}/`` Note: This method is always run inside of a daemon thread.
[ "Submit", "a", "query", "asking", "for", "the", "results", "for", "a", "particular", "problem", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/client.py#L1325-L1370
dwavesystems/dwave-cloud-client
dwave/cloud/coders.py
encode_bqm_as_qp
def encode_bqm_as_qp(solver, linear, quadratic): """Encode the binary quadratic problem for submission to a given solver, using the `qp` format for data. Args: solver (:class:`dwave.cloud.solver.Solver`): The solver used. linear (dict[variable, bias]/list[variable, bias]): ...
python
def encode_bqm_as_qp(solver, linear, quadratic): """Encode the binary quadratic problem for submission to a given solver, using the `qp` format for data. Args: solver (:class:`dwave.cloud.solver.Solver`): The solver used. linear (dict[variable, bias]/list[variable, bias]): ...
[ "def", "encode_bqm_as_qp", "(", "solver", ",", "linear", ",", "quadratic", ")", ":", "active", "=", "active_qubits", "(", "linear", ",", "quadratic", ")", "# Encode linear terms. The coefficients of the linear terms of the objective", "# are encoded as an array of little endian...
Encode the binary quadratic problem for submission to a given solver, using the `qp` format for data. Args: solver (:class:`dwave.cloud.solver.Solver`): The solver used. linear (dict[variable, bias]/list[variable, bias]): Linear terms of the model. quadratic (d...
[ "Encode", "the", "binary", "quadratic", "problem", "for", "submission", "to", "a", "given", "solver", "using", "the", "qp", "format", "for", "data", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L26-L70
dwavesystems/dwave-cloud-client
dwave/cloud/coders.py
decode_qp
def decode_qp(msg): """Decode SAPI response that uses `qp` format, without numpy. The 'qp' format is the current encoding used for problems and samples. In this encoding the reply is generally json, but the samples, energy, and histogram data (the occurrence count of each solution), are all base64 ...
python
def decode_qp(msg): """Decode SAPI response that uses `qp` format, without numpy. The 'qp' format is the current encoding used for problems and samples. In this encoding the reply is generally json, but the samples, energy, and histogram data (the occurrence count of each solution), are all base64 ...
[ "def", "decode_qp", "(", "msg", ")", ":", "# Decode the simple buffers", "result", "=", "msg", "[", "'answer'", "]", "result", "[", "'active_variables'", "]", "=", "_decode_ints", "(", "result", "[", "'active_variables'", "]", ")", "active_variables", "=", "resu...
Decode SAPI response that uses `qp` format, without numpy. The 'qp' format is the current encoding used for problems and samples. In this encoding the reply is generally json, but the samples, energy, and histogram data (the occurrence count of each solution), are all base64 encoded arrays.
[ "Decode", "SAPI", "response", "that", "uses", "qp", "format", "without", "numpy", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L73-L125
dwavesystems/dwave-cloud-client
dwave/cloud/coders.py
_decode_byte
def _decode_byte(byte): """Helper for decode_qp, turns a single byte into a list of bits. Args: byte: byte to be decoded Returns: list of bits corresponding to byte """ bits = [] for _ in range(8): bits.append(byte & 1) byte >>= 1 return bits
python
def _decode_byte(byte): """Helper for decode_qp, turns a single byte into a list of bits. Args: byte: byte to be decoded Returns: list of bits corresponding to byte """ bits = [] for _ in range(8): bits.append(byte & 1) byte >>= 1 return bits
[ "def", "_decode_byte", "(", "byte", ")", ":", "bits", "=", "[", "]", "for", "_", "in", "range", "(", "8", ")", ":", "bits", ".", "append", "(", "byte", "&", "1", ")", "byte", ">>=", "1", "return", "bits" ]
Helper for decode_qp, turns a single byte into a list of bits. Args: byte: byte to be decoded Returns: list of bits corresponding to byte
[ "Helper", "for", "decode_qp", "turns", "a", "single", "byte", "into", "a", "list", "of", "bits", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L128-L141
dwavesystems/dwave-cloud-client
dwave/cloud/coders.py
_decode_ints
def _decode_ints(message): """Helper for decode_qp, decodes an int array. The int array is stored as little endian 32 bit integers. The array has then been base64 encoded. Since we are decoding we do these steps in reverse. """ binary = base64.b64decode(message) return struct.unpack('<' + (...
python
def _decode_ints(message): """Helper for decode_qp, decodes an int array. The int array is stored as little endian 32 bit integers. The array has then been base64 encoded. Since we are decoding we do these steps in reverse. """ binary = base64.b64decode(message) return struct.unpack('<' + (...
[ "def", "_decode_ints", "(", "message", ")", ":", "binary", "=", "base64", ".", "b64decode", "(", "message", ")", "return", "struct", ".", "unpack", "(", "'<'", "+", "(", "'i'", "*", "(", "len", "(", "binary", ")", "//", "4", ")", ")", ",", "binary"...
Helper for decode_qp, decodes an int array. The int array is stored as little endian 32 bit integers. The array has then been base64 encoded. Since we are decoding we do these steps in reverse.
[ "Helper", "for", "decode_qp", "decodes", "an", "int", "array", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L144-L152
dwavesystems/dwave-cloud-client
dwave/cloud/coders.py
_decode_doubles
def _decode_doubles(message): """Helper for decode_qp, decodes a double array. The double array is stored as little endian 64 bit doubles. The array has then been base64 encoded. Since we are decoding we do these steps in reverse. Args: message: the double array Returns: decod...
python
def _decode_doubles(message): """Helper for decode_qp, decodes a double array. The double array is stored as little endian 64 bit doubles. The array has then been base64 encoded. Since we are decoding we do these steps in reverse. Args: message: the double array Returns: decod...
[ "def", "_decode_doubles", "(", "message", ")", ":", "binary", "=", "base64", ".", "b64decode", "(", "message", ")", "return", "struct", ".", "unpack", "(", "'<'", "+", "(", "'d'", "*", "(", "len", "(", "binary", ")", "//", "8", ")", ")", ",", "bina...
Helper for decode_qp, decodes a double array. The double array is stored as little endian 64 bit doubles. The array has then been base64 encoded. Since we are decoding we do these steps in reverse. Args: message: the double array Returns: decoded double array
[ "Helper", "for", "decode_qp", "decodes", "a", "double", "array", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L155-L169
dwavesystems/dwave-cloud-client
dwave/cloud/coders.py
decode_qp_numpy
def decode_qp_numpy(msg, return_matrix=True): """Decode SAPI response, results in a `qp` format, explicitly using numpy. If numpy is not installed, the method will fail. To use numpy for decoding, but return the results a lists (instead of numpy matrices), set `return_matrix=False`. """ import ...
python
def decode_qp_numpy(msg, return_matrix=True): """Decode SAPI response, results in a `qp` format, explicitly using numpy. If numpy is not installed, the method will fail. To use numpy for decoding, but return the results a lists (instead of numpy matrices), set `return_matrix=False`. """ import ...
[ "def", "decode_qp_numpy", "(", "msg", ",", "return_matrix", "=", "True", ")", ":", "import", "numpy", "as", "np", "result", "=", "msg", "[", "'answer'", "]", "# Build some little endian type encodings", "double_type", "=", "np", ".", "dtype", "(", "np", ".", ...
Decode SAPI response, results in a `qp` format, explicitly using numpy. If numpy is not installed, the method will fail. To use numpy for decoding, but return the results a lists (instead of numpy matrices), set `return_matrix=False`.
[ "Decode", "SAPI", "response", "results", "in", "a", "qp", "format", "explicitly", "using", "numpy", ".", "If", "numpy", "is", "not", "installed", "the", "method", "will", "fail", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/coders.py#L172-L240
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
evaluate_ising
def evaluate_ising(linear, quad, state): """Calculate the energy of a state given the Hamiltonian. Args: linear: Linear Hamiltonian terms. quad: Quadratic Hamiltonian terms. state: Vector of spins describing the system state. Returns: Energy of the state evaluated by the gi...
python
def evaluate_ising(linear, quad, state): """Calculate the energy of a state given the Hamiltonian. Args: linear: Linear Hamiltonian terms. quad: Quadratic Hamiltonian terms. state: Vector of spins describing the system state. Returns: Energy of the state evaluated by the gi...
[ "def", "evaluate_ising", "(", "linear", ",", "quad", ",", "state", ")", ":", "# If we were given a numpy array cast to list", "if", "_numpy", "and", "isinstance", "(", "state", ",", "np", ".", "ndarray", ")", ":", "return", "evaluate_ising", "(", "linear", ",", ...
Calculate the energy of a state given the Hamiltonian. Args: linear: Linear Hamiltonian terms. quad: Quadratic Hamiltonian terms. state: Vector of spins describing the system state. Returns: Energy of the state evaluated by the given energy function.
[ "Calculate", "the", "energy", "of", "a", "state", "given", "the", "Hamiltonian", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L49-L71
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
active_qubits
def active_qubits(linear, quadratic): """Calculate a set of all active qubits. Qubit is "active" if it has bias or coupling attached. Args: linear (dict[variable, bias]/list[variable, bias]): Linear terms of the model. quadratic (dict[(variable, variable), bias]): Q...
python
def active_qubits(linear, quadratic): """Calculate a set of all active qubits. Qubit is "active" if it has bias or coupling attached. Args: linear (dict[variable, bias]/list[variable, bias]): Linear terms of the model. quadratic (dict[(variable, variable), bias]): Q...
[ "def", "active_qubits", "(", "linear", ",", "quadratic", ")", ":", "active", "=", "{", "idx", "for", "idx", ",", "bias", "in", "uniform_iterator", "(", "linear", ")", "}", "for", "edge", ",", "_", "in", "six", ".", "iteritems", "(", "quadratic", ")", ...
Calculate a set of all active qubits. Qubit is "active" if it has bias or coupling attached. Args: linear (dict[variable, bias]/list[variable, bias]): Linear terms of the model. quadratic (dict[(variable, variable), bias]): Quadratic terms of the model. Returns: ...
[ "Calculate", "a", "set", "of", "all", "active", "qubits", ".", "Qubit", "is", "active", "if", "it", "has", "bias", "or", "coupling", "attached", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L74-L93
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
generate_random_ising_problem
def generate_random_ising_problem(solver, h_range=None, j_range=None): """Generates an Ising problem formulation valid for a particular solver, using all qubits and all couplings and linear/quadratic biases sampled uniformly from `h_range`/`j_range`. """ if h_range is None: h_range = solver...
python
def generate_random_ising_problem(solver, h_range=None, j_range=None): """Generates an Ising problem formulation valid for a particular solver, using all qubits and all couplings and linear/quadratic biases sampled uniformly from `h_range`/`j_range`. """ if h_range is None: h_range = solver...
[ "def", "generate_random_ising_problem", "(", "solver", ",", "h_range", "=", "None", ",", "j_range", "=", "None", ")", ":", "if", "h_range", "is", "None", ":", "h_range", "=", "solver", ".", "properties", ".", "get", "(", "'h_range'", ",", "[", "-", "1", ...
Generates an Ising problem formulation valid for a particular solver, using all qubits and all couplings and linear/quadratic biases sampled uniformly from `h_range`/`j_range`.
[ "Generates", "an", "Ising", "problem", "formulation", "valid", "for", "a", "particular", "solver", "using", "all", "qubits", "and", "all", "couplings", "and", "linear", "/", "quadratic", "biases", "sampled", "uniformly", "from", "h_range", "/", "j_range", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L96-L110
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
uniform_iterator
def uniform_iterator(sequence): """Uniform (key, value) iteration on a `dict`, or (idx, value) on a `list`.""" if isinstance(sequence, abc.Mapping): return six.iteritems(sequence) else: return enumerate(sequence)
python
def uniform_iterator(sequence): """Uniform (key, value) iteration on a `dict`, or (idx, value) on a `list`.""" if isinstance(sequence, abc.Mapping): return six.iteritems(sequence) else: return enumerate(sequence)
[ "def", "uniform_iterator", "(", "sequence", ")", ":", "if", "isinstance", "(", "sequence", ",", "abc", ".", "Mapping", ")", ":", "return", "six", ".", "iteritems", "(", "sequence", ")", "else", ":", "return", "enumerate", "(", "sequence", ")" ]
Uniform (key, value) iteration on a `dict`, or (idx, value) on a `list`.
[ "Uniform", "(", "key", "value", ")", "iteration", "on", "a", "dict", "or", "(", "idx", "value", ")", "on", "a", "list", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L113-L120
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
uniform_get
def uniform_get(sequence, index, default=None): """Uniform `dict`/`list` item getter, where `index` is interpreted as a key for maps and as numeric index for lists.""" if isinstance(sequence, abc.Mapping): return sequence.get(index, default) else: return sequence[index] if index < len(s...
python
def uniform_get(sequence, index, default=None): """Uniform `dict`/`list` item getter, where `index` is interpreted as a key for maps and as numeric index for lists.""" if isinstance(sequence, abc.Mapping): return sequence.get(index, default) else: return sequence[index] if index < len(s...
[ "def", "uniform_get", "(", "sequence", ",", "index", ",", "default", "=", "None", ")", ":", "if", "isinstance", "(", "sequence", ",", "abc", ".", "Mapping", ")", ":", "return", "sequence", ".", "get", "(", "index", ",", "default", ")", "else", ":", "...
Uniform `dict`/`list` item getter, where `index` is interpreted as a key for maps and as numeric index for lists.
[ "Uniform", "dict", "/", "list", "item", "getter", "where", "index", "is", "interpreted", "as", "a", "key", "for", "maps", "and", "as", "numeric", "index", "for", "lists", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L123-L130
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
strip_head
def strip_head(sequence, values): """Strips elements of `values` from the beginning of `sequence`.""" values = set(values) return list(itertools.dropwhile(lambda x: x in values, sequence))
python
def strip_head(sequence, values): """Strips elements of `values` from the beginning of `sequence`.""" values = set(values) return list(itertools.dropwhile(lambda x: x in values, sequence))
[ "def", "strip_head", "(", "sequence", ",", "values", ")", ":", "values", "=", "set", "(", "values", ")", "return", "list", "(", "itertools", ".", "dropwhile", "(", "lambda", "x", ":", "x", "in", "values", ",", "sequence", ")", ")" ]
Strips elements of `values` from the beginning of `sequence`.
[ "Strips", "elements", "of", "values", "from", "the", "beginning", "of", "sequence", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L133-L136
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
strip_tail
def strip_tail(sequence, values): """Strip `values` from the end of `sequence`.""" return list(reversed(list(strip_head(reversed(sequence), values))))
python
def strip_tail(sequence, values): """Strip `values` from the end of `sequence`.""" return list(reversed(list(strip_head(reversed(sequence), values))))
[ "def", "strip_tail", "(", "sequence", ",", "values", ")", ":", "return", "list", "(", "reversed", "(", "list", "(", "strip_head", "(", "reversed", "(", "sequence", ")", ",", "values", ")", ")", ")", ")" ]
Strip `values` from the end of `sequence`.
[ "Strip", "values", "from", "the", "end", "of", "sequence", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L139-L141
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
click_info_switch
def click_info_switch(f): """Decorator to create eager Click info switch option, as described in: http://click.pocoo.org/6/options/#callbacks-and-eager-options. Takes a no-argument function and abstracts the boilerplate required by Click (value checking, exit on done). Example: @click.opt...
python
def click_info_switch(f): """Decorator to create eager Click info switch option, as described in: http://click.pocoo.org/6/options/#callbacks-and-eager-options. Takes a no-argument function and abstracts the boilerplate required by Click (value checking, exit on done). Example: @click.opt...
[ "def", "click_info_switch", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "not", "value", "or", "ctx", ".", "resilient_parsing", ":", "return", "f", "(", ")", "ctx", ".", ...
Decorator to create eager Click info switch option, as described in: http://click.pocoo.org/6/options/#callbacks-and-eager-options. Takes a no-argument function and abstracts the boilerplate required by Click (value checking, exit on done). Example: @click.option('--my-option', is_flag=True, ...
[ "Decorator", "to", "create", "eager", "Click", "info", "switch", "option", "as", "described", "in", ":", "http", ":", "//", "click", ".", "pocoo", ".", "org", "/", "6", "/", "options", "/", "#callbacks", "-", "and", "-", "eager", "-", "options", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L165-L190
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
datetime_to_timestamp
def datetime_to_timestamp(dt): """Convert timezone-aware `datetime` to POSIX timestamp and return seconds since UNIX epoch. Note: similar to `datetime.timestamp()` in Python 3.3+. """ epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC) return (dt - epoch).total_seconds()
python
def datetime_to_timestamp(dt): """Convert timezone-aware `datetime` to POSIX timestamp and return seconds since UNIX epoch. Note: similar to `datetime.timestamp()` in Python 3.3+. """ epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC) return (dt - epoch).total_seconds()
[ "def", "datetime_to_timestamp", "(", "dt", ")", ":", "epoch", "=", "datetime", ".", "utcfromtimestamp", "(", "0", ")", ".", "replace", "(", "tzinfo", "=", "UTC", ")", "return", "(", "dt", "-", "epoch", ")", ".", "total_seconds", "(", ")" ]
Convert timezone-aware `datetime` to POSIX timestamp and return seconds since UNIX epoch. Note: similar to `datetime.timestamp()` in Python 3.3+.
[ "Convert", "timezone", "-", "aware", "datetime", "to", "POSIX", "timestamp", "and", "return", "seconds", "since", "UNIX", "epoch", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L193-L201
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
user_agent
def user_agent(name, version): """Return User-Agent ~ "name/version language/version interpreter/version os/version".""" def _interpreter(): name = platform.python_implementation() version = platform.python_version() bitness = platform.architecture()[0] if name == 'PyPy': ...
python
def user_agent(name, version): """Return User-Agent ~ "name/version language/version interpreter/version os/version".""" def _interpreter(): name = platform.python_implementation() version = platform.python_version() bitness = platform.architecture()[0] if name == 'PyPy': ...
[ "def", "user_agent", "(", "name", ",", "version", ")", ":", "def", "_interpreter", "(", ")", ":", "name", "=", "platform", ".", "python_implementation", "(", ")", "version", "=", "platform", ".", "python_version", "(", ")", "bitness", "=", "platform", ".",...
Return User-Agent ~ "name/version language/version interpreter/version os/version".
[ "Return", "User", "-", "Agent", "~", "name", "/", "version", "language", "/", "version", "interpreter", "/", "version", "os", "/", "version", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L252-L275
dwavesystems/dwave-cloud-client
dwave/cloud/utils.py
cached.argshash
def argshash(self, args, kwargs): "Hash mutable arguments' containers with immutable keys and values." a = repr(args) b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items())) return a + b
python
def argshash(self, args, kwargs): "Hash mutable arguments' containers with immutable keys and values." a = repr(args) b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items())) return a + b
[ "def", "argshash", "(", "self", ",", "args", ",", "kwargs", ")", ":", "a", "=", "repr", "(", "args", ")", "b", "=", "repr", "(", "sorted", "(", "(", "repr", "(", "k", ")", ",", "repr", "(", "v", ")", ")", "for", "k", ",", "v", "in", "kwargs...
Hash mutable arguments' containers with immutable keys and values.
[ "Hash", "mutable", "arguments", "containers", "with", "immutable", "keys", "and", "values", "." ]
train
https://github.com/dwavesystems/dwave-cloud-client/blob/df3221a8385dc0c04d7b4d84f740bf3ad6706230/dwave/cloud/utils.py#L316-L320
bitlabstudio/django-user-media
user_media/views.py
UserMediaImageViewMixin.get_context_data
def get_context_data(self, **kwargs): """ Adds `next` to the context. This makes sure that the `next` parameter doesn't get lost if the form was submitted invalid. """ ctx = super(UserMediaImageViewMixin, self).get_context_data(**kwargs) ctx.update({ ...
python
def get_context_data(self, **kwargs): """ Adds `next` to the context. This makes sure that the `next` parameter doesn't get lost if the form was submitted invalid. """ ctx = super(UserMediaImageViewMixin, self).get_context_data(**kwargs) ctx.update({ ...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "super", "(", "UserMediaImageViewMixin", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "ctx", ".", "update", "(", "{", "'action'", ":", "s...
Adds `next` to the context. This makes sure that the `next` parameter doesn't get lost if the form was submitted invalid.
[ "Adds", "next", "to", "the", "context", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L34-L47
bitlabstudio/django-user-media
user_media/views.py
UserMediaImageViewMixin.get_success_url
def get_success_url(self): """ Returns the success URL. This is either the given `next` URL parameter or the content object's `get_absolute_url` method's return value. """ if self.next: return self.next if self.object and self.object.content_object: ...
python
def get_success_url(self): """ Returns the success URL. This is either the given `next` URL parameter or the content object's `get_absolute_url` method's return value. """ if self.next: return self.next if self.object and self.object.content_object: ...
[ "def", "get_success_url", "(", "self", ")", ":", "if", "self", ".", "next", ":", "return", "self", ".", "next", "if", "self", ".", "object", "and", "self", ".", "object", ".", "content_object", ":", "return", "self", ".", "object", ".", "content_object",...
Returns the success URL. This is either the given `next` URL parameter or the content object's `get_absolute_url` method's return value.
[ "Returns", "the", "success", "URL", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L49-L63
bitlabstudio/django-user-media
user_media/views.py
CreateImageView.dispatch
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class and performs security checks.""" self._add_next_and_user(request) self.content_object = None self.content_type = None self.object_id = kwargs.get('object_id', None) if kwargs.get('content_t...
python
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class and performs security checks.""" self._add_next_and_user(request) self.content_object = None self.content_type = None self.object_id = kwargs.get('object_id', None) if kwargs.get('content_t...
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_add_next_and_user", "(", "request", ")", "self", ".", "content_object", "=", "None", "self", ".", "content_type", "=", "None", "self", "...
Adds useful objects to the class and performs security checks.
[ "Adds", "useful", "objects", "to", "the", "class", "and", "performs", "security", "checks", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L72-L104
bitlabstudio/django-user-media
user_media/views.py
DeleteImageView.dispatch
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class.""" self._add_next_and_user(request) return super(DeleteImageView, self).dispatch(request, *args, **kwargs)
python
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class.""" self._add_next_and_user(request) return super(DeleteImageView, self).dispatch(request, *args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_add_next_and_user", "(", "request", ")", "return", "super", "(", "DeleteImageView", ",", "self", ")", ".", "dispatch", "(", "request", "...
Adds useful objects to the class.
[ "Adds", "useful", "objects", "to", "the", "class", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L131-L134
bitlabstudio/django-user-media
user_media/views.py
DeleteImageView.get_queryset
def get_queryset(self): """ Making sure that a user can only delete his own images. Even when he forges the request URL. """ queryset = super(DeleteImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
python
def get_queryset(self): """ Making sure that a user can only delete his own images. Even when he forges the request URL. """ queryset = super(DeleteImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
[ "def", "get_queryset", "(", "self", ")", ":", "queryset", "=", "super", "(", "DeleteImageView", ",", "self", ")", ".", "get_queryset", "(", ")", "queryset", "=", "queryset", ".", "filter", "(", "user", "=", "self", ".", "user", ")", "return", "queryset" ...
Making sure that a user can only delete his own images. Even when he forges the request URL.
[ "Making", "sure", "that", "a", "user", "can", "only", "delete", "his", "own", "images", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L143-L152
bitlabstudio/django-user-media
user_media/views.py
UpdateImageView.dispatch
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class.""" self._add_next_and_user(request) return super(UpdateImageView, self).dispatch(request, *args, **kwargs)
python
def dispatch(self, request, *args, **kwargs): """Adds useful objects to the class.""" self._add_next_and_user(request) return super(UpdateImageView, self).dispatch(request, *args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_add_next_and_user", "(", "request", ")", "return", "super", "(", "UpdateImageView", ",", "self", ")", ".", "dispatch", "(", "request", "...
Adds useful objects to the class.
[ "Adds", "useful", "objects", "to", "the", "class", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L163-L166
bitlabstudio/django-user-media
user_media/views.py
UpdateImageView.get_queryset
def get_queryset(self): """ Making sure that a user can only edit his own images. Even when he forges the request URL. """ queryset = super(UpdateImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
python
def get_queryset(self): """ Making sure that a user can only edit his own images. Even when he forges the request URL. """ queryset = super(UpdateImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
[ "def", "get_queryset", "(", "self", ")", ":", "queryset", "=", "super", "(", "UpdateImageView", ",", "self", ")", ".", "get_queryset", "(", ")", "queryset", "=", "queryset", ".", "filter", "(", "user", "=", "self", ".", "user", ")", "return", "queryset" ...
Making sure that a user can only edit his own images. Even when he forges the request URL.
[ "Making", "sure", "that", "a", "user", "can", "only", "edit", "his", "own", "images", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/views.py#L186-L195
bitlabstudio/django-user-media
user_media/forms.py
UserMediaImageFormMixin._delete_images
def _delete_images(self, instance): """Deletes all user media images of the given instance.""" UserMediaImage.objects.filter( content_type=ContentType.objects.get_for_model(instance), object_id=instance.pk, user=instance.user, ).delete()
python
def _delete_images(self, instance): """Deletes all user media images of the given instance.""" UserMediaImage.objects.filter( content_type=ContentType.objects.get_for_model(instance), object_id=instance.pk, user=instance.user, ).delete()
[ "def", "_delete_images", "(", "self", ",", "instance", ")", ":", "UserMediaImage", ".", "objects", ".", "filter", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "instance", ")", ",", "object_id", "=", "instance", ".", "pk...
Deletes all user media images of the given instance.
[ "Deletes", "all", "user", "media", "images", "of", "the", "given", "instance", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/forms.py#L51-L57
bitlabstudio/django-user-media
user_media/forms.py
UserMediaImageForm.clean_image
def clean_image(self): """ It seems like in Django 1.5 something has changed. When Django tries to validate the form, it checks if the generated filename fit into the max_length. But at this point, self.instance.user is not yet set so our filename generation function cannot crea...
python
def clean_image(self): """ It seems like in Django 1.5 something has changed. When Django tries to validate the form, it checks if the generated filename fit into the max_length. But at this point, self.instance.user is not yet set so our filename generation function cannot crea...
[ "def", "clean_image", "(", "self", ")", ":", "self", ".", "instance", ".", "user", "=", "self", ".", "user", "data", "=", "self", ".", "cleaned_data", ".", "get", "(", "'image'", ")", "return", "data" ]
It seems like in Django 1.5 something has changed. When Django tries to validate the form, it checks if the generated filename fit into the max_length. But at this point, self.instance.user is not yet set so our filename generation function cannot create the new file path because it nee...
[ "It", "seems", "like", "in", "Django", "1", ".", "5", "something", "has", "changed", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/forms.py#L90-L103
bitlabstudio/django-user-media
user_media/models.py
get_image_file_path
def get_image_file_path(instance, filename): """Returns a unique filename for images.""" ext = filename.split('.')[-1] filename = '%s.%s' % (uuid.uuid4(), ext) return os.path.join( 'user_media', str(instance.user.pk), 'images', filename)
python
def get_image_file_path(instance, filename): """Returns a unique filename for images.""" ext = filename.split('.')[-1] filename = '%s.%s' % (uuid.uuid4(), ext) return os.path.join( 'user_media', str(instance.user.pk), 'images', filename)
[ "def", "get_image_file_path", "(", "instance", ",", "filename", ")", ":", "ext", "=", "filename", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "filename", "=", "'%s.%s'", "%", "(", "uuid", ".", "uuid4", "(", ")", ",", "ext", ")", "return", "o...
Returns a unique filename for images.
[ "Returns", "a", "unique", "filename", "for", "images", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/models.py#L15-L20
bitlabstudio/django-user-media
user_media/models.py
image_post_delete_handler
def image_post_delete_handler(sender, instance, **kwargs): """ Makes sure that a an image is also deleted from the media directory. This should prevent a load of "dead" image files on disc. """ for f in glob.glob('{}/{}*'.format(instance.image.storage.location, ...
python
def image_post_delete_handler(sender, instance, **kwargs): """ Makes sure that a an image is also deleted from the media directory. This should prevent a load of "dead" image files on disc. """ for f in glob.glob('{}/{}*'.format(instance.image.storage.location, ...
[ "def", "image_post_delete_handler", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "for", "f", "in", "glob", ".", "glob", "(", "'{}/{}*'", ".", "format", "(", "instance", ".", "image", ".", "storage", ".", "location", ",", "instance",...
Makes sure that a an image is also deleted from the media directory. This should prevent a load of "dead" image files on disc.
[ "Makes", "sure", "that", "a", "an", "image", "is", "also", "deleted", "from", "the", "media", "directory", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/models.py#L138-L148
bitlabstudio/django-user-media
user_media/models.py
UserMediaImage.box_coordinates
def box_coordinates(self): """Returns a thumbnail's coordinates.""" if ( self.thumb_x is not None and self.thumb_y is not None and self.thumb_x2 is not None and self.thumb_y2 is not None ): return ( int(self.thumb_x), ...
python
def box_coordinates(self): """Returns a thumbnail's coordinates.""" if ( self.thumb_x is not None and self.thumb_y is not None and self.thumb_x2 is not None and self.thumb_y2 is not None ): return ( int(self.thumb_x), ...
[ "def", "box_coordinates", "(", "self", ")", ":", "if", "(", "self", ".", "thumb_x", "is", "not", "None", "and", "self", ".", "thumb_y", "is", "not", "None", "and", "self", ".", "thumb_x2", "is", "not", "None", "and", "self", ".", "thumb_y2", "is", "n...
Returns a thumbnail's coordinates.
[ "Returns", "a", "thumbnail", "s", "coordinates", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/models.py#L106-L120
bitlabstudio/django-user-media
user_media/models.py
UserMediaImage.large_size
def large_size(self, as_string=True): """Returns a thumbnail's large size.""" size = getattr(settings, 'USER_MEDIA_THUMB_SIZE_LARGE', (150, 150)) if as_string: return u'{}x{}'.format(size[0], size[1]) return size
python
def large_size(self, as_string=True): """Returns a thumbnail's large size.""" size = getattr(settings, 'USER_MEDIA_THUMB_SIZE_LARGE', (150, 150)) if as_string: return u'{}x{}'.format(size[0], size[1]) return size
[ "def", "large_size", "(", "self", ",", "as_string", "=", "True", ")", ":", "size", "=", "getattr", "(", "settings", ",", "'USER_MEDIA_THUMB_SIZE_LARGE'", ",", "(", "150", ",", "150", ")", ")", "if", "as_string", ":", "return", "u'{}x{}'", ".", "format", ...
Returns a thumbnail's large size.
[ "Returns", "a", "thumbnail", "s", "large", "size", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/models.py#L122-L127
bitlabstudio/django-user-media
user_media/processors.py
crop_box
def crop_box(im, box=False, **kwargs): """Uses box coordinates to crop an image without resizing it first.""" if box: im = im.crop(box) return im
python
def crop_box(im, box=False, **kwargs): """Uses box coordinates to crop an image without resizing it first.""" if box: im = im.crop(box) return im
[ "def", "crop_box", "(", "im", ",", "box", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "box", ":", "im", "=", "im", ".", "crop", "(", "box", ")", "return", "im" ]
Uses box coordinates to crop an image without resizing it first.
[ "Uses", "box", "coordinates", "to", "crop", "an", "image", "without", "resizing", "it", "first", "." ]
train
https://github.com/bitlabstudio/django-user-media/blob/63905aeb57640f116320ab8d7116e0ec35fde377/user_media/processors.py#L4-L8
wroberts/pygermanet
pygermanet/germanet.py
load_germanet
def load_germanet(host = None, port = None, database_name = 'germanet'): ''' Loads a GermaNet instance connected to the given MongoDB instance. Arguments: - `host`: the hostname of the MongoDB instance - `port`: the port number of the MongoDB instance - `database_name`: the name of the GermaNet...
python
def load_germanet(host = None, port = None, database_name = 'germanet'): ''' Loads a GermaNet instance connected to the given MongoDB instance. Arguments: - `host`: the hostname of the MongoDB instance - `port`: the port number of the MongoDB instance - `database_name`: the name of the GermaNet...
[ "def", "load_germanet", "(", "host", "=", "None", ",", "port", "=", "None", ",", "database_name", "=", "'germanet'", ")", ":", "client", "=", "MongoClient", "(", "host", ",", "port", ")", "germanet_db", "=", "client", "[", "database_name", "]", "return", ...
Loads a GermaNet instance connected to the given MongoDB instance. Arguments: - `host`: the hostname of the MongoDB instance - `port`: the port number of the MongoDB instance - `database_name`: the name of the GermaNet database on the MongoDB instance
[ "Loads", "a", "GermaNet", "instance", "connected", "to", "the", "given", "MongoDB", "instance", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L664-L676
wroberts/pygermanet
pygermanet/germanet.py
GermaNet.cache_size
def cache_size(self, new_value): ''' Set the cache size used to reduce the number of database access operations. ''' if type(new_value) == int and 0 < new_value: if self._lemma_cache is not None: self._lemma_cache = repoze.lru.LRUCache(new_value) ...
python
def cache_size(self, new_value): ''' Set the cache size used to reduce the number of database access operations. ''' if type(new_value) == int and 0 < new_value: if self._lemma_cache is not None: self._lemma_cache = repoze.lru.LRUCache(new_value) ...
[ "def", "cache_size", "(", "self", ",", "new_value", ")", ":", "if", "type", "(", "new_value", ")", "==", "int", "and", "0", "<", "new_value", ":", "if", "self", ".", "_lemma_cache", "is", "not", "None", ":", "self", ".", "_lemma_cache", "=", "repoze", ...
Set the cache size used to reduce the number of database access operations.
[ "Set", "the", "cache", "size", "used", "to", "reduce", "the", "number", "of", "database", "access", "operations", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L75-L83
wroberts/pygermanet
pygermanet/germanet.py
GermaNet.all_lemmas
def all_lemmas(self): ''' A generator over all the lemmas in the GermaNet database. ''' for lemma_dict in self._mongo_db.lexunits.find(): yield Lemma(self, lemma_dict)
python
def all_lemmas(self): ''' A generator over all the lemmas in the GermaNet database. ''' for lemma_dict in self._mongo_db.lexunits.find(): yield Lemma(self, lemma_dict)
[ "def", "all_lemmas", "(", "self", ")", ":", "for", "lemma_dict", "in", "self", ".", "_mongo_db", ".", "lexunits", ".", "find", "(", ")", ":", "yield", "Lemma", "(", "self", ",", "lemma_dict", ")" ]
A generator over all the lemmas in the GermaNet database.
[ "A", "generator", "over", "all", "the", "lemmas", "in", "the", "GermaNet", "database", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L85-L90
wroberts/pygermanet
pygermanet/germanet.py
GermaNet.lemmas
def lemmas(self, lemma, pos = None): ''' Looks up lemmas in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' if pos is not None: if pos not in SHORT_POS_TO_LONG: return None pos = SHORT_POS_TO_LONG[pos] ...
python
def lemmas(self, lemma, pos = None): ''' Looks up lemmas in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' if pos is not None: if pos not in SHORT_POS_TO_LONG: return None pos = SHORT_POS_TO_LONG[pos] ...
[ "def", "lemmas", "(", "self", ",", "lemma", ",", "pos", "=", "None", ")", ":", "if", "pos", "is", "not", "None", ":", "if", "pos", "not", "in", "SHORT_POS_TO_LONG", ":", "return", "None", "pos", "=", "SHORT_POS_TO_LONG", "[", "pos", "]", "lemma_dicts",...
Looks up lemmas in the GermaNet database. Arguments: - `lemma`: - `pos`:
[ "Looks", "up", "lemmas", "in", "the", "GermaNet", "database", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L92-L108
wroberts/pygermanet
pygermanet/germanet.py
GermaNet.all_synsets
def all_synsets(self): ''' A generator over all the synsets in the GermaNet database. ''' for synset_dict in self._mongo_db.synsets.find(): yield Synset(self, synset_dict)
python
def all_synsets(self): ''' A generator over all the synsets in the GermaNet database. ''' for synset_dict in self._mongo_db.synsets.find(): yield Synset(self, synset_dict)
[ "def", "all_synsets", "(", "self", ")", ":", "for", "synset_dict", "in", "self", ".", "_mongo_db", ".", "synsets", ".", "find", "(", ")", ":", "yield", "Synset", "(", "self", ",", "synset_dict", ")" ]
A generator over all the synsets in the GermaNet database.
[ "A", "generator", "over", "all", "the", "synsets", "in", "the", "GermaNet", "database", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L110-L115
wroberts/pygermanet
pygermanet/germanet.py
GermaNet.synsets
def synsets(self, lemma, pos = None): ''' Looks up synsets in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' return sorted(set(lemma_obj.synset for lemma_obj in self.lemmas(lemma, pos)))
python
def synsets(self, lemma, pos = None): ''' Looks up synsets in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' return sorted(set(lemma_obj.synset for lemma_obj in self.lemmas(lemma, pos)))
[ "def", "synsets", "(", "self", ",", "lemma", ",", "pos", "=", "None", ")", ":", "return", "sorted", "(", "set", "(", "lemma_obj", ".", "synset", "for", "lemma_obj", "in", "self", ".", "lemmas", "(", "lemma", ",", "pos", ")", ")", ")" ]
Looks up synsets in the GermaNet database. Arguments: - `lemma`: - `pos`:
[ "Looks", "up", "synsets", "in", "the", "GermaNet", "database", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L117-L126
wroberts/pygermanet
pygermanet/germanet.py
GermaNet.synset
def synset(self, synset_repr): ''' Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'funktionieren.v.2') ...
python
def synset(self, synset_repr): ''' Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'funktionieren.v.2') ...
[ "def", "synset", "(", "self", ",", "synset_repr", ")", ":", "parts", "=", "synset_repr", ".", "split", "(", "'.'", ")", "if", "len", "(", "parts", ")", "!=", "3", ":", "return", "None", "lemma", ",", "pos", ",", "sensenum", "=", "parts", "if", "not...
Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'funktionieren.v.2') Synset(funktionieren.v.2)
[ "Looks", "up", "a", "synset", "in", "GermaNet", "using", "its", "string", "representation", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L128-L151
wroberts/pygermanet
pygermanet/germanet.py
GermaNet.get_synset_by_id
def get_synset_by_id(self, mongo_id): ''' Builds a Synset object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._synset_cache is not None: cache_hit = self...
python
def get_synset_by_id(self, mongo_id): ''' Builds a Synset object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._synset_cache is not None: cache_hit = self...
[ "def", "get_synset_by_id", "(", "self", ",", "mongo_id", ")", ":", "cache_hit", "=", "None", "if", "self", ".", "_synset_cache", "is", "not", "None", ":", "cache_hit", "=", "self", ".", "_synset_cache", ".", "get", "(", "mongo_id", ")", "if", "cache_hit", ...
Builds a Synset object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object
[ "Builds", "a", "Synset", "object", "from", "the", "database", "entry", "with", "the", "given", "ObjectId", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L153-L171
wroberts/pygermanet
pygermanet/germanet.py
GermaNet.get_lemma_by_id
def get_lemma_by_id(self, mongo_id): ''' Builds a Lemma object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._lemma_cache is not None: cache_hit = self._l...
python
def get_lemma_by_id(self, mongo_id): ''' Builds a Lemma object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._lemma_cache is not None: cache_hit = self._l...
[ "def", "get_lemma_by_id", "(", "self", ",", "mongo_id", ")", ":", "cache_hit", "=", "None", "if", "self", ".", "_lemma_cache", "is", "not", "None", ":", "cache_hit", "=", "self", ".", "_lemma_cache", ".", "get", "(", "mongo_id", ")", "if", "cache_hit", "...
Builds a Lemma object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object
[ "Builds", "a", "Lemma", "object", "from", "the", "database", "entry", "with", "the", "given", "ObjectId", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L173-L191
wroberts/pygermanet
pygermanet/germanet.py
GermaNet.lemmatise
def lemmatise(self, word): ''' Tries to find the base form (lemma) of the given word, using the data provided by the Projekt deutscher Wortschatz. This method returns a list of potential lemmas. >>> gn.lemmatise(u'Männer') [u'Mann'] >>> gn.lemmatise(u'XYZ123') ...
python
def lemmatise(self, word): ''' Tries to find the base form (lemma) of the given word, using the data provided by the Projekt deutscher Wortschatz. This method returns a list of potential lemmas. >>> gn.lemmatise(u'Männer') [u'Mann'] >>> gn.lemmatise(u'XYZ123') ...
[ "def", "lemmatise", "(", "self", ",", "word", ")", ":", "lemmas", "=", "list", "(", "self", ".", "_mongo_db", ".", "lemmatiser", ".", "find", "(", "{", "'word'", ":", "word", "}", ")", ")", "if", "lemmas", ":", "return", "[", "lemma", "[", "'lemma'...
Tries to find the base form (lemma) of the given word, using the data provided by the Projekt deutscher Wortschatz. This method returns a list of potential lemmas. >>> gn.lemmatise(u'Männer') [u'Mann'] >>> gn.lemmatise(u'XYZ123') [u'XYZ123']
[ "Tries", "to", "find", "the", "base", "form", "(", "lemma", ")", "of", "the", "given", "word", "using", "the", "data", "provided", "by", "the", "Projekt", "deutscher", "Wortschatz", ".", "This", "method", "returns", "a", "list", "of", "potential", "lemmas"...
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/germanet.py#L193-L208
wroberts/pygermanet
pygermanet/mongo_import.py
find_germanet_xml_files
def find_germanet_xml_files(xml_path): ''' Globs the XML files contained in the given directory and sorts them into sections for import into the MongoDB database. Arguments: - `xml_path`: the path to the directory containing the GermaNet XML files ''' xml_files = sorted(glob.glob(os.p...
python
def find_germanet_xml_files(xml_path): ''' Globs the XML files contained in the given directory and sorts them into sections for import into the MongoDB database. Arguments: - `xml_path`: the path to the directory containing the GermaNet XML files ''' xml_files = sorted(glob.glob(os.p...
[ "def", "find_germanet_xml_files", "(", "xml_path", ")", ":", "xml_files", "=", "sorted", "(", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "xml_path", ",", "'*.xml'", ")", ")", ")", "# sort out the lexical files", "lex_files", "=", "[", "...
Globs the XML files contained in the given directory and sorts them into sections for import into the MongoDB database. Arguments: - `xml_path`: the path to the directory containing the GermaNet XML files
[ "Globs", "the", "XML", "files", "contained", "in", "the", "given", "directory", "and", "sorts", "them", "into", "sections", "for", "import", "into", "the", "MongoDB", "database", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L30-L85
wroberts/pygermanet
pygermanet/mongo_import.py
warn_attribs
def warn_attribs(loc, node, recognised_attribs, reqd_attribs=None): ''' Error checking of XML input: check that the given node has certain required attributes, and does not have any unrecognised attributes. Arguments: - `loc`: a string with som...
python
def warn_attribs(loc, node, recognised_attribs, reqd_attribs=None): ''' Error checking of XML input: check that the given node has certain required attributes, and does not have any unrecognised attributes. Arguments: - `loc`: a string with som...
[ "def", "warn_attribs", "(", "loc", ",", "node", ",", "recognised_attribs", ",", "reqd_attribs", "=", "None", ")", ":", "if", "reqd_attribs", "is", "None", ":", "reqd_attribs", "=", "recognised_attribs", "found_attribs", "=", "set", "(", "node", ".", "keys", ...
Error checking of XML input: check that the given node has certain required attributes, and does not have any unrecognised attributes. Arguments: - `loc`: a string with some information about the location of the error in the XML file - `node`: the node to check - `recognised_attribs`: a s...
[ "Error", "checking", "of", "XML", "input", ":", "check", "that", "the", "given", "node", "has", "certain", "required", "attributes", "and", "does", "not", "have", "any", "unrecognised", "attributes", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L92-L119
wroberts/pygermanet
pygermanet/mongo_import.py
read_lexical_file
def read_lexical_file(filename): ''' Reads in a GermaNet lexical information file and returns its contents as a list of dictionary structures. Arguments: - `filename`: the name of the XML file to read ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) sy...
python
def read_lexical_file(filename): ''' Reads in a GermaNet lexical information file and returns its contents as a list of dictionary structures. Arguments: - `filename`: the name of the XML file to read ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) sy...
[ "def", "read_lexical_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "input_file", ":", "doc", "=", "etree", ".", "parse", "(", "input_file", ")", "synsets", "=", "[", "]", "assert", "doc", ".", "getroot", "("...
Reads in a GermaNet lexical information file and returns its contents as a list of dictionary structures. Arguments: - `filename`: the name of the XML file to read
[ "Reads", "in", "a", "GermaNet", "lexical", "information", "file", "and", "returns", "its", "contents", "as", "a", "list", "of", "dictionary", "structures", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L132-L275
wroberts/pygermanet
pygermanet/mongo_import.py
read_relation_file
def read_relation_file(filename): ''' Reads the GermaNet relation file ``gn_relations.xml`` which lists all the relations holding between lexical units and synsets. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) lex_rels = []...
python
def read_relation_file(filename): ''' Reads the GermaNet relation file ``gn_relations.xml`` which lists all the relations holding between lexical units and synsets. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) lex_rels = []...
[ "def", "read_relation_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "input_file", ":", "doc", "=", "etree", ".", "parse", "(", "input_file", ")", "lex_rels", "=", "[", "]", "con_rels", "=", "[", "]", "assert...
Reads the GermaNet relation file ``gn_relations.xml`` which lists all the relations holding between lexical units and synsets. Arguments: - `filename`:
[ "Reads", "the", "GermaNet", "relation", "file", "gn_relations", ".", "xml", "which", "lists", "all", "the", "relations", "holding", "between", "lexical", "units", "and", "synsets", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L288-L329
wroberts/pygermanet
pygermanet/mongo_import.py
read_paraphrase_file
def read_paraphrase_file(filename): ''' Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) assert doc.getroot().tag == 'w...
python
def read_paraphrase_file(filename): ''' Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) assert doc.getroot().tag == 'w...
[ "def", "read_paraphrase_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "input_file", ":", "doc", "=", "etree", ".", "parse", "(", "input_file", ")", "assert", "doc", ".", "getroot", "(", ")", ".", "tag", "=="...
Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures. Arguments: - `filename`:
[ "Reads", "in", "a", "GermaNet", "wiktionary", "paraphrase", "file", "and", "returns", "its", "contents", "as", "a", "list", "of", "dictionary", "structures", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L339-L376
wroberts/pygermanet
pygermanet/mongo_import.py
insert_lexical_information
def insert_lexical_information(germanet_db, lex_files): ''' Reads in the given lexical information files and inserts their contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `lex_files`: a list of paths to XML files containing lexial ...
python
def insert_lexical_information(germanet_db, lex_files): ''' Reads in the given lexical information files and inserts their contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `lex_files`: a list of paths to XML files containing lexial ...
[ "def", "insert_lexical_information", "(", "germanet_db", ",", "lex_files", ")", ":", "# drop the database collections if they already exist", "germanet_db", ".", "lexunits", ".", "drop", "(", ")", "germanet_db", ".", "synsets", ".", "drop", "(", ")", "# inject data from...
Reads in the given lexical information files and inserts their contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `lex_files`: a list of paths to XML files containing lexial information
[ "Reads", "in", "the", "given", "lexical", "information", "files", "and", "inserts", "their", "contents", "into", "the", "given", "MongoDB", "database", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L389-L427
wroberts/pygermanet
pygermanet/mongo_import.py
insert_relation_information
def insert_relation_information(germanet_db, gn_rels_file): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `gn_rels_file`: ''' lex_rels, con_rels = read_relation_fil...
python
def insert_relation_information(germanet_db, gn_rels_file): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `gn_rels_file`: ''' lex_rels, con_rels = read_relation_fil...
[ "def", "insert_relation_information", "(", "germanet_db", ",", "gn_rels_file", ")", ":", "lex_rels", ",", "con_rels", "=", "read_relation_file", "(", "gn_rels_file", ")", "# cache the lexunits while we work on them", "lexunits", "=", "{", "}", "for", "lex_rel", "in", ...
Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `gn_rels_file`:
[ "Reads", "in", "the", "given", "GermaNet", "relation", "file", "and", "inserts", "its", "contents", "into", "the", "given", "MongoDB", "database", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L429-L487
wroberts/pygermanet
pygermanet/mongo_import.py
insert_paraphrase_information
def insert_paraphrase_information(germanet_db, wiktionary_files): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `wiktionary_files`: ''' num_paraphrases = 0 # ca...
python
def insert_paraphrase_information(germanet_db, wiktionary_files): ''' Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `wiktionary_files`: ''' num_paraphrases = 0 # ca...
[ "def", "insert_paraphrase_information", "(", "germanet_db", ",", "wiktionary_files", ")", ":", "num_paraphrases", "=", "0", "# cache the lexunits while we work on them", "lexunits", "=", "{", "}", "for", "filename", "in", "wiktionary_files", ":", "paraphrases", "=", "re...
Reads in the given GermaNet relation file and inserts its contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `wiktionary_files`:
[ "Reads", "in", "the", "given", "GermaNet", "relation", "file", "and", "inserts", "its", "contents", "into", "the", "given", "MongoDB", "database", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L489-L516
wroberts/pygermanet
pygermanet/mongo_import.py
insert_lemmatisation_data
def insert_lemmatisation_data(germanet_db): ''' Creates the lemmatiser collection in the given MongoDB instance using the data derived from the Projekt deutscher Wortschatz. Arguments: - `germanet_db`: a pymongo.database.Database object ''' # drop the database collection if it already exist...
python
def insert_lemmatisation_data(germanet_db): ''' Creates the lemmatiser collection in the given MongoDB instance using the data derived from the Projekt deutscher Wortschatz. Arguments: - `germanet_db`: a pymongo.database.Database object ''' # drop the database collection if it already exist...
[ "def", "insert_lemmatisation_data", "(", "germanet_db", ")", ":", "# drop the database collection if it already exists", "germanet_db", ".", "lemmatiser", ".", "drop", "(", ")", "num_lemmas", "=", "0", "input_file", "=", "gzip", ".", "open", "(", "os", ".", "path", ...
Creates the lemmatiser collection in the given MongoDB instance using the data derived from the Projekt deutscher Wortschatz. Arguments: - `germanet_db`: a pymongo.database.Database object
[ "Creates", "the", "lemmatiser", "collection", "in", "the", "given", "MongoDB", "instance", "using", "the", "data", "derived", "from", "the", "Projekt", "deutscher", "Wortschatz", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L520-L542
wroberts/pygermanet
pygermanet/mongo_import.py
insert_infocontent_data
def insert_infocontent_data(germanet_db): ''' For every synset in GermaNet, inserts count information derived from SDEWAC. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) # use add one smoothing gn_counts = defa...
python
def insert_infocontent_data(germanet_db): ''' For every synset in GermaNet, inserts count information derived from SDEWAC. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) # use add one smoothing gn_counts = defa...
[ "def", "insert_infocontent_data", "(", "germanet_db", ")", ":", "gnet", "=", "germanet", ".", "GermaNet", "(", "germanet_db", ")", "# use add one smoothing", "gn_counts", "=", "defaultdict", "(", "lambda", ":", "1.", ")", "total_count", "=", "1", "input_file", "...
For every synset in GermaNet, inserts count information derived from SDEWAC. Arguments: - `germanet_db`: a pymongo.database.Database object
[ "For", "every", "synset", "in", "GermaNet", "inserts", "count", "information", "derived", "from", "SDEWAC", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L551-L600
wroberts/pygermanet
pygermanet/mongo_import.py
compute_max_min_depth
def compute_max_min_depth(germanet_db): ''' For every part of speech in GermaNet, computes the maximum min_depth in that hierarchy. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) max_min_depths = defaultdict(lambda: -1)...
python
def compute_max_min_depth(germanet_db): ''' For every part of speech in GermaNet, computes the maximum min_depth in that hierarchy. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) max_min_depths = defaultdict(lambda: -1)...
[ "def", "compute_max_min_depth", "(", "germanet_db", ")", ":", "gnet", "=", "germanet", ".", "GermaNet", "(", "germanet_db", ")", "max_min_depths", "=", "defaultdict", "(", "lambda", ":", "-", "1", ")", "for", "synset", "in", "gnet", ".", "all_synsets", "(", ...
For every part of speech in GermaNet, computes the maximum min_depth in that hierarchy. Arguments: - `germanet_db`: a pymongo.database.Database object
[ "For", "every", "part", "of", "speech", "in", "GermaNet", "computes", "the", "maximum", "min_depth", "in", "that", "hierarchy", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L602-L625
wroberts/pygermanet
pygermanet/mongo_import.py
main
def main(): '''Main function.''' usage = ('\n\n %prog [options] XML_PATH\n\nArguments:\n\n ' 'XML_PATH the directory containing the ' 'GermaNet .xml files') parser = optparse.OptionParser(usage=usage) parser.add_option('--host', default=None, ...
python
def main(): '''Main function.''' usage = ('\n\n %prog [options] XML_PATH\n\nArguments:\n\n ' 'XML_PATH the directory containing the ' 'GermaNet .xml files') parser = optparse.OptionParser(usage=usage) parser.add_option('--host', default=None, ...
[ "def", "main", "(", ")", ":", "usage", "=", "(", "'\\n\\n %prog [options] XML_PATH\\n\\nArguments:\\n\\n '", "'XML_PATH the directory containing the '", "'GermaNet .xml files'", ")", "parser", "=", "optparse", ".", "OptionParser", "(", "usage", "=", "usage", ...
Main function.
[ "Main", "function", "." ]
train
https://github.com/wroberts/pygermanet/blob/1818c20a7e8c431c4cfb5a570ed0d850bb6dd515/pygermanet/mongo_import.py#L632-L669
alonho/pql
pql/matching.py
Operator.handle_In
def handle_In(self, node): '''in''' try: elts = node.elts except AttributeError: raise ParseError('Invalid value type for `in` operator: {0}'.format(node.__class__.__name__), col_offset=node.col_offset) return {'$in': list(map(self.fie...
python
def handle_In(self, node): '''in''' try: elts = node.elts except AttributeError: raise ParseError('Invalid value type for `in` operator: {0}'.format(node.__class__.__name__), col_offset=node.col_offset) return {'$in': list(map(self.fie...
[ "def", "handle_In", "(", "self", ",", "node", ")", ":", "try", ":", "elts", "=", "node", ".", "elts", "except", "AttributeError", ":", "raise", "ParseError", "(", "'Invalid value type for `in` operator: {0}'", ".", "format", "(", "node", ".", "__class__", ".",...
in
[ "in" ]
train
https://github.com/alonho/pql/blob/fd8fefcb720b4325d27ab71f15a882fe5f9f77e2/pql/matching.py#L302-L309
jonathanslenders/textfsm
jtextfsm.py
TextFSMValue.AssignVar
def AssignVar(self, value): """Assign a value to this Value.""" self.value = value # Call OnAssignVar on options. [option.OnAssignVar() for option in self.options]
python
def AssignVar(self, value): """Assign a value to this Value.""" self.value = value # Call OnAssignVar on options. [option.OnAssignVar() for option in self.options]
[ "def", "AssignVar", "(", "self", ",", "value", ")", ":", "self", ".", "value", "=", "value", "# Call OnAssignVar on options.", "[", "option", ".", "OnAssignVar", "(", ")", "for", "option", "in", "self", ".", "options", "]" ]
Assign a value to this Value.
[ "Assign", "a", "value", "to", "this", "Value", "." ]
train
https://github.com/jonathanslenders/textfsm/blob/cca5084512d14bc367205aceb34c938ac1c65daf/jtextfsm.py#L223-L227
jonathanslenders/textfsm
jtextfsm.py
TextFSMValue.Parse
def Parse(self, value): """Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error. """ value_line = value.split(' ') if len(value_line) < 3: raise TextFSMTemplat...
python
def Parse(self, value): """Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error. """ value_line = value.split(' ') if len(value_line) < 3: raise TextFSMTemplat...
[ "def", "Parse", "(", "self", ",", "value", ")", ":", "value_line", "=", "value", ".", "split", "(", "' '", ")", "if", "len", "(", "value_line", ")", "<", "3", ":", "raise", "TextFSMTemplateError", "(", "'Expect at least 3 tokens on line.'", ")", "if", "not...
Parse a 'Value' declaration. Args: value: String line from a template file, must begin with 'Value '. Raises: TextFSMTemplateError: Value declaration contains an error.
[ "Parse", "a", "Value", "declaration", "." ]
train
https://github.com/jonathanslenders/textfsm/blob/cca5084512d14bc367205aceb34c938ac1c65daf/jtextfsm.py#L251-L291
jonathanslenders/textfsm
jtextfsm.py
TextFSM._CheckLine
def _CheckLine(self, line): """Passes the line through each rule until a match is made. Args: line: A string, the current input line. """ for rule in self._cur_state: matched = self._CheckRule(rule, line) if matched: for value in matched.groupdict(): self._AssignVar(...
python
def _CheckLine(self, line): """Passes the line through each rule until a match is made. Args: line: A string, the current input line. """ for rule in self._cur_state: matched = self._CheckRule(rule, line) if matched: for value in matched.groupdict(): self._AssignVar(...
[ "def", "_CheckLine", "(", "self", ",", "line", ")", ":", "for", "rule", "in", "self", ".", "_cur_state", ":", "matched", "=", "self", ".", "_CheckRule", "(", "rule", ",", "line", ")", "if", "matched", ":", "for", "value", "in", "matched", ".", "group...
Passes the line through each rule until a match is made. Args: line: A string, the current input line.
[ "Passes", "the", "line", "through", "each", "rule", "until", "a", "match", "is", "made", "." ]
train
https://github.com/jonathanslenders/textfsm/blob/cca5084512d14bc367205aceb34c938ac1c65daf/jtextfsm.py#L866-L884
vimeo/graphite-influxdb
graphite_influxdb.py
_make_graphite_api_points_list
def _make_graphite_api_points_list(influxdb_data): """Make graphite-api data points dictionary from Influxdb ResultSet data""" _data = {} for key in influxdb_data.keys(): _data[key[0]] = [(datetime.datetime.fromtimestamp(float(d['time'])), d['value']) for d in influxdb_data...
python
def _make_graphite_api_points_list(influxdb_data): """Make graphite-api data points dictionary from Influxdb ResultSet data""" _data = {} for key in influxdb_data.keys(): _data[key[0]] = [(datetime.datetime.fromtimestamp(float(d['time'])), d['value']) for d in influxdb_data...
[ "def", "_make_graphite_api_points_list", "(", "influxdb_data", ")", ":", "_data", "=", "{", "}", "for", "key", "in", "influxdb_data", ".", "keys", "(", ")", ":", "_data", "[", "key", "[", "0", "]", "]", "=", "[", "(", "datetime", ".", "datetime", ".", ...
Make graphite-api data points dictionary from Influxdb ResultSet data
[ "Make", "graphite", "-", "api", "data", "points", "dictionary", "from", "Influxdb", "ResultSet", "data" ]
train
https://github.com/vimeo/graphite-influxdb/blob/56e4aeec57f39c90f14f3fbec57641b90d06c08b/graphite_influxdb.py#L90-L96
vimeo/graphite-influxdb
graphite_influxdb.py
InfluxdbFinder._setup_logger
def _setup_logger(self, level, log_file): """Setup log level and log file if set""" if logger.handlers: return level = getattr(logging, level.upper()) logger.setLevel(level) formatter = logging.Formatter( '[%(levelname)s] %(asctime)s - %(module)s.%(funcNam...
python
def _setup_logger(self, level, log_file): """Setup log level and log file if set""" if logger.handlers: return level = getattr(logging, level.upper()) logger.setLevel(level) formatter = logging.Formatter( '[%(levelname)s] %(asctime)s - %(module)s.%(funcNam...
[ "def", "_setup_logger", "(", "self", ",", "level", ",", "log_file", ")", ":", "if", "logger", ".", "handlers", ":", "return", "level", "=", "getattr", "(", "logging", ",", "level", ".", "upper", "(", ")", ")", "logger", ".", "setLevel", "(", "level", ...
Setup log level and log file if set
[ "Setup", "log", "level", "and", "log", "file", "if", "set" ]
train
https://github.com/vimeo/graphite-influxdb/blob/56e4aeec57f39c90f14f3fbec57641b90d06c08b/graphite_influxdb.py#L166-L186
vimeo/graphite-influxdb
graphite_influxdb.py
InfluxdbFinder.compile_regex
def compile_regex(self, fmt, query): """Turn glob (graphite) queries into compiled regex * becomes .* . becomes \. fmt argument is so that caller can control anchoring (must contain exactly 1 {0} !""" return re.compile(fmt.format( query.pattern.replace('.', '\.').repl...
python
def compile_regex(self, fmt, query): """Turn glob (graphite) queries into compiled regex * becomes .* . becomes \. fmt argument is so that caller can control anchoring (must contain exactly 1 {0} !""" return re.compile(fmt.format( query.pattern.replace('.', '\.').repl...
[ "def", "compile_regex", "(", "self", ",", "fmt", ",", "query", ")", ":", "return", "re", ".", "compile", "(", "fmt", ".", "format", "(", "query", ".", "pattern", ".", "replace", "(", "'.'", ",", "'\\.'", ")", ".", "replace", "(", "'*'", ",", "'[^\\...
Turn glob (graphite) queries into compiled regex * becomes .* . becomes \. fmt argument is so that caller can control anchoring (must contain exactly 1 {0} !
[ "Turn", "glob", "(", "graphite", ")", "queries", "into", "compiled", "regex", "*", "becomes", ".", "*", ".", "becomes", "\\", ".", "fmt", "argument", "is", "so", "that", "caller", "can", "control", "anchoring", "(", "must", "contain", "exactly", "1", "{"...
train
https://github.com/vimeo/graphite-influxdb/blob/56e4aeec57f39c90f14f3fbec57641b90d06c08b/graphite_influxdb.py#L230-L238
alonho/pql
pql/__init__.py
find
def find(expression, schema=None): ''' Gets an <expression> and optional <schema>. <expression> should be a string of python code. <schema> should be a dictionary mapping field names to types. ''' parser = SchemaFreeParser() if schema is None else SchemaAwareParser(schema) return parser.pars...
python
def find(expression, schema=None): ''' Gets an <expression> and optional <schema>. <expression> should be a string of python code. <schema> should be a dictionary mapping field names to types. ''' parser = SchemaFreeParser() if schema is None else SchemaAwareParser(schema) return parser.pars...
[ "def", "find", "(", "expression", ",", "schema", "=", "None", ")", ":", "parser", "=", "SchemaFreeParser", "(", ")", "if", "schema", "is", "None", "else", "SchemaAwareParser", "(", "schema", ")", "return", "parser", ".", "parse", "(", "expression", ")" ]
Gets an <expression> and optional <schema>. <expression> should be a string of python code. <schema> should be a dictionary mapping field names to types.
[ "Gets", "an", "<expression", ">", "and", "optional", "<schema", ">", ".", "<expression", ">", "should", "be", "a", "string", "of", "python", "code", ".", "<schema", ">", "should", "be", "a", "dictionary", "mapping", "field", "names", "to", "types", "." ]
train
https://github.com/alonho/pql/blob/fd8fefcb720b4325d27ab71f15a882fe5f9f77e2/pql/__init__.py#L7-L14
alonho/pql
pql/__init__.py
sort
def sort(fields): ''' Gets a list of <fields> to sort by. Also supports getting a single string for sorting by one field. Reverse sort is supported by appending '-' to the field name. Example: sort(['age', '-height']) will sort by ascending age and descending height. ''' from pymongo import ...
python
def sort(fields): ''' Gets a list of <fields> to sort by. Also supports getting a single string for sorting by one field. Reverse sort is supported by appending '-' to the field name. Example: sort(['age', '-height']) will sort by ascending age and descending height. ''' from pymongo import ...
[ "def", "sort", "(", "fields", ")", ":", "from", "pymongo", "import", "ASCENDING", ",", "DESCENDING", "from", "bson", "import", "SON", "if", "isinstance", "(", "fields", ",", "str", ")", ":", "fields", "=", "[", "fields", "]", "if", "not", "hasattr", "(...
Gets a list of <fields> to sort by. Also supports getting a single string for sorting by one field. Reverse sort is supported by appending '-' to the field name. Example: sort(['age', '-height']) will sort by ascending age and descending height.
[ "Gets", "a", "list", "of", "<fields", ">", "to", "sort", "by", ".", "Also", "supports", "getting", "a", "single", "string", "for", "sorting", "by", "one", "field", ".", "Reverse", "sort", "is", "supported", "by", "appending", "-", "to", "the", "field", ...
train
https://github.com/alonho/pql/blob/fd8fefcb720b4325d27ab71f15a882fe5f9f77e2/pql/__init__.py#L73-L97
numberoverzero/bloop
bloop/util.py
ordered
def ordered(obj): """ Return sorted version of nested dicts/lists for comparing. Modified from: http://stackoverflow.com/a/25851972 """ if isinstance(obj, collections.abc.Mapping): return sorted((k, ordered(v)) for k, v in obj.items()) # Special case str since it's a collections.abc...
python
def ordered(obj): """ Return sorted version of nested dicts/lists for comparing. Modified from: http://stackoverflow.com/a/25851972 """ if isinstance(obj, collections.abc.Mapping): return sorted((k, ordered(v)) for k, v in obj.items()) # Special case str since it's a collections.abc...
[ "def", "ordered", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "collections", ".", "abc", ".", "Mapping", ")", ":", "return", "sorted", "(", "(", "k", ",", "ordered", "(", "v", ")", ")", "for", "k", ",", "v", "in", "obj", ".", "it...
Return sorted version of nested dicts/lists for comparing. Modified from: http://stackoverflow.com/a/25851972
[ "Return", "sorted", "version", "of", "nested", "dicts", "/", "lists", "for", "comparing", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/util.py#L65-L80
numberoverzero/bloop
bloop/util.py
walk_subclasses
def walk_subclasses(root): """Does not yield the input class""" classes = [root] visited = set() while classes: cls = classes.pop() if cls is type or cls in visited: continue classes.extend(cls.__subclasses__()) visited.add(cls) if cls is not root: ...
python
def walk_subclasses(root): """Does not yield the input class""" classes = [root] visited = set() while classes: cls = classes.pop() if cls is type or cls in visited: continue classes.extend(cls.__subclasses__()) visited.add(cls) if cls is not root: ...
[ "def", "walk_subclasses", "(", "root", ")", ":", "classes", "=", "[", "root", "]", "visited", "=", "set", "(", ")", "while", "classes", ":", "cls", "=", "classes", ".", "pop", "(", ")", "if", "cls", "is", "type", "or", "cls", "in", "visited", ":", ...
Does not yield the input class
[ "Does", "not", "yield", "the", "input", "class" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/util.py#L83-L94
numberoverzero/bloop
bloop/util.py
dump_key
def dump_key(engine, obj): """dump the hash (and range, if there is one) key(s) of an object into a dynamo-friendly format. returns {dynamo_name: {type: value} for dynamo_name in hash/range keys} """ key = {} for key_column in obj.Meta.keys: key_value = getattr(obj, key_column.name, mis...
python
def dump_key(engine, obj): """dump the hash (and range, if there is one) key(s) of an object into a dynamo-friendly format. returns {dynamo_name: {type: value} for dynamo_name in hash/range keys} """ key = {} for key_column in obj.Meta.keys: key_value = getattr(obj, key_column.name, mis...
[ "def", "dump_key", "(", "engine", ",", "obj", ")", ":", "key", "=", "{", "}", "for", "key_column", "in", "obj", ".", "Meta", ".", "keys", ":", "key_value", "=", "getattr", "(", "obj", ",", "key_column", ".", "name", ",", "missing", ")", "if", "key_...
dump the hash (and range, if there is one) key(s) of an object into a dynamo-friendly format. returns {dynamo_name: {type: value} for dynamo_name in hash/range keys}
[ "dump", "the", "hash", "(", "and", "range", "if", "there", "is", "one", ")", "key", "(", "s", ")", "of", "an", "object", "into", "a", "dynamo", "-", "friendly", "format", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/util.py#L125-L142
numberoverzero/bloop
examples/mixins.py
new_expiry
def new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS): """Return an expiration `days` in the future""" now = delorean.Delorean() return now + datetime.timedelta(days=days)
python
def new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS): """Return an expiration `days` in the future""" now = delorean.Delorean() return now + datetime.timedelta(days=days)
[ "def", "new_expiry", "(", "days", "=", "DEFAULT_PASTE_LIFETIME_DAYS", ")", ":", "now", "=", "delorean", ".", "Delorean", "(", ")", "return", "now", "+", "datetime", ".", "timedelta", "(", "days", "=", "days", ")" ]
Return an expiration `days` in the future
[ "Return", "an", "expiration", "days", "in", "the", "future" ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/examples/mixins.py#L14-L17
numberoverzero/bloop
bloop/conditions.py
sync
def sync(obj, engine): """Mark the object as having been persisted at least once. Store the latest snapshot of all marked values.""" snapshot = Condition() # Only expect values (or lack of a value) for columns that have been explicitly set for column in sorted(_obj_tracking[obj]["marked"], key=lamb...
python
def sync(obj, engine): """Mark the object as having been persisted at least once. Store the latest snapshot of all marked values.""" snapshot = Condition() # Only expect values (or lack of a value) for columns that have been explicitly set for column in sorted(_obj_tracking[obj]["marked"], key=lamb...
[ "def", "sync", "(", "obj", ",", "engine", ")", ":", "snapshot", "=", "Condition", "(", ")", "# Only expect values (or lack of a value) for columns that have been explicitly set", "for", "column", "in", "sorted", "(", "_obj_tracking", "[", "obj", "]", "[", "\"marked\""...
Mark the object as having been persisted at least once. Store the latest snapshot of all marked values.
[ "Mark", "the", "object", "as", "having", "been", "persisted", "at", "least", "once", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L63-L78
numberoverzero/bloop
bloop/conditions.py
printable_name
def printable_name(column, path=None): """Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar """ pieces = [column.name] path = path or path_of(column) for segment in path: if isinstance(segment, str): pieces.append(segmen...
python
def printable_name(column, path=None): """Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar """ pieces = [column.name] path = path or path_of(column) for segment in path: if isinstance(segment, str): pieces.append(segmen...
[ "def", "printable_name", "(", "column", ",", "path", "=", "None", ")", ":", "pieces", "=", "[", "column", ".", "name", "]", "path", "=", "path", "or", "path_of", "(", "column", ")", "for", "segment", "in", "path", ":", "if", "isinstance", "(", "segme...
Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar
[ "Provided", "for", "debug", "output", "when", "rendering", "conditions", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L887-L899
numberoverzero/bloop
bloop/conditions.py
iter_conditions
def iter_conditions(condition): """Yield all conditions within the given condition. If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found).""" conditions = list() visited = set() # Has to be split out, since we don't want to visit the root (for cyclic cond...
python
def iter_conditions(condition): """Yield all conditions within the given condition. If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found).""" conditions = list() visited = set() # Has to be split out, since we don't want to visit the root (for cyclic cond...
[ "def", "iter_conditions", "(", "condition", ")", ":", "conditions", "=", "list", "(", ")", "visited", "=", "set", "(", ")", "# Has to be split out, since we don't want to visit the root (for cyclic conditions)", "# but we don't want to yield it (if it's non-cyclic) because this onl...
Yield all conditions within the given condition. If the root condition is and/or/not, it is not yielded (unless a cyclic reference to it is found).
[ "Yield", "all", "conditions", "within", "the", "given", "condition", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L914-L935
numberoverzero/bloop
bloop/conditions.py
iter_columns
def iter_columns(condition): """ Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths. """ # Like iter_conditions, this can't live in each condition without going possibly infinite on the # recursion, or pas...
python
def iter_columns(condition): """ Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths. """ # Like iter_conditions, this can't live in each condition without going possibly infinite on the # recursion, or pas...
[ "def", "iter_columns", "(", "condition", ")", ":", "# Like iter_conditions, this can't live in each condition without going possibly infinite on the", "# recursion, or passing the visited set through every call. That makes the signature ugly, so we", "# take care of it here. Luckily, it's pretty e...
Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) include paths.
[ "Yield", "all", "columns", "in", "the", "condition", "or", "its", "inner", "conditions", "." ]
train
https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/conditions.py#L938-L970