code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
r
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('Given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_labels_):
pred[:, i] = self.clfs_[i].predict(X)
return pred.astype(int)
|
def predict(self, X)
|
r"""Predict labels.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted labels of given feature vector.
| 2.989619 | 3.067501 | 0.97461 |
r
X = np.asarray(X)
if self.clfs_ is None:
raise ValueError("Train before prediction")
if X.shape[1] != self.n_features_:
raise ValueError('given feature size does not match')
pred = np.zeros((X.shape[0], self.n_labels_))
for i in range(self.n_labels_):
pred[:, i] = self.clfs_[i].predict_real(X)[:, 1]
return pred
|
def predict_real(self, X)
|
r"""Predict the probability of being 1 for each label.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted probability of each label.
| 3.206027 | 3.299707 | 0.971609 |
# TODO check if data in dataset are all correct
X, Y = testing_dataset.format_sklearn()
if criterion == 'hamming':
return np.mean(np.abs(self.predict(X) - Y).mean(axis=1))
elif criterion == 'f1':
Z = self.predict(X)
Z = Z.astype(int)
Y = Y.astype(int)
up = 2*np.sum(Z & Y, axis=1).astype(float)
down1 = np.sum(Z, axis=1)
down2 = np.sum(Y, axis=1)
down = (down1 + down2)
down[down==0] = 1.
up[down==0] = 1.
return np.mean(up / down)
else:
raise NotImplementedError(
"criterion '%s' not implemented" % criterion)
|
def score(self, testing_dataset, criterion='hamming')
|
Return the mean accuracy on the test dataset
Parameters
----------
testing_dataset : Dataset object
The testing dataset used to measure the perforance of the trained
model.
criterion : ['hamming', 'f1']
instance-wise criterion.
Returns
-------
score : float
Mean accuracy of self.predict(X) wrt. y.
| 3.06123 | 3.053513 | 1.002527 |
if self.w_ is not None:
sigmoid = lambda t: 1. / (1. + np.exp(-t))
return sigmoid(np.dot(self.centers, self.w_[:-1]) + self.w_[-1])
else:
# TODO the model is not trained
pass
|
def predict(self)
|
Returns
-------
proba : ndarray, shape=(n_clusters, )
The probability of given cluster being label 1.
| 4.484375 | 4.057502 | 1.105206 |
def fit(self, X, y=None, init=None):
self.fit_transform(X, init=init)
return self
|
Computes the position of the points in the embedding space
Parameters
----------
X : array, shape=[n_samples, n_features], or [n_samples, n_samples] \
if dissimilarity='precomputed'
Input data.
init : {None or ndarray, shape (n_samples,)}, optional
If None, randomly chooses the initial configuration
if ndarray, initialize the SMACOF algorithm with this array.
| null | null | null |
|
def fit_transform(self, X, y=None, init=None):
X = check_array(X)
if X.shape[0] == X.shape[1] and self.dissimilarity != "precomputed":
warnings.warn("The MDS API has changed. ``fit`` now constructs an"
" dissimilarity matrix from data. To use a custom "
"dissimilarity matrix, set "
"``dissimilarity=precomputed``.")
if self.dissimilarity == "precomputed":
self.dissimilarity_matrix_ = X
elif self.dissimilarity == "euclidean":
self.dissimilarity_matrix_ = euclidean_distances(X)
else:
raise ValueError("Proximity must be 'precomputed' or 'euclidean'."
" Got %s instead" % str(self.dissimilarity))
self.embedding_, self.stress_, self.n_iter_ = smacof_p(
self.dissimilarity_matrix_, self.n_uq, metric=self.metric,
n_components=self.n_components, init=init, n_init=self.n_init,
n_jobs=self.n_jobs, max_iter=self.max_iter, verbose=self.verbose,
eps=self.eps, random_state=self.random_state,
return_n_iter=True)
return self.embedding_
|
Fit the data from X, and returns the embedded coordinates
Parameters
----------
X : array, shape=[n_samples, n_features], or [n_samples, n_samples] \
if dissimilarity='precomputed'
Input data.
init : {None or ndarray, shape (n_samples,)}, optional
If None, randomly chooses the initial configuration
if ndarray, initialize the SMACOF algorithm with this array.
| null | null | null |
|
if (seed is None) or (isinstance(seed, int)):
return np.random.RandomState(seed)
elif isinstance(seed, np.random.RandomState):
return seed
raise ValueError("%r can not be used to generate numpy.random.RandomState"
" instance" % seed)
|
def seed_random_state(seed)
|
Turn seed into np.random.RandomState instance
| 2.603577 | 2.217435 | 1.174139 |
return np.mean(cost_matrix[list(y), list(yhat)])
|
def calc_cost(y, yhat, cost_matrix)
|
Calculate the cost with given cost matrix
y : ground truth
yhat : estimation
cost_matrix : array-like, shape=(n_classes, n_classes)
The ith row, jth column represents the cost of the ground truth being
ith class and prediction as jth class.
| 3.98221 | 7.614255 | 0.522994 |
dataset = self.dataset
self.model.train(dataset)
unlabeled_entry_ids, X_pool = zip(*dataset.get_unlabeled_entries())
if isinstance(self.model, ProbabilisticModel):
dvalue = self.model.predict_proba(X_pool)
elif isinstance(self.model, ContinuousModel):
dvalue = self.model.predict_real(X_pool)
if self.method == 'lc': # least confident
score = -np.max(dvalue, axis=1)
elif self.method == 'sm': # smallest margin
if np.shape(dvalue)[1] > 2:
# Find 2 largest decision values
dvalue = -(np.partition(-dvalue, 2, axis=1)[:, :2])
score = -np.abs(dvalue[:, 0] - dvalue[:, 1])
elif self.method == 'entropy':
score = np.sum(-dvalue * np.log(dvalue), axis=1)
ask_id = np.argmax(score)
if return_score:
return unlabeled_entry_ids[ask_id], \
list(zip(unlabeled_entry_ids, score))
else:
return unlabeled_entry_ids[ask_id]
|
def make_query(self, return_score=False)
|
Return the index of the sample to be queried and labeled and
selection score of each sample. Read-only.
No modification to the internal states.
Returns
-------
ask_id : int
The index of the next unlabeled sample to be queried and labeled.
score : list of (index, score) tuple
Selection score of unlabled entries, the larger the better.
| 3.164944 | 3.061051 | 1.03394 |
ret = []
for candidate in votes:
ret.append(0.0)
lab_count = {}
for lab in candidate:
lab_count[lab] = lab_count.setdefault(lab, 0) + 1
# Using vote entropy to measure disagreement
for lab in lab_count.keys():
ret[-1] -= lab_count[lab] / self.n_students * \
math.log(float(lab_count[lab]) / self.n_students)
return ret
|
def _vote_disagreement(self, votes)
|
Return the disagreement measurement of the given number of votes.
It uses the vote vote to measure the disagreement.
Parameters
----------
votes : list of int, shape==(n_samples, n_students)
The predictions that each student gives to each sample.
Returns
-------
disagreement : list of float, shape=(n_samples)
The vote entropy of the given votes.
| 3.567094 | 3.194644 | 1.116586 |
n_students = np.shape(proba)[1]
consensus = np.mean(proba, axis=1) # shape=(n_samples, n_class)
# average probability of each class across all students
consensus = np.tile(consensus, (n_students, 1, 1)).transpose(1, 0, 2)
kl = np.sum(proba * np.log(proba / consensus), axis=2)
return np.mean(kl, axis=1)
|
def _kl_divergence_disagreement(self, proba)
|
Calculate the Kullback-Leibler (KL) divergence disaagreement measure.
Parameters
----------
proba : array-like, shape=(n_samples, n_students, n_class)
Returns
-------
disagreement : list of float, shape=(n_samples)
The kl_divergence of the given probability.
| 3.172951 | 3.093796 | 1.025585 |
labeled_entries = self.dataset.get_labeled_entries()
samples = [labeled_entries[
self.random_state_.randint(0, len(labeled_entries))
]for _ in range(sample_size)]
return Dataset(*zip(*samples))
|
def _labeled_uniform_sample(self, sample_size)
|
sample labeled entries uniformly
| 4.984657 | 4.410181 | 1.130261 |
dataset = self.dataset
for student in self.students:
bag = self._labeled_uniform_sample(int(dataset.len_labeled()))
while bag.get_num_of_labels() != dataset.get_num_of_labels():
bag = self._labeled_uniform_sample(int(dataset.len_labeled()))
LOGGER.warning('There is student receiving only one label,'
're-sample the bag.')
student.train(bag)
|
def teach_students(self)
|
Train each model (student) with the labeled data using bootstrap
aggregating (bagging).
| 6.706908 | 6.032181 | 1.111855 |
model = copy.copy(self.model)
model.train(self.dataset)
# reward function: Importance-Weighted-Accuracy (IW-ACC) (tau, f)
reward = 0.
for i in range(len(self.queried_hist_)):
reward += self.W[i] * (
model.predict(
self.dataset.data[
self.queried_hist_[i]][0].reshape(1, -1)
)[0] ==
self.dataset.data[self.queried_hist_[i]][1]
)
reward /= (self.dataset.len_labeled() + self.dataset.len_unlabeled())
reward /= self.T
return reward
|
def calc_reward_fn(self)
|
Calculate the reward value
| 5.289376 | 5.345384 | 0.989522 |
# initial query
if self.query_dist is None:
self.query_dist = self.exp4p_.next(-1, None, None)
else:
self.query_dist = self.exp4p_.next(
self.calc_reward_fn(),
self.queried_hist_[-1],
self.dataset.data[self.queried_hist_[-1]][1]
)
return
|
def calc_query(self)
|
Calculate the sampling query distribution
| 7.247103 | 6.785662 | 1.068002 |
# first run don't have reward, TODO exception on reward == -1 only once
if reward == -1:
return next(self.exp4p_gen)
else:
# TODO exception on reward in [0, 1]
return self.exp4p_gen.send((reward, ask_id, lbl))
|
def next(self, reward, ask_id, lbl)
|
Taking the label and the reward value of last question and returns
the next question to ask.
| 9.57969 | 10.186291 | 0.940449 |
while True:
# TODO probabilistic active learning algorithm
# len(self.unlabeled_invert_id_idx) is the number of unlabeled data
query = np.zeros((self.N, len(self.unlabeled_invert_id_idx)))
if self.uniform_sampler:
query[-1, :] = 1. / len(self.unlabeled_invert_id_idx)
for i, model in enumerate(self.query_strategies_):
query[i][self.unlabeled_invert_id_idx[model.make_query()]] = 1
# choice vector, shape = (self.K, )
W = np.sum(self.w)
p = (1 - self.K * self.pmin) * self.w / W + self.pmin
# query vector, shape= = (self.n_unlabeled, )
query_vector = np.dot(p, query)
reward, ask_id, _ = yield query_vector
ask_idx = self.unlabeled_invert_id_idx[ask_id]
rhat = reward * query[:, ask_idx] / query_vector[ask_idx]
# The original advice vector in Exp4.P in ALBL is a identity matrix
yhat = rhat
vhat = 1 / p
self.w = self.w * np.exp(
self.pmin / 2 * (
yhat + vhat * np.sqrt(
np.log(self.N / self.delta) / self.K / self.T
)
)
)
raise StopIteration
|
def exp4p(self)
|
The generator which implements the main part of Exp4.P.
Parameters
----------
reward: float
The reward value calculated from ALBL.
ask_id: integer
The entry_id of the sample point ALBL asked.
lbl: integer
The answer received from asking the entry_id ask_id.
Yields
------
q: array-like, shape = [K]
The query vector which tells ALBL what kind of distribution if
should sample from the unlabeled pool.
| 6.138509 | 5.350557 | 1.147265 |
from sklearn.datasets import load_svmlight_file
X, y = load_svmlight_file(filename)
return Dataset(X.toarray().tolist(), y.tolist())
|
def import_libsvm_sparse(filename)
|
Imports dataset file in libsvm sparse format
| 2.291934 | 2.381439 | 0.962415 |
self.data.append((feature, label))
self.modified = True
return len(self.data) - 1
|
def append(self, feature, label=None)
|
Add a (feature, label) entry into the dataset.
A None label indicates an unlabeled entry.
Parameters
----------
feature : {array-like}, shape = (n_features)
Feature of the sample to append to dataset.
label : {int, None}
Label of the sample to append to dataset. None if unlabeled.
Returns
-------
entry_id : {int}
entry_id for the appened sample.
| 3.81519 | 5.6489 | 0.675386 |
self.data[entry_id] = (self.data[entry_id][0], new_label)
self.modified = True
for callback in self._update_callback:
callback(entry_id, new_label)
|
def update(self, entry_id, new_label)
|
Updates an entry with entry_id with the given label
Parameters
----------
entry_id : int
entry id of the sample to update.
label : {int, None}
Label of the sample to be update.
| 2.896252 | 3.566644 | 0.812039 |
X, y = zip(*self.get_labeled_entries())
return np.array(X), np.array(y)
|
def format_sklearn(self)
|
Returns dataset in (X, y) format for use in scikit-learn.
Unlabeled entries are ignored.
Returns
-------
X : numpy array, shape = (n_samples, n_features)
Sample feature set.
y : numpy array, shape = (n_samples)
Sample labels.
| 6.053194 | 4.777668 | 1.266977 |
return [
(idx, entry[0]) for idx, entry in enumerate(self.data)
if entry[1] is None
]
|
def get_unlabeled_entries(self)
|
Returns list of unlabeled features, along with their entry_ids
Returns
-------
unlabeled_entries : list of (entry_id, feature) tuple
Labeled entries
| 4.681275 | 5.753983 | 0.813571 |
if replace:
samples = [
random.choice(self.get_labeled_entries())
for _ in range(sample_size)
]
else:
samples = random.sample(self.get_labeled_entries(), sample_size)
return Dataset(*zip(*samples))
|
def labeled_uniform_sample(self, sample_size, replace=True)
|
Returns a Dataset object with labeled data only, which is
resampled uniformly with given sample size.
Parameter `replace` decides whether sampling with replacement or not.
Parameters
----------
sample_size
| 2.9887 | 3.332221 | 0.896909 |
''' Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise.
'''
num_consumed_args = _num_consumed_args.get(action, 0)
if action.nargs in [OPTIONAL, ZERO_OR_MORE, REMAINDER]:
return True
if action.nargs == ONE_OR_MORE:
return num_consumed_args >= 1
if action.nargs == PARSER:
# Not sure what this should be, but this previously always returned False
# so at least this won't break anything that wasn't already broken.
return False
if action.nargs is None:
return num_consumed_args == 1
assert isinstance(action.nargs, int), 'failed to handle a possible nargs value: %r' % action.nargs
return num_consumed_args == action.nargs
|
def action_is_satisfied(action)
|
Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise.
| 5.037715 | 3.92449 | 1.283661 |
''' Returns True if action will necessarily consume the next argument.
isoptional indicates whether the argument is an optional (starts with -).
'''
num_consumed_args = _num_consumed_args.get(action, 0)
if action.option_strings:
if not isoptional and not action_is_satisfied(action):
return True
return action.nargs == REMAINDER
else:
return action.nargs == REMAINDER and num_consumed_args >= 1
|
def action_is_greedy(action, isoptional=False)
|
Returns True if action will necessarily consume the next argument.
isoptional indicates whether the argument is an optional (starts with -).
| 6.678809 | 3.698914 | 1.805613 |
"Push a token onto the stack popped by the get_token method"
if self.debug >= 1:
print("shlex: pushing token " + repr(tok))
self.pushback.appendleft(tok)
|
def push_token(self, tok)
|
Push a token onto the stack popped by the get_token method
| 7.660406 | 5.763319 | 1.329166 |
"Pop the input source stack."
self.instream.close()
(self.infile, self.instream, self.lineno) = self.filestack.popleft()
if self.debug:
print('shlex: popping to %s, line %d' \
% (self.instream, self.lineno))
self.state = ' '
|
def pop_source(self)
|
Pop the input source stack.
| 7.297515 | 6.707995 | 1.087883 |
self.active_parsers = []
self.visited_positionals = []
completer = self
def patch(parser):
completer.visited_positionals.append(parser)
completer.active_parsers.append(parser)
if isinstance(parser, IntrospectiveArgumentParser):
return
classname = "MonkeyPatchedIntrospectiveArgumentParser"
if USING_PYTHON2:
classname = bytes(classname)
parser.__class__ = type(classname, (IntrospectiveArgumentParser, parser.__class__), {})
for action in parser._actions:
if hasattr(action, "_orig_class"):
continue
# TODO: accomplish this with super
class IntrospectAction(action.__class__):
def __call__(self, parser, namespace, values, option_string=None):
debug("Action stub called on", self)
debug("\targs:", parser, namespace, values, option_string)
debug("\torig class:", self._orig_class)
debug("\torig callable:", self._orig_callable)
if not completer.completing:
self._orig_callable(parser, namespace, values, option_string=option_string)
elif issubclass(self._orig_class, argparse._SubParsersAction):
debug("orig class is a subparsers action: patching and running it")
patch(self._name_parser_map[values[0]])
self._orig_callable(parser, namespace, values, option_string=option_string)
elif self._orig_class in safe_actions:
if not self.option_strings:
completer.visited_positionals.append(self)
self._orig_callable(parser, namespace, values, option_string=option_string)
action._orig_class = action.__class__
action._orig_callable = action.__call__
action.__class__ = IntrospectAction
patch(self._parser)
debug("Active parsers:", self.active_parsers)
debug("Visited positionals:", self.visited_positionals)
return self.active_parsers
|
def _patch_argument_parser(self)
|
Since argparse doesn't support much introspection, we monkey-patch it to replace the parse_known_args method and
all actions with hooks that tell us which action was last taken or about to be taken, and let us have the parser
figure out which subparsers need to be activated (then recursively monkey-patch those).
We save all active ArgumentParsers to extract all their possible option names later.
| 3.237893 | 3.142784 | 1.030263 |
completions = []
debug("all active parsers:", active_parsers)
active_parser = active_parsers[-1]
debug("active_parser:", active_parser)
if self.always_complete_options or (len(cword_prefix) > 0 and cword_prefix[0] in active_parser.prefix_chars):
completions += self._get_option_completions(active_parser, cword_prefix)
debug("optional options:", completions)
next_positional = self._get_next_positional()
debug("next_positional:", next_positional)
if isinstance(next_positional, argparse._SubParsersAction):
completions += self._get_subparser_completions(next_positional, cword_prefix)
completions = self._complete_active_option(active_parser, next_positional, cword_prefix, parsed_args,
completions)
debug("active options:", completions)
debug("display completions:", self._display_completions)
return completions
|
def collect_completions(self, active_parsers, parsed_args, cword_prefix, debug)
|
Visits the active parsers and their actions, executes their completers or introspects them to collect their
option strings. Returns the resulting completions as a list of strings.
This method is exposed for overriding in subclasses; there is no need to use it directly.
| 3.063665 | 3.114636 | 0.983635 |
active_parser = self.active_parsers[-1]
last_positional = self.visited_positionals[-1]
all_positionals = active_parser._get_positional_actions()
if not all_positionals:
return None
if active_parser == last_positional:
return all_positionals[0]
i = 0
for i in range(len(all_positionals)):
if all_positionals[i] == last_positional:
break
if i + 1 < len(all_positionals):
return all_positionals[i + 1]
return None
|
def _get_next_positional(self)
|
Get the next positional action if it exists.
| 2.707493 | 2.518297 | 1.075129 |
# On Python 2, we have to make sure all completions are unicode objects before we continue and output them.
# Otherwise, because python disobeys the system locale encoding and uses ascii as the default encoding, it will
# try to implicitly decode string objects using ascii, and fail.
completions = [ensure_str(c) for c in completions]
# De-duplicate completions and remove excluded ones
if self.exclude is None:
self.exclude = set()
seen = set(self.exclude)
return [c for c in completions if c not in seen and not seen.add(c)]
|
def filter_completions(self, completions)
|
Ensures collected completions are Unicode text, de-duplicates them, and excludes those specified by ``exclude``.
Returns the filtered completions as an iterable.
This method is exposed for overriding in subclasses; there is no need to use it directly.
| 7.140364 | 6.090218 | 1.172432 |
special_chars = "\\"
# If the word under the cursor was quoted, escape the quote char.
# Otherwise, escape all special characters and specially handle all COMP_WORDBREAKS chars.
if cword_prequote == "":
# Bash mangles completions which contain characters in COMP_WORDBREAKS.
# This workaround has the same effect as __ltrim_colon_completions in bash_completion
# (extended to characters other than the colon).
if last_wordbreak_pos:
completions = [c[last_wordbreak_pos + 1:] for c in completions]
special_chars += "();<>|&!`$* \t\n\"'"
elif cword_prequote == '"':
special_chars += '"`$!'
if os.environ.get("_ARGCOMPLETE_SHELL") == "tcsh":
# tcsh escapes special characters itself.
special_chars = ""
elif cword_prequote == "'":
# Nothing can be escaped in single quotes, so we need to close
# the string, escape the single quote, then open a new string.
special_chars = ""
completions = [c.replace("'", r"'\''") for c in completions]
for char in special_chars:
completions = [c.replace(char, "\\" + char) for c in completions]
if self.append_space:
# Similar functionality in bash was previously turned off by supplying the "-o nospace" option to complete.
# Now it is conditionally disabled using "compopt -o nospace" if the match ends in a continuation character.
# This code is retained for environments where this isn't done natively.
continuation_chars = "=/:"
if len(completions) == 1 and completions[0][-1] not in continuation_chars:
if cword_prequote == "":
completions[0] += " "
return completions
|
def quote_completions(self, completions, cword_prequote, last_wordbreak_pos)
|
If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes
occurrences of that quote character in the completions, and adds the quote to the beginning of each completion.
Otherwise, escapes all characters that bash splits words on (``COMP_WORDBREAKS``), and removes portions of
completions before the first colon if (``COMP_WORDBREAKS``) contains a colon.
If there is only one completion, and it doesn't end with a **continuation character** (``/``, ``:``, or ``=``),
adds a space after the completion.
This method is exposed for overriding in subclasses; there is no need to use it directly.
| 6.748539 | 6.134274 | 1.100137 |
if state == 0:
cword_prequote, cword_prefix, cword_suffix, comp_words, first_colon_pos = split_line(text)
comp_words.insert(0, sys.argv[0])
matches = self._get_completions(comp_words, cword_prefix, cword_prequote, first_colon_pos)
self._rl_matches = [text + match[len(cword_prefix):] for match in matches]
if state < len(self._rl_matches):
return self._rl_matches[state]
else:
return None
|
def rl_complete(self, text, state)
|
Alternate entry point for using the argcomplete completer in a readline-based REPL. See also
`rlcompleter <https://docs.python.org/2/library/rlcompleter.html#completer-objects>`_.
Usage:
.. code-block:: python
import argcomplete, argparse, readline
parser = argparse.ArgumentParser()
...
completer = argcomplete.CompletionFinder(parser)
readline.set_completer_delims("")
readline.set_completer(completer.rl_complete)
readline.parse_and_bind("tab: complete")
result = input("prompt> ")
(Use ``raw_input`` instead of ``input`` on Python 2, or use `eight <https://github.com/kislyuk/eight>`_).
| 3.980925 | 4.014974 | 0.991519 |
'''
Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_defaults: Whether to fallback to readline's default completion when no matches are generated.
:param str shell: Name of the shell to output code for (bash or tcsh)
:param complete_arguments: Arguments to call complete with
:type complete_arguments: list(str) or None
'''
if complete_arguments is None:
complete_options = '-o nospace -o default' if use_defaults else '-o nospace'
else:
complete_options = " ".join(complete_arguments)
if shell == 'bash':
quoted_executables = [quote(i) for i in executables]
executables_list = " ".join(quoted_executables)
code = bashcode % dict(complete_opts=complete_options, executables=executables_list)
else:
code = ""
for executable in executables:
code += tcshcode % dict(executable=executable)
return code
|
def shellcode(executables, use_defaults=True, shell='bash', complete_arguments=None)
|
Provide the shell code required to register a python executable for use with the argcomplete module.
:param str executables: Executables to be completed (when invoked exactly with this name
:param bool use_defaults: Whether to fallback to readline's default completion when no matches are generated.
:param str shell: Name of the shell to output code for (bash or tcsh)
:param complete_arguments: Arguments to call complete with
:type complete_arguments: list(str) or None
| 4.454965 | 1.984803 | 2.244538 |
params = {
'V': SMSPUBLI_API_VERSION,
'UN': SMSPUBLI_USERNAME,
'PWD': SMSPUBLI_PASSWORD,
'R': SMSPUBLI_ROUTE,
'SA': message.from_phone,
'DA': ','.join(message.to),
'M': message.body.encode('latin-1'),
'DC': SMSPUBLI_DC,
'DR': SMSPUBLI_DR,
'UR': message.from_phone
}
if SMSPUBLI_ALLOW_LONG_SMS:
params['LM'] = '1'
response = requests.post(SMSPUBLI_API_URL, params)
if response.status_code != 200:
if not self.fail_silently:
raise
else:
return False
response_msg, response_code = response.content.split(':')
if response_msg == 'OK':
try:
if "," in response_code:
codes = map(int, response_code.split(","))
else:
codes = [int(response_code)]
for code in codes:
if code == -5:
#: TODO send error signal (no $$)
pass
elif code == -3:
#: TODO send error signal (incorrect num)
pass
return True
except (ValueError, TypeError):
if not self.fail_silently:
raise
return False
return False
|
def _send(self, message)
|
Private method for send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sended else False
:rtype: bool
| 3.963265 | 3.904989 | 1.014924 |
if self._fname is None:
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
fname = "%s-%s.log" % (timestamp, abs(id(self)))
self._fname = os.path.join(self.file_path, fname)
return self._fname
|
def _get_filename(self)
|
Return a unique file name.
| 2.765625 | 2.405198 | 1.149853 |
if not SMSGLOBAL_CHECK_BALANCE_COUNTRY:
raise Exception('SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.')
params = {
'user' : self.get_username(),
'password' : self.get_password(),
'country' : SMSGLOBAL_CHECK_BALANCE_COUNTRY,
}
req = urllib2.Request(SMSGLOBAL_API_URL_CHECKBALANCE, urllib.urlencode(params))
response = urllib2.urlopen(req).read()
# CREDITS:8658.44;COUNTRY:AU;SMS:3764.54;
if response.startswith('ERROR'):
raise Exception('Error retrieving balance: %s' % response.replace('ERROR:', ''))
return dict([(p.split(':')[0].lower(), p.split(':')[1]) for p in response.split(';') if len(p) > 0])
|
def get_balance(self)
|
Get balance with provider.
| 4.27358 | 4.188765 | 1.020248 |
if not sms_messages:
return
num_sent = 0
for message in sms_messages:
if self._send(message):
num_sent += 1
return num_sent
|
def send_messages(self, sms_messages)
|
Sends one or more SmsMessage objects and returns the number of sms
messages sent.
| 2.728685 | 2.894152 | 0.942827 |
charset='UTF-8'
params = {
'action' : 'sendsms',
'user' : self.get_username(),
'password' : self.get_password(),
'from' : message.from_phone,
'to' : ",".join(message.to),
'text' : message.body,
'clientcharset' : charset,
'detectcharset' : 1,
'maxsplit': int(math.ceil(len(message.body) / 160))
}
req = urllib2.Request(SMSGLOBAL_API_URL_SENDSMS, urllib.urlencode(params))
result_page = urllib2.urlopen(req).read()
results = self._parse_response(result_page)
if results is None:
if not self.fail_silently:
raise Exception("Error determining response: [" + result_page + "]")
return False
code, sendqmsgid, msgid = results
if code != '0':
if not self.fail_silently:
raise Exception("Error sending sms: [%s], extracted results(code, sendqmsgid, msgid): [%s]" % (result_page, results))
return False
else:
logger.info('SENT to: %s; sender: %s; code: %s; sendqmsgid: %s; msgid: %s; message: %s' % (
message.to,
message.from_phone,
code,
sendqmsgid,
msgid,
message.body
))
return True
|
def _send(self, message)
|
A helper method that does the actual sending.
| 3.468219 | 3.41533 | 1.015486 |
# Sample result_page, single line -> "OK: 0; Sent queued message ID: 2063619577732703 SMSGlobalMsgID:6171799108850954"
resultline = result_page.splitlines()[0] # get result line
if resultline.startswith('ERROR:'):
raise Exception(resultline.replace('ERROR: ', ''))
patt = re.compile(r'^.+?:\s*(.+?)\s*;\s*Sent queued message ID:\s*(.+?)\s*SMSGlobalMsgID:(.+?)$', re.IGNORECASE)
m = patt.match(resultline)
if m:
return (m.group(1), m.group(2), m.group(3))
return None
|
def _parse_response(self, result_page)
|
Takes a result page of sending the sms, returns an extracted tuple:
('numeric_err_code', '<sent_queued_message_id>', '<smsglobalmsgid>')
Returns None if unable to extract info from result_page, it should be
safe to assume that it was either a failed result or worse, the interface
contract has changed.
| 5.803047 | 4.592879 | 1.263488 |
from sendsms.message import SmsMessage
connection = connection or get_connection(
username = auth_user,
password = auth_password,
fail_silently = fail_silently
)
return SmsMessage(body=body, from_phone=from_phone, to=to, \
flash=flash, connection=connection).send()
|
def send_sms(body, from_phone, to, flash=False, fail_silently=False,
auth_user=None, auth_password=None, connection=None)
|
Easy wrapper for send a single SMS to a recipient list.
:returns: the number of SMSs sent.
| 2.625983 | 3.826575 | 0.686249 |
from sendsms.message import SmsMessage
connection = connection or get_connection(
username = auth_user,
password = auth_password,
fail_silently = fail_silently
)
messages = [SmsMessage(message=message, from_phone=from_phone, to=to, flash=flash)
for message, from_phone, to, flash in datatuple]
connection.send_messages(messages)
|
def send_mass_sms(datatuple, fail_silently=False,
auth_user=None, auth_password=None, connection=None)
|
Given a datatuple of (message, from_phone, to, flash), sends each message to each
recipient list.
:returns: the number of SMSs sent.
| 2.78578 | 2.563744 | 1.086606 |
path = path or getattr(settings, 'SENDSMS_BACKEND', 'sendsms.backends.locmem.SmsBackend')
try:
mod_name, klass_name = path.rsplit('.', 1)
mod = import_module(mod_name)
except AttributeError as e:
raise ImproperlyConfigured(u'Error importing sms backend module %s: "%s"' % (mod_name, e))
try:
klass = getattr(mod, klass_name)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a "%s" class' % (mod_name, klass_name))
return klass(fail_silently=fail_silently, **kwargs)
|
def get_connection(path=None, fail_silently=False, **kwargs)
|
Load an sms backend and return an instance of it.
:param string path: backend python path. Default: sendsms.backends.console.SmsBackend
:param bool fail_silently: Flag to not throw exceptions on error. Default: False
:returns: backend class instance.
:rtype: :py:class:`~sendsms.backends.base.BaseSmsBackend` subclass
| 2.058221 | 1.894062 | 1.086671 |
self.client = SmsGateApi(getattr(settings, 'SMS_SLUZBA_API_LOGIN', ''),
getattr(settings, 'SMS_SLUZBA_API_PASSWORD', ''),
getattr(settings, 'SMS_SLUZBA_API_TIMEOUT', 2),
getattr(settings, 'SMS_SLUZBA_API_USE_SSL', True))
|
def open(self)
|
Initializes sms.sluzba.cz API library.
| 3.942961 | 2.687036 | 1.467402 |
count = 0
for message in messages:
message_body = unicodedata.normalize('NFKD', unicode(message.body)).encode('ascii', 'ignore')
for tel_number in message.to:
try:
self.client.send(tel_number, message_body, getattr(settings, 'SMS_SLUZBA_API_USE_POST', True))
except Exception:
if self.fail_silently:
log.exception('Error while sending sms via sms.sluzba.cz backend API.')
else:
raise
else:
count += 1
return count
|
def send_messages(self, messages)
|
Sending SMS messages via sms.sluzba.cz API.
Note:
This method returns number of actually sent sms messages
not number of SmsMessage instances processed.
:param messages: list of sms messages
:type messages: list of sendsms.message.SmsMessage instances
:returns: number of sent sms messages
:rtype: int
| 4.29078 | 3.35094 | 1.280471 |
if not messages:
return
self._lock.acquire()
try:
# The try-except is nested to allow for
# Python 2.4 support (Refs #12147)
try:
stream_created = self.open()
for message in messages:
self.stream.write(render_message(message))
self.stream.write('\n')
self.stream.write('-'*79)
self.stream.write('\n')
self.stream.flush() # flush after each message
if stream_created:
self.close()
except:
if not self.fail_silently:
raise
finally:
self._lock.release()
return len(messages)
|
def send_messages(self, messages)
|
Write all messages to the stream in a thread-safe way.
| 3.975415 | 3.682756 | 1.079467 |
response_dict = {}
for line in response.splitlines():
key, value = response.split("=", 1)
response_dict[key] = value
return response_dict
|
def _parse_response(self, response)
|
Parse http raw respone into python
dictionary object.
:param str response: http response
:returns: response dict
:rtype: dict
| 3.687561 | 3.264046 | 1.129751 |
params = {
'EsendexUsername': self.get_username(),
'EsendexPassword': self.get_password(),
'EsendexAccount': self.get_account(),
'EsendexOriginator': message.from_phone,
'EsendexRecipient': ",".join(message.to),
'EsendexBody': message.body,
'EsendexPlainText':'1'
}
if ESENDEX_SANDBOX:
params['EsendexTest'] = '1'
response = requests.post(ESENDEX_API_URL, params)
if response.status_code != 200:
if not self.fail_silently:
raise Exception('Bad status code')
else:
return False
if not response.content.startswith(b'Result'):
if not self.fail_silently:
raise Exception('Bad result')
else:
return False
response = self._parse_response(response.content.decode('utf8'))
if ESENDEX_SANDBOX and response['Result'] == 'Test':
return True
else:
if response['Result'].startswith('OK'):
return True
else:
if not self.fail_silently:
raise Exception('Bad result')
return False
|
def _send(self, message)
|
Private method to send one message.
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool
| 3.046465 | 2.959503 | 1.029384 |
if '.' not in import_path:
raise TypeError(
"'import_path' argument to 'load_object' must "
"contain at least one dot."
)
module_name, object_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, object_name)
|
def load_object(import_path)
|
Shamelessly stolen from https://github.com/ojii/django-load
Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
likes.
Import paths should be: "mypackage.mymodule.MyObject". It then imports the
module up until the last dot and tries to get the attribute after that dot
from the imported module.
If the import path does not contain any dots, a TypeError is raised.
If the module cannot be imported, an ImportError is raised.
If the attribute does not exist in the module, a AttributeError is raised.
| 2.226087 | 2.403814 | 0.926065 |
if not self.to:
# Don't bother creating the connection if there's nobody to send to
return 0
res = self.get_connection(fail_silently).send_messages([self])
sms_post_send.send(sender=self, to=self.to, from_phone=self.from_phone, body=self.body)
return res
|
def send(self, fail_silently=False)
|
Sends the sms message
| 4.40159 | 4.280941 | 1.028183 |
params = {
'from': message.from_phone,
'to': ",".join(message.to),
'text': message.body,
'api_key': self.get_api_key(),
'api_secret': self.get_api_secret(),
}
print(params)
logger.debug("POST to %r with body: %r", NEXMO_API_URL, params)
return self.parse(NEXMO_API_URL, requests.post(NEXMO_API_URL, data=params))
|
def _send(self, message)
|
A helper method that does the actual sending
:param SmsMessage message: SmsMessage class instance.
:returns: True if message is sent else False
:rtype: bool
| 3.884158 | 3.704304 | 1.048553 |
counter = 0
for message in messages:
res, _ = self._send(message)
if res:
counter += 1
return counter
|
def send_messages(self, messages)
|
Send messages.
:param list messages: List of SmsMessage instances.
:returns: number of messages sended successful.
:rtype: int
| 4.285751 | 4.568785 | 0.938051 |
if not options:
options = {}
if self.api_version not in path_dict:
raise Exception('method call not available under API version {}'.format(self.api_version))
request_url = BASE_URL_V2_0 if self.api_version == API_V2_0 else BASE_URL_V1_1
request_url = request_url.format(path=path_dict[self.api_version])
nonce = str(int(time.time() * 1000))
if protection != PROTECTION_PUB:
request_url = "{0}apikey={1}&nonce={2}&".format(request_url, self.api_key, nonce)
request_url += urlencode(options)
try:
if sys.version_info >= (3, 0) and protection != PROTECTION_PUB:
apisign = hmac.new(bytearray(self.api_secret, 'ascii'),
bytearray(request_url, 'ascii'),
hashlib.sha512).hexdigest()
else:
apisign = hmac.new(self.api_secret.encode(),
request_url.encode(),
hashlib.sha512).hexdigest()
self.wait()
return self.dispatch(request_url, apisign)
except Exception:
return {
'success': False,
'message': 'NO_API_RESPONSE',
'result': None
}
|
def _api_query(self, protection=None, path_dict=None, options=None)
|
Queries Bittrex
:param request_url: fully-formed URL to request
:type options: dict
:return: JSON response from Bittrex
:rtype : dict
| 2.751312 | 2.729433 | 1.008016 |
return self._api_query(path_dict={
API_V1_1: '/public/getmarketsummary',
API_V2_0: '/pub/Market/GetMarketSummary'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB)
|
def get_market_summary(self, market)
|
Used to get the last 24 hour summary of all active
exchanges in specific coin
Endpoint:
1.1 /public/getmarketsummary
2.0 /pub/Market/GetMarketSummary
:param market: String literal for the market(ex: BTC-XRP)
:type market: str
:return: Summaries of active exchanges of a coin in JSON
:rtype : dict
| 7.111793 | 5.811693 | 1.223704 |
return self._api_query(path_dict={
API_V1_1: '/public/getorderbook',
API_V2_0: '/pub/Market/GetMarketOrderBook'
}, options={'market': market, 'marketname': market, 'type': depth_type}, protection=PROTECTION_PUB)
|
def get_orderbook(self, market, depth_type=BOTH_ORDERBOOK)
|
Used to get retrieve the orderbook for a given market.
The depth_type parameter is IGNORED under v2.0 and both orderbooks are always returned
Endpoint:
1.1 /public/getorderbook
2.0 /pub/Market/GetMarketOrderBook
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param depth_type: buy, sell or both to identify the type of
orderbook to return.
Use constants BUY_ORDERBOOK, SELL_ORDERBOOK, BOTH_ORDERBOOK
:type depth_type: str
:return: Orderbook of market in JSON
:rtype : dict
| 6.947748 | 5.091065 | 1.364694 |
return self._api_query(path_dict={
API_V1_1: '/public/getmarkethistory',
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PUB)
|
def get_market_history(self, market)
|
Used to retrieve the latest trades that have occurred for a
specific market.
Endpoint:
1.1 /market/getmarkethistory
2.0 NO Equivalent
Example ::
{'success': True,
'message': '',
'result': [ {'Id': 5625015,
'TimeStamp': '2017-08-31T01:29:50.427',
'Quantity': 7.31008193,
'Price': 0.00177639,
'Total': 0.01298555,
'FillType': 'FILL',
'OrderType': 'BUY'},
...
]
}
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:return: Market history in JSON
:rtype : dict
| 10.875722 | 11.527325 | 0.943473 |
return self._api_query(path_dict={
API_V1_1: '/market/buylimit',
}, options={'market': market,
'quantity': quantity,
'rate': rate}, protection=PROTECTION_PRV)
|
def buy_limit(self, market, quantity, rate)
|
Used to place a buy order in a specific market. Use buylimit to place
limit orders Make sure you have the proper permissions set on your
API keys for this call to work
Endpoint:
1.1 /market/buylimit
2.0 NO Direct equivalent. Use trade_buy for LIMIT and MARKET buys
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param quantity: The amount to purchase
:type quantity: float
:param rate: The rate at which to place the order.
This is not needed for market orders
:type rate: float
:return:
:rtype : dict
| 8.950755 | 8.139032 | 1.099732 |
return self._api_query(path_dict={
API_V1_1: '/market/getopenorders',
API_V2_0: '/key/market/getopenorders'
}, options={'market': market, 'marketname': market} if market else None, protection=PROTECTION_PRV)
|
def get_open_orders(self, market=None)
|
Get all orders that you currently have opened.
A specific market can be requested.
Endpoint:
1.1 /market/getopenorders
2.0 /key/market/getopenorders
:param market: String literal for the market (ie. BTC-LTC)
:type market: str
:return: Open orders info in JSON
:rtype : dict
| 7.812674 | 6.093313 | 1.282172 |
return self._api_query(path_dict={
API_V1_1: '/account/getdepositaddress',
API_V2_0: '/key/balance/getdepositaddress'
}, options={'currency': currency, 'currencyname': currency}, protection=PROTECTION_PRV)
|
def get_deposit_address(self, currency)
|
Used to generate or retrieve an address for a specific currency
Endpoint:
1.1 /account/getdepositaddress
2.0 /key/balance/getdepositaddress
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: Address info in JSON
:rtype : dict
| 8.807233 | 6.165888 | 1.42838 |
options = {
'currency': currency,
'quantity': quantity,
'address': address
}
if paymentid:
options['paymentid'] = paymentid
return self._api_query(path_dict={
API_V1_1: '/account/withdraw',
API_V2_0: '/key/balance/withdrawcurrency'
}, options=options, protection=PROTECTION_PRV)
|
def withdraw(self, currency, quantity, address, paymentid=None)
|
Used to withdraw funds from your account
Endpoint:
1.1 /account/withdraw
2.0 /key/balance/withdrawcurrency
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:param quantity: The quantity of coins to withdraw
:type quantity: float
:param address: The address where to send the funds.
:type address: str
:param paymentid: Optional argument for memos, tags, or other supplemental information for cryptos such as XRP.
:type paymentid: str
:return:
:rtype : dict
| 4.610993 | 3.579692 | 1.288098 |
if market:
return self._api_query(path_dict={
API_V1_1: '/account/getorderhistory',
API_V2_0: '/key/market/GetOrderHistory'
}, options={'market': market, 'marketname': market}, protection=PROTECTION_PRV)
else:
return self._api_query(path_dict={
API_V1_1: '/account/getorderhistory',
API_V2_0: '/key/orders/getorderhistory'
}, protection=PROTECTION_PRV)
|
def get_order_history(self, market=None)
|
Used to retrieve order trade history of account
Endpoint:
1.1 /account/getorderhistory
2.0 /key/orders/getorderhistory or /key/market/GetOrderHistory
:param market: optional a string literal for the market (ie. BTC-LTC).
If omitted, will return for all markets
:type market: str
:return: order history in JSON
:rtype : dict
| 3.677668 | 2.714046 | 1.35505 |
return self._api_query(path_dict={
API_V1_1: '/account/getorder',
API_V2_0: '/key/orders/getorder'
}, options={'uuid': uuid, 'orderid': uuid}, protection=PROTECTION_PRV)
|
def get_order(self, uuid)
|
Used to get details of buy or sell order
Endpoint:
1.1 /account/getorder
2.0 /key/orders/getorder
:param uuid: uuid of buy or sell order
:type uuid: str
:return:
:rtype : dict
| 9.532585 | 6.282418 | 1.517343 |
return [market['MarketName'] for market in self.get_markets()['result']
if market['MarketName'].lower().endswith(currency.lower())]
|
def list_markets_by_currency(self, currency)
|
Helper function to see which markets exist for a currency.
Endpoint: /public/getmarkets
Example ::
>>> Bittrex(None, None).list_markets_by_currency('LTC')
['BTC-LTC', 'ETH-LTC', 'USDT-LTC']
:param currency: String literal for the currency (ex: LTC)
:type currency: str
:return: List of markets that the currency appears in
:rtype: list
| 4.329244 | 4.870522 | 0.888866 |
return self._api_query(path_dict={
API_V2_0: '/key/balance/getpendingwithdrawals'
}, options={'currencyname': currency} if currency else None,
protection=PROTECTION_PRV)
|
def get_pending_withdrawals(self, currency=None)
|
Used to view your pending withdrawals
Endpoint:
1.1 NO EQUIVALENT
2.0 /key/balance/getpendingwithdrawals
:param currency: String literal for the currency (ie. BTC)
:type currency: str
:return: pending withdrawals in JSON
:rtype : list
| 16.775038 | 13.029964 | 1.28742 |
return self._api_query(path_dict={
API_V2_0: '/key/market/tradesell'
}, options={
'marketname': market,
'ordertype': order_type,
'quantity': quantity,
'rate': rate,
'timeInEffect': time_in_effect,
'conditiontype': condition_type,
'target': target
}, protection=PROTECTION_PRV)
|
def trade_sell(self, market=None, order_type=None, quantity=None, rate=None, time_in_effect=None,
condition_type=None, target=0.0)
|
Enter a sell order into the book
Endpoint
1.1 NO EQUIVALENT -- see sell_market or sell_limit
2.0 /key/market/tradesell
:param market: String literal for the market (ex: BTC-LTC)
:type market: str
:param order_type: ORDERTYPE_LIMIT = 'LIMIT' or ORDERTYPE_MARKET = 'MARKET'
:type order_type: str
:param quantity: The amount to purchase
:type quantity: float
:param rate: The rate at which to place the order.
This is not needed for market orders
:type rate: float
:param time_in_effect: TIMEINEFFECT_GOOD_TIL_CANCELLED = 'GOOD_TIL_CANCELLED',
TIMEINEFFECT_IMMEDIATE_OR_CANCEL = 'IMMEDIATE_OR_CANCEL', or TIMEINEFFECT_FILL_OR_KILL = 'FILL_OR_KILL'
:type time_in_effect: str
:param condition_type: CONDITIONTYPE_NONE = 'NONE', CONDITIONTYPE_GREATER_THAN = 'GREATER_THAN',
CONDITIONTYPE_LESS_THAN = 'LESS_THAN', CONDITIONTYPE_STOP_LOSS_FIXED = 'STOP_LOSS_FIXED',
CONDITIONTYPE_STOP_LOSS_PERCENTAGE = 'STOP_LOSS_PERCENTAGE'
:type condition_type: str
:param target: used in conjunction with condition_type
:type target: float
:return:
| 4.191787 | 3.779781 | 1.109003 |
return self._api_query(path_dict={
API_V2_0: '/pub/market/GetTicks'
}, options={
'marketName': market, 'tickInterval': tick_interval
}, protection=PROTECTION_PUB)
|
def get_candles(self, market, tick_interval)
|
Used to get all tick candles for a market.
Endpoint:
1.1 NO EQUIVALENT
2.0 /pub/market/GetTicks
Example ::
{ success: true,
message: '',
result:
[ { O: 421.20630125,
H: 424.03951276,
L: 421.20630125,
C: 421.20630125,
V: 0.05187504,
T: '2016-04-08T00:00:00',
BV: 21.87921187 },
{ O: 420.206,
H: 420.206,
L: 416.78743422,
C: 416.78743422,
V: 2.42281573,
T: '2016-04-09T00:00:00',
BV: 1012.63286332 }]
}
:return: Available tick candles in JSON
:rtype: dict
| 10.371889 | 7.970278 | 1.301321 |
if extra_context is None:
extra_context = {}
response = self.adv_filters_handle(request,
extra_context=extra_context)
if response:
return response
return super(AdminAdvancedFiltersMixin, self
).changelist_view(request, extra_context=extra_context)
|
def changelist_view(self, request, extra_context=None)
|
Add advanced_filters form to changelist context
| 3.826398 | 3.405147 | 1.12371 |
return self.filter(Q(users=user) | Q(groups__in=user.groups.all()))
|
def filter_by_user(self, user)
|
All filters that should be displayed to a user (by users/group)
| 4.14145 | 3.841561 | 1.078064 |
if not self.b64_query:
return None
s = QSerializer(base64=True)
return s.loads(self.b64_query)
|
def query(self)
|
De-serialize, decode and return an ORM query stored in b64_query.
| 6.761565 | 3.81443 | 1.772628 |
if not isinstance(value, Q):
raise Exception('Must only be passed a Django (Q)uery object')
s = QSerializer(base64=True)
self.b64_query = s.dumps(value)
|
def query(self, value)
|
Serialize an ORM query, Base-64 encode it and set it to
the b64_query field
| 11.627123 | 7.660866 | 1.51773 |
children = []
for child in q.children:
if isinstance(child, Q):
children.append(self.serialize(child))
else:
children.append(child)
serialized = q.__dict__
serialized['children'] = children
return serialized
|
def serialize(self, q)
|
Serialize a Q object into a (possibly nested) dict.
| 2.602676 | 2.163932 | 1.202753 |
children = []
for child in d.pop('children'):
if isinstance(child, dict):
children.append(self.deserialize(child))
else:
children.append(self.prepare_value(child))
query = Q()
query.children = children
query.connector = d['connector']
query.negated = d['negated']
if 'subtree_parents' in d:
query.subtree_parents = d['subtree_parents']
return query
|
def deserialize(self, d)
|
De-serialize a Q object from a (possibly nested) dict.
| 3.022664 | 2.68916 | 1.124018 |
fields = []
children = d.get('children', [])
for child in children:
if isinstance(child, dict):
fields.extend(self.get_field_values_list(child))
else:
f = {'field': child[0], 'value': child[1]}
if self._is_range(child):
f['value_from'] = child[1][0]
f['value_to'] = child[1][1]
f['negate'] = d.get('negated', False)
fields.append(f)
# add _OR line
if d['connector'] == 'OR' and children[-1] != child:
fields.append({'field': '_OR', 'value': 'null'})
return fields
|
def get_field_values_list(self, d)
|
Iterate over a (possibly nested) dict, and return a list
of all children queries, as a dict of the following structure:
{
'field': 'some_field__iexact',
'value': 'some_value',
'value_from': 'optional_range_val1',
'value_to': 'optional_range_val2',
'negate': True,
}
OR relations are expressed as an extra "line" between queries.
| 3.147017 | 2.457589 | 1.28053 |
res = super(VaryingTypeCharField, self).to_python(value)
split_res = res.split(self._default_separator)
if not res or len(split_res) < 2:
return res.strip()
# create a regex string out of the list of choices passed, i.e: (a|b)
res = r"({pattern})".format(pattern="|".join(
map(lambda x: x.strip(), split_res)))
return res
|
def to_python(self, value)
|
Split a string value by separator (default to ",") into a
list; then, returns a regex pattern string that ORs the values
in the resulting list.
>>> field = VaryingTypeCharField()
>>> assert field.to_python('') == ''
>>> assert field.to_python('test') == 'test'
>>> assert field.to_python('and,me') == '(and|me)'
>>> assert field.to_python('and,me;too') == '(and|me;too)'
| 5.838772 | 5.085393 | 1.148146 |
cleaned_data = super(CleanWhiteSpacesMixin, self).clean()
for k in self.cleaned_data:
if isinstance(self.cleaned_data[k], six.string_types):
cleaned_data[k] = re.sub(extra_spaces_pattern, ' ',
self.cleaned_data[k] or '').strip()
return cleaned_data
|
def clean(self)
|
>>> import django.forms
>>> class MyForm(CleanWhiteSpacesMixin, django.forms.Form):
... some_field = django.forms.CharField()
>>>
>>> form = MyForm({'some_field': ' a weird value '})
>>> assert form.is_valid()
>>> assert form.cleaned_data == {'some_field': 'a weird value'}
| 3.395335 | 3.263943 | 1.040256 |
return tuple(sorted(
[(fquery, capfirst(fname)) for fquery, fname in fields.items()],
key=lambda f: f[1].lower())
) + self.FIELD_CHOICES
|
def _build_field_choices(self, fields)
|
Iterate over passed model fields tuple and update initial choices.
| 7.958596 | 7.121741 | 1.117507 |
if self.is_valid() and formdata is None:
formdata = self.cleaned_data
key = "{field}__{operator}".format(**formdata)
if formdata['operator'] == "isnull":
return {key: None}
elif formdata['operator'] == "istrue":
return {formdata['field']: True}
elif formdata['operator'] == "isfalse":
return {formdata['field']: False}
return {key: formdata['value']}
|
def _build_query_dict(self, formdata=None)
|
Take submitted data from form and create a query dict to be
used in a Q object (or filter)
| 2.622666 | 2.57996 | 1.016553 |
operator = 'iexact'
if query_data['field'] == '_OR':
query_data['operator'] = operator
return query_data
parts = query_data['field'].split('__')
if len(parts) < 2:
field = parts[0]
else:
if parts[-1] in dict(AdvancedFilterQueryForm.OPERATORS).keys():
field = '__'.join(parts[:-1])
operator = parts[-1]
else:
field = query_data['field']
query_data['field'] = field
mfield = get_fields_from_path(model, query_data['field'])
if not mfield:
raise Exception('Field path "%s" could not be followed to a field'
' in model %s', query_data['field'], model)
else:
mfield = mfield[-1] # get the field object
if query_data['value'] is None:
query_data['operator'] = "isnull"
elif query_data['value'] is True:
query_data['operator'] = "istrue"
elif query_data['value'] is False:
query_data['operator'] = "isfalse"
else:
if isinstance(mfield, DateField):
# this is a date/datetime field
query_data['operator'] = "range" # default
else:
query_data['operator'] = operator # default
if isinstance(query_data.get('value'),
list) and query_data['operator'] == 'range':
date_from = date_to_string(query_data.get('value_from'))
date_to = date_to_string(query_data.get('value_to'))
query_data['value'] = ','.join([date_from, date_to])
return query_data
|
def _parse_query_dict(query_data, model)
|
Take a list of query field dict and return data for form initialization
| 2.734641 | 2.698817 | 1.013274 |
dtfrom = data.pop('value_from')
dtto = data.pop('value_to')
if dtfrom is dtto is None:
self.errors['value'] = ['Date range requires values']
raise forms.ValidationError([])
data['value'] = (dtfrom, dtto)
|
def set_range_value(self, data)
|
Validates date range by parsing into 2 datetime objects and
validating them both.
| 5.920473 | 5.061445 | 1.16972 |
query = Q() # initial is an empty query
query_dict = self._build_query_dict(self.cleaned_data)
if 'negate' in self.cleaned_data and self.cleaned_data['negate']:
query = query & ~Q(**query_dict)
else:
query = query & Q(**query_dict)
return query
|
def make_query(self, *args, **kwargs)
|
Returns a Q object from the submitted form
| 3.406197 | 3.037163 | 1.121506 |
model_fields = {}
for field in fields:
if isinstance(field, tuple) and len(field) == 2:
field, verbose_name = field[0], field[1]
else:
try:
model_field = get_fields_from_path(model, field)[-1]
verbose_name = model_field.verbose_name
except (FieldDoesNotExist, IndexError, TypeError) as e:
logger.warn("AdvancedFilterForm: skip invalid field "
"- %s", e)
continue
model_fields[field] = verbose_name
return model_fields
|
def get_fields_from_model(self, model, fields)
|
Iterate over given <field> names (in "orm query" notation) and find
the actual field given the initial <model>.
If <field> is a tuple of the format ('field_name', 'Verbose name'),
overwrite the field's verbose name with the given name for display
purposes.
| 3.263205 | 3.382766 | 0.964656 |
query = Q()
ORed = []
for form in self._non_deleted_forms:
if not hasattr(form, 'cleaned_data'):
continue
if form.cleaned_data['field'] == "_OR":
ORed.append(query)
query = Q()
else:
query = query & form.make_query()
if ORed:
if query: # add last query for OR if any
ORed.append(query)
query = reduce(operator.or_, ORed)
return query
|
def generate_query(self)
|
Reduces multiple queries into a single usable query
| 4.206623 | 3.860088 | 1.089774 |
model_fields = self.get_fields_from_model(model, self._filter_fields)
forms = []
if instance:
for field_data in instance.list_fields():
forms.append(
AdvancedFilterQueryForm._parse_query_dict(
field_data, model))
formset = AFQFormSetNoExtra if not extra else AFQFormSet
self.fields_formset = formset(
data=data,
initial=forms or None,
model_fields=model_fields
)
|
def initialize_form(self, instance, model, data=None, extra=None)
|
Takes a "finalized" query and generate it's form data
| 6.210246 | 6.111759 | 1.016114 |
cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY']
redirect_url = create_cas_login_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGIN_ROUTE'],
flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True))
if 'ticket' in flask.request.args:
flask.session[cas_token_session_key] = flask.request.args['ticket']
if cas_token_session_key in flask.session:
if validate(flask.session[cas_token_session_key]):
if 'CAS_AFTER_LOGIN_SESSION_URL' in flask.session:
redirect_url = flask.session.pop('CAS_AFTER_LOGIN_SESSION_URL')
elif flask.request.args.get('origin'):
redirect_url = flask.request.args['origin']
else:
redirect_url = flask.url_for(
current_app.config['CAS_AFTER_LOGIN'])
else:
del flask.session[cas_token_session_key]
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url)
|
def login()
|
This route has two purposes. First, it is used by the user
to login. Second, it is used by the CAS to respond with the
`ticket` after the user logs in successfully.
When the user accesses this url, they are redirected to the CAS
to login. If the login was successful, the CAS will respond to this
route with the ticket in the url. The ticket is then validated.
If validation was successful the logged in username is saved in
the user's session under the key `CAS_USERNAME_SESSION_KEY` and
the user's attributes are saved under the key
'CAS_USERNAME_ATTRIBUTE_KEY'
| 2.38968 | 2.273954 | 1.050892 |
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
if cas_username_session_key in flask.session:
del flask.session[cas_username_session_key]
if cas_attributes_session_key in flask.session:
del flask.session[cas_attributes_session_key]
if(current_app.config['CAS_AFTER_LOGOUT'] is not None):
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'],
current_app.config['CAS_AFTER_LOGOUT'])
else:
redirect_url = create_cas_logout_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_LOGOUT_ROUTE'])
current_app.logger.debug('Redirecting to: {0}'.format(redirect_url))
return flask.redirect(redirect_url)
|
def logout()
|
When the user accesses this route they are logged out.
| 1.831227 | 1.808865 | 1.012363 |
cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY']
cas_attributes_session_key = current_app.config['CAS_ATTRIBUTES_SESSION_KEY']
current_app.logger.debug("validating token {0}".format(ticket))
cas_validate_url = create_cas_validate_url(
current_app.config['CAS_SERVER'],
current_app.config['CAS_VALIDATE_ROUTE'],
flask.url_for('.login', origin=flask.session.get('CAS_AFTER_LOGIN_SESSION_URL'), _external=True),
ticket)
current_app.logger.debug("Making GET request to {0}".format(
cas_validate_url))
xml_from_dict = {}
isValid = False
try:
xmldump = urlopen(cas_validate_url).read().strip().decode('utf8', 'ignore')
xml_from_dict = parse(xmldump)
isValid = True if "cas:authenticationSuccess" in xml_from_dict["cas:serviceResponse"] else False
except ValueError:
current_app.logger.error("CAS returned unexpected result")
if isValid:
current_app.logger.debug("valid")
xml_from_dict = xml_from_dict["cas:serviceResponse"]["cas:authenticationSuccess"]
username = xml_from_dict["cas:user"]
flask.session[cas_username_session_key] = username
if "cas:attributes" in xml_from_dict:
attributes = xml_from_dict["cas:attributes"]
if "cas:memberOf" in attributes:
attributes["cas:memberOf"] = attributes["cas:memberOf"].lstrip('[').rstrip(']').split(',')
for group_number in range(0, len(attributes['cas:memberOf'])):
attributes['cas:memberOf'][group_number] = attributes['cas:memberOf'][group_number].lstrip(' ').rstrip(' ')
flask.session[cas_attributes_session_key] = attributes
else:
current_app.logger.debug("invalid")
return isValid
|
def validate(ticket)
|
Will attempt to validate the ticket. If validation fails, then False
is returned. If validation is successful, then True is returned
and the validated username is saved in the session under the
key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary
is saved under the key 'CAS_ATTRIBUTES_SESSION_KEY'.
| 2.528654 | 2.359308 | 1.071778 |
url = base
# Add the path to the url if it's not None.
if path is not None:
url = urljoin(url, quote(path))
# Remove key/value pairs with None values.
query = filter(lambda pair: pair[1] is not None, query)
# Add the query string to the url
url = urljoin(url, '?{0}'.format(urlencode(list(query))))
return url
|
def create_url(base, path=None, *query)
|
Create a url.
Creates a url by combining base, path, and the query's list of
key/value pairs. Escaping is handled automatically. Any
key/value pair with a value that is None is ignored.
Keyword arguments:
base -- The left most part of the url (ex. http://localhost:5000).
path -- The path after the base (ex. /foo/bar).
query -- A list of key value pairs (ex. [('key', 'value')]).
Example usage:
>>> create_url(
... 'http://localhost:5000',
... 'foo/bar',
... ('key1', 'value'),
... ('key2', None), # Will not include None
... ('url', 'http://example.com'),
... )
'http://localhost:5000/foo/bar?key1=value&url=http%3A%2F%2Fexample.com'
| 2.841681 | 3.041847 | 0.934196 |
return create_url(
cas_url,
cas_route,
('service', service),
('renew', renew),
('gateway', gateway),
)
|
def create_cas_login_url(cas_url, cas_route, service, renew=None, gateway=None)
|
Create a CAS login URL .
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas)
service -- (ex. http://localhost:5000/login)
renew -- "true" or "false"
gateway -- "true" or "false"
Example usage:
>>> create_cas_login_url(
... 'http://sso.pdx.edu',
... '/cas',
... 'http://localhost:5000',
... )
'http://sso.pdx.edu/cas?service=http%3A%2F%2Flocalhost%3A5000'
| 2.783418 | 4.432482 | 0.627959 |
return create_url(
cas_url,
cas_route,
('service', service),
('ticket', ticket),
('renew', renew),
)
|
def create_cas_validate_url(cas_url, cas_route, service, ticket,
renew=None)
|
Create a CAS validate URL.
Keyword arguments:
cas_url -- The url to the CAS (ex. http://sso.pdx.edu)
cas_route -- The route where the CAS lives on server (ex. /cas/serviceValidate)
service -- (ex. http://localhost:5000/login)
ticket -- (ex. 'ST-58274-x839euFek492ou832Eena7ee-cas')
renew -- "true" or "false"
Example usage:
>>> create_cas_validate_url(
... 'http://sso.pdx.edu',
... '/cas/serviceValidate',
... 'http://localhost:5000/login',
... 'ST-58274-x839euFek492ou832Eena7ee-cas'
... )
'http://sso.pdx.edu/cas/serviceValidate?service=http%3A%2F%2Flocalhost%3A5000%2Flogin&ticket=ST-58274-x839euFek492ou832Eena7ee-cas'
| 2.75591 | 4.376113 | 0.629762 |
if isinstance(obj, (argparse.Namespace, optparse.Values)):
return vars(obj)
return obj
|
def namespace_to_dict(obj)
|
If obj is argparse.Namespace or optparse.Values we'll return
a dict representation of it, else return the original object.
Redefine this method if using other parsers.
:param obj: *
:return:
:rtype: dict or *
| 4.659722 | 3.818286 | 1.22037 |
loader = pkgutil.get_loader(name)
if loader is None or name == '__main__':
return None
if hasattr(loader, 'get_filename'):
filepath = loader.get_filename(name)
else:
# Fall back to importing the specified module.
__import__(name)
filepath = sys.modules[name].__file__
return os.path.dirname(os.path.abspath(filepath))
|
def _package_path(name)
|
Returns the path to the package containing the named module or
None if the path could not be identified (e.g., if
``name == "__main__"``).
| 2.432666 | 2.464092 | 0.987247 |
paths = []
if 'XDG_CONFIG_HOME' in os.environ:
paths.append(os.environ['XDG_CONFIG_HOME'])
if 'XDG_CONFIG_DIRS' in os.environ:
paths.extend(os.environ['XDG_CONFIG_DIRS'].split(':'))
else:
paths.append('/etc/xdg')
paths.append('/etc')
return paths
|
def xdg_config_dirs()
|
Returns a list of paths taken from the XDG_CONFIG_DIRS
and XDG_CONFIG_HOME environment varibables if they exist
| 1.623557 | 1.619261 | 1.002653 |
paths = []
if platform.system() == 'Darwin':
paths.append(MAC_DIR)
paths.append(UNIX_DIR_FALLBACK)
paths.extend(xdg_config_dirs())
elif platform.system() == 'Windows':
paths.append(WINDOWS_DIR_FALLBACK)
if WINDOWS_DIR_VAR in os.environ:
paths.append(os.environ[WINDOWS_DIR_VAR])
else:
# Assume Unix.
paths.append(UNIX_DIR_FALLBACK)
paths.extend(xdg_config_dirs())
# Expand and deduplicate paths.
out = []
for path in paths:
path = os.path.abspath(os.path.expanduser(path))
if path not in out:
out.append(path)
return out
|
def config_dirs()
|
Return a platform-specific list of candidates for user
configuration directories on the system.
The candidates are in order of priority, from highest to lowest. The
last element is the "fallback" location to be used when no
higher-priority config file exists.
| 2.31421 | 2.293405 | 1.009072 |
try:
with open(filename, 'rb') as f:
return yaml.load(f, Loader=Loader)
except (IOError, yaml.error.YAMLError) as exc:
raise ConfigReadError(filename, exc)
|
def load_yaml(filename)
|
Read a YAML document from a file. If the file cannot be read or
parsed, a ConfigReadError is raised.
| 2.488879 | 2.164902 | 1.14965 |
comment_map = dict()
default_lines = iter(default_data.splitlines())
for line in default_lines:
if not line:
comment = "\n"
elif line.startswith("#"):
comment = "{0}\n".format(line)
else:
continue
while True:
line = next(default_lines)
if line and not line.startswith("#"):
break
comment += "{0}\n".format(line)
key = line.split(':')[0].strip()
comment_map[key] = comment
out_lines = iter(data.splitlines())
out_data = ""
for line in out_lines:
key = line.split(':')[0].strip()
if key in comment_map:
out_data += comment_map[key]
out_data += "{0}\n".format(line)
return out_data
|
def restore_yaml_comments(data, default_data)
|
Scan default_data for comments (we include empty lines in our
definition of comments) and place them before the same keys in data.
Only works with comments that are on one or more own lines, i.e.
not next to a yaml mapping.
| 2.088846 | 2.063268 | 1.012397 |
if isinstance(value, Template):
# If it's already a Template, pass it through.
return value
elif isinstance(value, abc.Mapping):
# Dictionaries work as templates.
return MappingTemplate(value)
elif value is int:
return Integer()
elif isinstance(value, int):
return Integer(value)
elif isinstance(value, type) and issubclass(value, BASESTRING):
return String()
elif isinstance(value, BASESTRING):
return String(value)
elif isinstance(value, set):
# convert to list to avoid hash related problems
return Choice(list(value))
elif (SUPPORTS_ENUM and isinstance(value, type)
and issubclass(value, enum.Enum)):
return Choice(value)
elif isinstance(value, list):
return OneOf(value)
elif value is float:
return Number()
elif value is None:
return Template()
elif value is dict:
return TypeTemplate(abc.Mapping)
elif value is list:
return TypeTemplate(abc.Sequence)
elif isinstance(value, type):
return TypeTemplate(value)
else:
raise ValueError(u'cannot convert to template: {0!r}'.format(value))
|
def as_template(value)
|
Convert a simple "shorthand" Python value to a `Template`.
| 3.257457 | 3.128807 | 1.041118 |
if isinstance(value, ConfigSource):
return value
elif isinstance(value, dict):
return ConfigSource(value)
else:
raise TypeError(u'source value must be a dict')
|
def of(cls, value)
|
Given either a dictionary or a `ConfigSource` object, return
a `ConfigSource` object. This lets a function accept either type
of object as an argument.
| 3.953833 | 3.277092 | 1.206507 |
pairs = self.resolve()
try:
return iter_first(pairs)
except ValueError:
raise NotFoundError(u"{0} not found".format(self.name))
|
def first(self)
|
Return a (value, source) pair for the first object found for
this view. This amounts to the first element returned by
`resolve`. If no values are available, a NotFoundError is
raised.
| 7.744495 | 5.187266 | 1.492982 |
# We expect our root object to be a dict, but it may come in as
# a namespace
obj = namespace_to_dict(obj)
# We only deal with dictionaries
if not isinstance(obj, dict):
return obj
# Get keys iterator
keys = obj.keys() if PY3 else obj.iterkeys()
if dots:
# Dots needs sorted keys to prevent parents from
# clobbering children
keys = sorted(list(keys))
output = {}
for key in keys:
value = obj[key]
if value is None: # Avoid unset options.
continue
save_to = output
result = cls._build_namespace_dict(value, dots)
if dots:
# Split keys by dots as this signifies nesting
split = key.split('.')
if len(split) > 1:
# The last index will be the key we assign result to
key = split.pop()
# Build the dict tree if needed and change where
# we're saving to
for child_key in split:
if child_key in save_to and \
isinstance(save_to[child_key], dict):
save_to = save_to[child_key]
else:
# Clobber or create
save_to[child_key] = {}
save_to = save_to[child_key]
# Save
if key in save_to:
save_to[key].update(result)
else:
save_to[key] = result
return output
|
def _build_namespace_dict(cls, obj, dots=False)
|
Recursively replaces all argparse.Namespace and optparse.Values
with dicts and drops any keys with None values.
Additionally, if dots is True, will expand any dot delimited
keys.
:param obj: Namespace, Values, or dict to iterate over. Other
values will simply be returned.
:type obj: argparse.Namespace or optparse.Values or dict or *
:param dots: If True, any properties on obj that contain dots (.)
will be broken down into child dictionaries.
:return: A new dictionary or the value passed if obj was not a
dict, Namespace, or Values.
:rtype: dict or *
| 4.056947 | 4.0222 | 1.008639 |
self.set(self._build_namespace_dict(namespace, dots))
|
def set_args(self, namespace, dots=False)
|
Overlay parsed command-line arguments, generated by a library
like argparse or optparse, onto this view's value.
:param namespace: Dictionary or Namespace to overlay this config with.
Supports nested Dictionaries and Namespaces.
:type namespace: dict or Namespace
:param dots: If True, any properties on namespace that contain dots (.)
will be broken down into child dictionaries.
:Example:
{'foo.bar': 'car'}
# Will be turned into
{'foo': {'bar': 'car'}}
:type dots: bool
| 11.572721 | 10.288807 | 1.124787 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.