signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
@property<EOL><INDENT>def _statistic(self):<DEDENT>
|
return self.I<EOL>
|
More consistent hidden attribute to access ESDA statistics
|
f11560:c0:m3
|
@classmethod<EOL><INDENT>def by_col(cls, df, cols, w=None, inplace=False, pvalue='<STR_LIT>', outvals=None, **stat_kws):<DEDENT>
|
return _univariate_handler(df, cols, w=w, inplace=inplace, pvalue=pvalue,<EOL>outvals=outvals, stat=cls,<EOL>swapname=cls.__name__.lower(), **stat_kws)<EOL>
|
Function to compute a Moran statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to compute the statistic
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran class in pysal.esda
|
f11560:c0:m4
|
@property<EOL><INDENT>def _statistic(self):<DEDENT>
|
return self.I<EOL>
|
More consistent hidden attribute to access ESDA statistics
|
f11560:c1:m2
|
@classmethod<EOL><INDENT>def by_col(cls, df, x, y=None, w=None, inplace=False, pvalue='<STR_LIT>', outvals=None, **stat_kws):<DEDENT>
|
return _bivariate_handler(df, x, y=y, w=w, inplace=inplace,<EOL>pvalue = pvalue, outvals = outvals,<EOL>swapname=cls.__name__.lower(), stat=cls,**stat_kws)<EOL>
|
Function to compute a Moran_BV statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
X : list of strings
column name or list of column names to use as X values to compute
the bivariate statistic. If no Y is provided, pairwise comparisons
among these variates are used instead.
Y : list of strings
column name or list of column names to use as Y values to compute
the bivariate statistic. if no Y is provided, pariwise comparisons
among the X variates are used instead.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_local'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_BV statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_BV statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_BV statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_BV class in pysal.esda
|
f11560:c1:m3
|
@classmethod<EOL><INDENT>def by_col(cls, df, events, populations, w=None, inplace=False,<EOL>pvalue='<STR_LIT>', outvals=None, swapname='<STR_LIT>', **stat_kws):<DEDENT>
|
if not inplace:<EOL><INDENT>new = df.copy()<EOL>cls.by_col(new, events, populations, w=w, inplace=True,<EOL>pvalue=pvalue, outvals=outvals, swapname=swapname,<EOL>**stat_kws)<EOL>return new<EOL><DEDENT>if isinstance(events, str):<EOL><INDENT>events = [events]<EOL><DEDENT>if isinstance(populations, str):<EOL><INDENT>populations = [populations]<EOL><DEDENT>if len(populations) < len(events):<EOL><INDENT>populations = populations * len(events)<EOL><DEDENT>if len(events) != len(populations):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(events, populations))<EOL><DEDENT>adjusted = stat_kws.pop('<STR_LIT>', True)<EOL>if isinstance(adjusted, bool):<EOL><INDENT>adjusted = [adjusted] * len(events)<EOL><DEDENT>if swapname is '<STR_LIT>':<EOL><INDENT>swapname = cls.__name__.lower()<EOL><DEDENT>rates = [assuncao_rate(df[e], df[pop]) if adj<EOL>else df[e].astype(float) / df[pop]<EOL>for e,pop,adj in zip(events, populations, adjusted)]<EOL>names = ['<STR_LIT:->'.join((e,p)) for e,p in zip(events, populations)]<EOL>out_df = df.copy()<EOL>rate_df = out_df.from_items(list(zip(names, rates))) <EOL>stat_df = _univariate_handler(rate_df, names, w=w, inplace=False,<EOL>pvalue = pvalue, outvals = outvals,<EOL>swapname=swapname,<EOL>stat=Moran, <EOL>**stat_kws)<EOL>for col in stat_df.columns:<EOL><INDENT>df[col] = stat_df[col]<EOL><DEDENT>
|
Function to compute a Moran_Rate statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
events : string or list of strings
one or more names where events are stored
populations : string or list of strings
one or more names where the populations corresponding to the
events are stored. If one population column is provided, it is
used for all event columns. If more than one population column
is provided but there is not a population for every event
column, an exception will be raised.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_rate'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_Rate statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_Rate statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_Rate statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_Rate class in pysal.esda
|
f11560:c2:m1
|
def __crand(self):
|
z = self.z<EOL>lisas = np.zeros((self.n, self.permutations))<EOL>n_1 = self.n - <NUM_LIT:1><EOL>prange = list(range(self.permutations))<EOL>k = self.w.max_neighbors + <NUM_LIT:1><EOL>nn = self.n - <NUM_LIT:1><EOL>rids = np.array([np.random.permutation(nn)[<NUM_LIT:0>:k] for i in prange])<EOL>ids = np.arange(self.w.n)<EOL>ido = self.w.id_order<EOL>w = [self.w.weights[ido[i]] for i in ids]<EOL>wc = [self.w.cardinalities[ido[i]] for i in ids]<EOL>for i in range(self.w.n):<EOL><INDENT>idsi = ids[ids != i]<EOL>np.random.shuffle(idsi)<EOL>tmp = z[idsi[rids[:, <NUM_LIT:0>:wc[i]]]]<EOL>lisas[i] = z[i] * (w[i] * tmp).sum(<NUM_LIT:1>)<EOL><DEDENT>self.rlisas = (n_1 / self.den) * lisas<EOL>
|
conditional randomization
for observation i with ni neighbors, the candidate set cannot include
i (we don't want i being a neighbor of i). we have to sample without
replacement from a set of ids that doesn't include i. numpy doesn't
directly support sampling wo replacement and it is expensive to
implement this. instead we omit i from the original ids, permute the
ids and take the first ni elements of the permuted ids as the
neighbors to i in each randomization.
|
f11560:c3:m2
|
@property<EOL><INDENT>def _statistic(self):<DEDENT>
|
return self.Is<EOL>
|
More consistent hidden attribute to access ESDA statistics
|
f11560:c3:m4
|
@classmethod<EOL><INDENT>def by_col(cls, df, cols, w=None, inplace=False, pvalue='<STR_LIT>', outvals=None, **stat_kws):<DEDENT>
|
return _univariate_handler(df, cols, w=w, inplace=inplace, pvalue=pvalue,<EOL>outvals=outvals, stat=cls,<EOL>swapname=cls.__name__.lower(), **stat_kws)<EOL>
|
Function to compute a Moran_Local statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
cols : string or list of string
name or list of names of columns to use to compute the statistic
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_local'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_Local statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_Local statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_Local statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_Local class in pysal.esda
|
f11560:c3:m5
|
def __crand(self):
|
lisas = np.zeros((self.n, self.permutations))<EOL>n_1 = self.n - <NUM_LIT:1><EOL>prange = list(range(self.permutations))<EOL>k = self.w.max_neighbors + <NUM_LIT:1><EOL>nn = self.n - <NUM_LIT:1><EOL>rids = np.array([np.random.permutation(nn)[<NUM_LIT:0>:k] for i in prange])<EOL>ids = np.arange(self.w.n)<EOL>ido = self.w.id_order<EOL>w = [self.w.weights[ido[i]] for i in ids]<EOL>wc = [self.w.cardinalities[ido[i]] for i in ids]<EOL>zx = self.zx<EOL>zy = self.zy<EOL>for i in range(self.w.n):<EOL><INDENT>idsi = ids[ids != i]<EOL>np.random.shuffle(idsi)<EOL>tmp = zy[idsi[rids[:, <NUM_LIT:0>:wc[i]]]]<EOL>lisas[i] = zx[i] * (w[i] * tmp).sum(<NUM_LIT:1>)<EOL><DEDENT>self.rlisas = (n_1 / self.den) * lisas<EOL>
|
conditional randomization
for observation i with ni neighbors, the candidate set cannot include
i (we don't want i being a neighbor of i). we have to sample without
replacement from a set of ids that doesn't include i. numpy doesn't
directly support sampling wo replacement and it is expensive to
implement this. instead we omit i from the original ids, permute the
ids and take the first ni elements of the permuted ids as the
neighbors to i in each randomization.
|
f11560:c4:m2
|
@property<EOL><INDENT>def _statistic(self):<DEDENT>
|
return self.Is<EOL>
|
More consistent hidden attribute to access ESDA statistics
|
f11560:c4:m4
|
@classmethod<EOL><INDENT>def by_col(cls, df, x, y=None, w=None, inplace=False, pvalue='<STR_LIT>', outvals=None, **stat_kws):<DEDENT>
|
return _bivariate_handler(df, x, y=y, w=w, inplace=inplace,<EOL>pvalue = pvalue, outvals = outvals,<EOL>swapname=cls.__name__.lower(), stat=cls,**stat_kws)<EOL>
|
Function to compute a Moran_Local_BV statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
X : list of strings
column name or list of column names to use as X values to compute
the bivariate statistic. If no Y is provided, pairwise comparisons
among these variates are used instead.
Y : list of strings
column name or list of column names to use as Y values to compute
the bivariate statistic. if no Y is provided, pariwise comparisons
among the X variates are used instead.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named
'column_moran_local_bv'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_Local_BV statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_Local_BV statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_Local_BV statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_Local_BV class in pysal.esda
|
f11560:c4:m5
|
@classmethod<EOL><INDENT>def by_col(cls, df, events, populations, w=None, inplace=False,<EOL>pvalue='<STR_LIT>', outvals=None, swapname='<STR_LIT>', **stat_kws):<DEDENT>
|
if not inplace:<EOL><INDENT>new = df.copy()<EOL>cls.by_col(new, events, populations, w=w, inplace=True,<EOL>pvalue=pvalue, outvals=outvals, swapname=swapname,<EOL>**stat_kws)<EOL>return new<EOL><DEDENT>if isinstance(events, str):<EOL><INDENT>events = [events]<EOL><DEDENT>if isinstance(populations, str):<EOL><INDENT>populations = [populations]<EOL><DEDENT>if len(populations) < len(events):<EOL><INDENT>populations = populations * len(events)<EOL><DEDENT>if len(events) != len(populations):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(events, populations))<EOL><DEDENT>adjusted = stat_kws.pop('<STR_LIT>', True)<EOL>if isinstance(adjusted, bool):<EOL><INDENT>adjusted = [adjusted] * len(events)<EOL><DEDENT>if swapname is '<STR_LIT>':<EOL><INDENT>swapname = cls.__name__.lower()<EOL><DEDENT>rates = [assuncao_rate(df[e], df[pop]) if adj<EOL>else df[e].astype(float) / df[pop]<EOL>for e,pop,adj in zip(events, populations, adjusted)]<EOL>names = ['<STR_LIT:->'.join((e,p)) for e,p in zip(events, populations)]<EOL>out_df = df.copy()<EOL>rate_df = out_df.from_items(list(zip(names, rates))) <EOL>_univariate_handler(rate_df, names, w=w, inplace=True,<EOL>pvalue = pvalue, outvals = outvals,<EOL>swapname=swapname,<EOL>stat=Moran_Local, <EOL>**stat_kws)<EOL>for col in rate_df.columns:<EOL><INDENT>df[col] = rate_df[col]<EOL><DEDENT>
|
Function to compute a Moran_Local_Rate statistic on a dataframe
Arguments
---------
df : pandas.DataFrame
a pandas dataframe with a geometry column
events : string or list of strings
one or more names where events are stored
populations : string or list of strings
one or more names where the populations corresponding to the
events are stored. If one population column is provided, it is
used for all event columns. If more than one population column
is provided but there is not a population for every event
column, an exception will be raised.
w : pysal weights object
a weights object aligned with the dataframe. If not provided, this
is searched for in the dataframe's metadata
inplace : bool
a boolean denoting whether to operate on the dataframe inplace or to
return a series contaning the results of the computation. If
operating inplace, the derived columns will be named 'column_moran_local_rate'
pvalue : string
a string denoting which pvalue should be returned. Refer to the
the Moran_Local_Rate statistic's documentation for available p-values
outvals : list of strings
list of arbitrary attributes to return as columns from the
Moran_Local_Rate statistic
**stat_kws : keyword arguments
options to pass to the underlying statistic. For this, see the
documentation for the Moran_Local_Rate statistic.
Returns
--------
If inplace, None, and operation is conducted on dataframe in memory. Otherwise,
returns a copy of the dataframe with the relevant columns attached.
See Also
---------
For further documentation, refer to the Moran_Local_Rate class in pysal.esda
|
f11560:c5:m1
|
def handle_image_posts(function=None):
|
@wraps(function, assigned=available_attrs(function))<EOL>def _wrapped_view(request, *args, **kwargs):<EOL><INDENT>if '<STR_LIT:image>' in request.META['<STR_LIT>']:<EOL><INDENT>name = default_storage.save(os.path.join('<STR_LIT>', '<STR_LIT>', request.META['<STR_LIT>']),<EOL>ContentFile(base64.b64decode(request.body.split("<STR_LIT:U+002C>", <NUM_LIT:1>)[<NUM_LIT:1>])))<EOL>return HttpResponse(posixpath.join(settings.MEDIA_URL, name), content_type="<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>return function(request, *args, **kwargs)<EOL><DEDENT><DEDENT>return _wrapped_view<EOL>
|
Decorator for views that handles ajax image posts in base64 encoding, saving
the image and returning the url
|
f11564:m0
|
def from_object(self, obj):
|
for key in dir(obj):<EOL><INDENT>if key.isupper():<EOL><INDENT>self[key] = getattr(obj, key)<EOL><DEDENT><DEDENT>
|
Updates the values from the given object
Args:
obj (instance): Object with config attributes
Objects are classes.
Just the uppercase variables in that object are stored in the config.
Example usage::
from yourapplication import default_config
app.config.from_object(default_config())
|
f11574:c0:m2
|
def ask_yes_no(question, default='<STR_LIT>', answer=None):
|
default = default.lower()<EOL>yes = [u'<STR_LIT:yes>', u'<STR_LIT>', u'<STR_LIT:y>']<EOL>no = [u'<STR_LIT>', u'<STR_LIT:n>']<EOL>if default in no:<EOL><INDENT>help_ = u'<STR_LIT>'<EOL>default = False<EOL><DEDENT>else:<EOL><INDENT>default = True<EOL>help_ = u'<STR_LIT>'<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>display = question + '<STR_LIT:\n>' + help_<EOL>if answer is None:<EOL><INDENT>log.debug(u'<STR_LIT>')<EOL>answer = six.moves.input(display)<EOL>answer = answer.lower()<EOL><DEDENT>if answer == u'<STR_LIT>':<EOL><INDENT>log.debug(u'<STR_LIT>')<EOL>return default<EOL><DEDENT>if answer in yes:<EOL><INDENT>log.debug(u'<STR_LIT>')<EOL>return True<EOL><DEDENT>elif answer in no:<EOL><INDENT>log.debug(u'<STR_LIT>')<EOL>return False<EOL><DEDENT>else:<EOL><INDENT>sys.stdout.write(u'<STR_LIT>')<EOL>sys.stdout.flush()<EOL>answer = None<EOL>six.moves.input(u'<STR_LIT>')<EOL>sys.stdout.write('<STR_LIT>')<EOL>sys.stdout.flush()<EOL><DEDENT><DEDENT>
|
u"""Will ask a question and keeps prompting until
answered.
Args:
question (str): Question to ask end user
default (str): Default answer if user just press enter at prompt
answer (str): Used for testing
Returns:
(bool) Meaning:
True - Answer is yes
False - Answer is no
|
f11575:m6
|
def get_correct_answer(question, default=None, required=False,<EOL>answer=None, is_answer_correct=None):
|
while <NUM_LIT:1>:<EOL><INDENT>if default is None:<EOL><INDENT>msg = u'<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>msg = (u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(default))<EOL><DEDENT>prompt = question + msg + u'<STR_LIT>'<EOL>if answer is None:<EOL><INDENT>answer = six.moves.input(prompt)<EOL><DEDENT>if answer == '<STR_LIT>' and required and default is not None:<EOL><INDENT>print(u'<STR_LIT>')<EOL>six.moves.input(u'<STR_LIT>')<EOL>print(u'<STR_LIT>')<EOL>answer = None<EOL>continue<EOL><DEDENT>if answer == u'<STR_LIT>' and default is not None:<EOL><INDENT>answer = default<EOL><DEDENT>_ans = ask_yes_no(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(answer),<EOL>answer=is_answer_correct)<EOL>if _ans:<EOL><INDENT>return answer<EOL><DEDENT>else:<EOL><INDENT>answer = None<EOL><DEDENT><DEDENT>
|
u"""Ask user a question and confirm answer
Args:
question (str): Question to ask user
default (str): Default answer if no input from user
required (str): Require user to input answer
answer (str): Used for testing
is_answer_correct (str): Used for testing
|
f11575:m7
|
def make_compat_str(in_str):
|
assert isinstance(in_str, (bytes, str, unicode))<EOL>if not in_str:<EOL><INDENT>return unicode()<EOL><DEDENT>if six.PY2 and isinstance(in_str, unicode):<EOL><INDENT>return in_str<EOL><DEDENT>if not six.PY2 and not isinstance(in_str, bytes):<EOL><INDENT>return in_str<EOL><DEDENT>enc = chardet.detect(in_str)<EOL>out_str = in_str.decode(enc['<STR_LIT>'])<EOL>if enc['<STR_LIT>'] == "<STR_LIT>":<EOL><INDENT>if out_str.startswith('<STR_LIT>'):<EOL><INDENT>out_str = out_str[<NUM_LIT:1>:]<EOL><DEDENT><DEDENT>return out_str<EOL>
|
Tries to guess encoding of [str/bytes] and decode it into
an unicode object.
|
f11577:m0
|
def get_package_hashes(filename):
|
log.debug('<STR_LIT>')<EOL>filename = os.path.abspath(filename)<EOL>with open(filename, '<STR_LIT:rb>') as f:<EOL><INDENT>data = f.read()<EOL><DEDENT>_hash = hashlib.sha256(data).hexdigest()<EOL>log.debug('<STR_LIT>', filename, _hash)<EOL>return _hash<EOL>
|
Provides hash of given filename.
Args:
filename (str): Name of file to hash
Returns:
(str): sha256 hash
|
f11578:m0
|
def get_keywords():
|
<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full}<EOL>return keywords<EOL>
|
Get the keywords needed to look up the version information.
|
f11579:m0
|
def get_config():
|
<EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL>
|
Create, populate and return the VersioneerConfig() object.
|
f11579:m1
|
def register_vcs_handler(vcs, method):
|
def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>
|
Decorator to mark a method as the handler for a particular VCS.
|
f11579:m2
|
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL><DEDENT>return None<EOL><DEDENT>return stdout<EOL>
|
Call the given command(s).
|
f11579:m3
|
def versions_from_parentdir(parentdir_prefix, root, verbose):
|
dirname = os.path.basename(root)<EOL>if not dirname.startswith(parentdir_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>" % (root, dirname, parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None}<EOL>
|
Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes
both the project name and a version string.
|
f11579:m4
|
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs):
|
<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>
|
Extract version information from the given file.
|
f11579:m5
|
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs-tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None<EOL>}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>"}<EOL>
|
Get version information from git keywords.
|
f11579:m6
|
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
|
if not os.path.exists(os.path.join(root, "<STR_LIT>")):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>describe_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>] <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out) <EOL><DEDENT>return pieces<EOL>
|
Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
|
f11579:m7
|
def plus_or_dot(pieces):
|
if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>
|
Return a + if we don't already have one, else return a .
|
f11579:m8
|
def render_pep440(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
|
Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
|
f11579:m9
|
def render_pep440_pre(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
|
TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
|
f11579:m10
|
def render_pep440_post(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
|
TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]
|
f11579:m11
|
def render_pep440_old(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
|
TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
|
f11579:m12
|
def render_git_describe(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
|
TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
|
f11579:m13
|
def render_git_describe_long(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
|
TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
|
f11579:m14
|
def render(pieces, style):
|
if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"]}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None}<EOL>
|
Render the given version pieces into the requested style.
|
f11579:m15
|
def get_versions():
|
<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>'):<EOL><INDENT>root = os.path.dirname(root)<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>"}<EOL><DEDENT>try:<EOL><INDENT>pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)<EOL>return render(pieces, cfg.style)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>"}<EOL>
|
Get version information or return default if unable to do so.
|
f11579:m16
|
def get_mac_dot_app_dir(directory):
|
return os.path.dirname(os.path.dirname(os.path.dirname(directory)))<EOL>
|
Returns parent directory of mac .app
Args:
directory (str): Current directory
Returns:
(str): Parent directory of mac .app
|
f11580:m0
|
def lazy_import(func):
|
try:<EOL><INDENT>f = sys._getframe(<NUM_LIT:1>)<EOL><DEDENT>except Exception: <EOL><INDENT>namespace = None<EOL><DEDENT>else:<EOL><INDENT>namespace = f.f_locals<EOL><DEDENT>return _LazyImport(func.__name__, func, namespace)<EOL>
|
Decorator for declaring a lazy import.
This decorator turns a function into an object that will act as a lazy
importer. Whenever the object's attributes are accessed, the function
is called and its return value used in place of the object. So you
can declare lazy imports like this:
@lazy_import
def socket():
import socket
return socket
The name "socket" will then be bound to a transparent object proxy which
will import the socket module upon first use.
The syntax here is slightly more verbose than other lazy import recipes,
but it's designed not to hide the actual "import" statements from tools
like pyinstaller or grep.
|
f11582:m1
|
def get_root():
|
root = os.path.realpath(os.path.abspath(os.getcwd()))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[<NUM_LIT:0>])))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL><DEDENT>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>err = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise VersioneerBadRootError(err)<EOL><DEDENT>try:<EOL><INDENT>me = os.path.realpath(os.path.abspath(__file__))<EOL>if os.path.splitext(me)[<NUM_LIT:0>] != os.path.splitext(versioneer_py)[<NUM_LIT:0>]:<EOL><INDENT>print("<STR_LIT>"<EOL>% (os.path.dirname(me), versioneer_py))<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT>return root<EOL>
|
Get the project root directory.
We require that all commands are run from the project root, i.e. the
directory that contains setup.py, setup.cfg, and versioneer.py .
|
f11588:m0
|
def get_config_from_root(root):
|
<EOL>setup_cfg = os.path.join(root, "<STR_LIT>")<EOL>parser = configparser.SafeConfigParser()<EOL>with open(setup_cfg, "<STR_LIT:r>") as f:<EOL><INDENT>parser.readfp(f)<EOL><DEDENT>VCS = parser.get("<STR_LIT>", "<STR_LIT>") <EOL>def get(parser, name):<EOL><INDENT>if parser.has_option("<STR_LIT>", name):<EOL><INDENT>return parser.get("<STR_LIT>", name)<EOL><DEDENT>return None<EOL><DEDENT>cfg = VersioneerConfig()<EOL>cfg.VCS = VCS<EOL>cfg.style = get(parser, "<STR_LIT>") or "<STR_LIT>"<EOL>cfg.versionfile_source = get(parser, "<STR_LIT>")<EOL>cfg.versionfile_build = get(parser, "<STR_LIT>")<EOL>cfg.tag_prefix = get(parser, "<STR_LIT>")<EOL>if cfg.tag_prefix in ("<STR_LIT>", '<STR_LIT>'):<EOL><INDENT>cfg.tag_prefix = "<STR_LIT>"<EOL><DEDENT>cfg.parentdir_prefix = get(parser, "<STR_LIT>")<EOL>cfg.verbose = get(parser, "<STR_LIT>")<EOL>return cfg<EOL>
|
Read the project setup.cfg file to determine Versioneer config.
|
f11588:m1
|
def register_vcs_handler(vcs, method):
|
def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>
|
Decorator to mark a method as the handler for a particular VCS.
|
f11588:m2
|
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
|
assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL><DEDENT>return None<EOL><DEDENT>return stdout<EOL>
|
Call the given command(s).
|
f11588:m3
|
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs):
|
<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>
|
Extract version information from the given file.
|
f11588:m4
|
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):
|
if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs-tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None<EOL>}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>"}<EOL>
|
Get version information from git keywords.
|
f11588:m5
|
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
|
if not os.path.exists(os.path.join(root, "<STR_LIT>")):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>describe_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>] <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out) <EOL><DEDENT>return pieces<EOL>
|
Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
|
f11588:m6
|
def do_vcs_install(manifest_in, versionfile_source, ipy):
|
GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>files = [manifest_in, versionfile_source]<EOL>if ipy:<EOL><INDENT>files.append(ipy)<EOL><DEDENT>try:<EOL><INDENT>me = __file__<EOL>if me.endswith("<STR_LIT>") or me.endswith("<STR_LIT>"):<EOL><INDENT>me = os.path.splitext(me)[<NUM_LIT:0>] + "<STR_LIT>"<EOL><DEDENT>versioneer_file = os.path.relpath(me)<EOL><DEDENT>except NameError:<EOL><INDENT>versioneer_file = "<STR_LIT>"<EOL><DEDENT>files.append(versioneer_file)<EOL>present = False<EOL>try:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith(versionfile_source):<EOL><INDENT>if "<STR_LIT>" in line.strip().split()[<NUM_LIT:1>:]:<EOL><INDENT>present = True<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if not present:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT>")<EOL>f.write("<STR_LIT>" % versionfile_source)<EOL>f.close()<EOL>files.append("<STR_LIT>")<EOL><DEDENT>run_command(GITS, ["<STR_LIT>", "<STR_LIT>"] + files)<EOL>
|
Git-specific installation logic for Versioneer.
For Git, this means creating/changing .gitattributes to mark _version.py
for export-time keyword substitution.
|
f11588:m7
|
def versions_from_parentdir(parentdir_prefix, root, verbose):
|
dirname = os.path.basename(root)<EOL>if not dirname.startswith(parentdir_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>"<EOL>"<STR_LIT>" % (root, dirname, parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None}<EOL>
|
Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes
both the project name and a version string.
|
f11588:m8
|
def versions_from_file(filename):
|
try:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>contents = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL>if not mo:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return json.loads(mo.group(<NUM_LIT:1>))<EOL>
|
Try to determine the version from _version.py if present.
|
f11588:m9
|
def write_to_version_file(filename, versions):
|
os.unlink(filename)<EOL>contents = json.dumps(versions, sort_keys=True,<EOL>indent=<NUM_LIT:1>, separators=("<STR_LIT:U+002C>", "<STR_LIT>"))<EOL>with open(filename, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(SHORT_VERSION_PY % contents)<EOL><DEDENT>print("<STR_LIT>" % (filename, versions["<STR_LIT:version>"]))<EOL>
|
Write the given version number to the given _version.py file.
|
f11588:m10
|
def plus_or_dot(pieces):
|
if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>
|
Return a + if we don't already have one, else return a .
|
f11588:m11
|
def render_pep440(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
|
Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
|
f11588:m12
|
def render_pep440_pre(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
|
TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
|
f11588:m13
|
def render_pep440_post(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
|
TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0]
|
f11588:m14
|
def render_pep440_old(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
|
TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
|
f11588:m15
|
def render_git_describe(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
|
TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
|
f11588:m16
|
def render_git_describe_long(pieces):
|
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
|
TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
|
f11588:m17
|
def render(pieces, style):
|
if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"]}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None}<EOL>
|
Render the given version pieces into the requested style.
|
f11588:m18
|
def get_versions(verbose=False):
|
if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>assert cfg.VCS is not None, "<STR_LIT>"<EOL>handlers = HANDLERS.get(cfg.VCS)<EOL>assert handlers, "<STR_LIT>" % cfg.VCS<EOL>verbose = verbose or cfg.verbose<EOL>assert cfg.versionfile_source is not None,"<STR_LIT>"<EOL>assert cfg.tag_prefix is not None, "<STR_LIT>"<EOL>versionfile_abs = os.path.join(root, cfg.versionfile_source)<EOL>get_keywords_f = handlers.get("<STR_LIT>")<EOL>from_keywords_f = handlers.get("<STR_LIT>")<EOL>if get_keywords_f and from_keywords_f:<EOL><INDENT>try:<EOL><INDENT>keywords = get_keywords_f(versionfile_abs)<EOL>ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>ver = versions_from_file(versionfile_abs)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % (versionfile_abs, ver))<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>from_vcs_f = handlers.get("<STR_LIT>")<EOL>if from_vcs_f:<EOL><INDENT>try:<EOL><INDENT>pieces = from_vcs_f(cfg.tag_prefix, root, verbose)<EOL>ver = render(pieces, cfg.style)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None, "<STR_LIT:error>": "<STR_LIT>"}<EOL>
|
Get the project version from whatever source is available.
Returns dict with two keys: 'version' and 'full'.
|
f11588:m19
|
def get_version():
|
return get_versions()["<STR_LIT:version>"]<EOL>
|
Get the short version string for this project.
|
f11588:m20
|
def get_cmdclass():
|
if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>cmds = {}<EOL>from distutils.core import Command<EOL>class cmd_version(Command):<EOL><INDENT>description = "<STR_LIT>"<EOL>user_options = []<EOL>boolean_options = []<EOL>def initialize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def finalize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def run(self):<EOL><INDENT>vers = get_versions(verbose=True)<EOL>print("<STR_LIT>" % vers["<STR_LIT:version>"])<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>if vers["<STR_LIT:error>"]:<EOL><INDENT>print("<STR_LIT>" % vers["<STR_LIT:error>"])<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT:version>"] = cmd_version<EOL>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.build_py import build_py as _build_py<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.build_py import build_py as _build_py<EOL><DEDENT>class cmd_build_py(_build_py):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>_build_py.run(self)<EOL>if cfg.versionfile_build:<EOL><INDENT>target_versionfile = os.path.join(self.build_lib,<EOL>cfg.versionfile_build)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_py<EOL>if "<STR_LIT>" in sys.modules: <EOL><INDENT>from cx_Freeze.dist import build_exe as _build_exe<EOL>class cmd_build_exe(_build_exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_build_exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_exe<EOL>del cmds["<STR_LIT>"]<EOL><DEDENT>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.sdist import sdist as _sdist<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.sdist import sdist as _sdist<EOL><DEDENT>class cmd_sdist(_sdist):<EOL><INDENT>def run(self):<EOL><INDENT>versions = get_versions()<EOL>self._versioneer_generated_versions = versions<EOL>self.distribution.metadata.version = versions["<STR_LIT:version>"]<EOL>return _sdist.run(self)<EOL><DEDENT>def make_release_tree(self, base_dir, files):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>_sdist.make_release_tree(self, base_dir, files)<EOL>target_versionfile = os.path.join(base_dir, cfg.versionfile_source)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile,<EOL>self._versioneer_generated_versions)<EOL><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_sdist<EOL>return cmds<EOL>
|
Get the custom setuptools/distutils subclasses used by Versioneer.
|
f11588:m21
|
def do_setup():
|
root = get_root()<EOL>try:<EOL><INDENT>cfg = get_config_from_root(root)<EOL><DEDENT>except (EnvironmentError, configparser.NoSectionError,<EOL>configparser.NoOptionError) as e:<EOL><INDENT>if isinstance(e, (EnvironmentError, configparser.NoSectionError)):<EOL><INDENT>print("<STR_LIT>",<EOL>file=sys.stderr)<EOL>with open(os.path.join(root, "<STR_LIT>"), "<STR_LIT:a>") as f:<EOL><INDENT>f.write(SAMPLE_CONFIG)<EOL><DEDENT><DEDENT>print(CONFIG_ERROR, file=sys.stderr)<EOL>return <NUM_LIT:1><EOL><DEDENT>print("<STR_LIT>" % cfg.versionfile_source)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG % {"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT>ipy = os.path.join(os.path.dirname(cfg.versionfile_source),<EOL>"<STR_LIT>")<EOL>if os.path.exists(ipy):<EOL><INDENT>try:<EOL><INDENT>with open(ipy, "<STR_LIT:r>") as f:<EOL><INDENT>old = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>old = "<STR_LIT>"<EOL><DEDENT>if INIT_PY_SNIPPET not in old:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>with open(ipy, "<STR_LIT:a>") as f:<EOL><INDENT>f.write(INIT_PY_SNIPPET)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>ipy = None<EOL><DEDENT>manifest_in = os.path.join(root, "<STR_LIT>")<EOL>simple_includes = set()<EOL>try:<EOL><INDENT>with open(manifest_in, "<STR_LIT:r>") as f:<EOL><INDENT>for line in f:<EOL><INDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>for include in line.split()[<NUM_LIT:1>:]:<EOL><INDENT>simple_includes.add(include)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if "<STR_LIT>" not in simple_includes:<EOL><INDENT>print("<STR_LIT>")<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>if cfg.versionfile_source not in simple_includes:<EOL><INDENT>print("<STR_LIT>" %<EOL>cfg.versionfile_source)<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>" % cfg.versionfile_source)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>do_vcs_install(manifest_in, cfg.versionfile_source, ipy)<EOL>return <NUM_LIT:0><EOL>
|
Main VCS-independent setup function for installing Versioneer.
|
f11588:m22
|
def scan_setup_py():
|
found = set()<EOL>setters = False<EOL>errors = <NUM_LIT:0><EOL>with open("<STR_LIT>", "<STR_LIT:r>") as f:<EOL><INDENT>for line in f.readlines():<EOL><INDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT><DEDENT><DEDENT>if len(found) != <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>if setters:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>return errors<EOL>
|
Validate the contents of setup.py against Versioneer's expectations.
|
f11588:m23
|
def send(self, subname, value, timestamp=None):
|
if timestamp is None:<EOL><INDENT>ts = int(dt.datetime.now().strftime("<STR_LIT:%s>"))<EOL><DEDENT>else:<EOL><INDENT>ts = timestamp<EOL><DEDENT>name = self._get_name(self.name, subname)<EOL>self.logger.info('<STR_LIT>' % (name, value, ts))<EOL>return statsd.Client._send(self, {name: '<STR_LIT>' % (value, ts)})<EOL>
|
Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword value: The raw value to send
|
f11595:c0:m0
|
def send(self, data, sample_rate=None):
|
if self._disabled:<EOL><INDENT>self.logger.debug('<STR_LIT>')<EOL>return False<EOL><DEDENT>if sample_rate is None:<EOL><INDENT>sample_rate = self._sample_rate<EOL><DEDENT>sampled_data = {}<EOL>if sample_rate < <NUM_LIT:1>:<EOL><INDENT>if random.random() <= sample_rate:<EOL><INDENT>for stat, value in compat.iter_dict(data):<EOL><INDENT>sampled_data[stat] = '<STR_LIT>' % (data[stat], sample_rate)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>sampled_data = data<EOL><DEDENT>try:<EOL><INDENT>for stat, value in compat.iter_dict(sampled_data):<EOL><INDENT>send_data = ('<STR_LIT>' % (stat, value)).encode("<STR_LIT:utf-8>")<EOL>self.udp_sock.send(send_data)<EOL><DEDENT>return True<EOL><DEDENT>except Exception as e:<EOL><INDENT>self.logger.exception('<STR_LIT>', e)<EOL>return False<EOL><DEDENT>
|
Send the data over UDP while taking the sample_rate in account
The sample rate should be a number between `0` and `1` which indicates
the probability that a message will be sent. The sample_rate is also
communicated to `statsd` so it knows what multiplier to use.
:keyword data: The data to send
:type data: dict
:keyword sample_rate: The sample rate, defaults to `1` (meaning always)
:type sample_rate: int
|
f11596:c0:m2
|
def __del__(self):
|
self.udp_sock.close()<EOL>
|
We close UDP socket connection explicitly for pypy.
|
f11596:c0:m3
|
def increment(key, delta=<NUM_LIT:1>):
|
return Counter(key).increment(delta=delta)<EOL>
|
Increment the counter with `delta`
:keyword key: The key to report the data to
:type key: str
:keyword delta: The delta to add to the counter
:type delta: int
|
f11597:m0
|
def decrement(key, delta=<NUM_LIT:1>):
|
return Counter(key).decrement(delta=delta)<EOL>
|
Decrement the counter with `delta`
:keyword key: The key to report the data to
:type key: str
:keyword delta: The delta to remove from the counter
:type delta: int
|
f11597:m1
|
def _send(self, subname, delta):
|
name = self._get_name(self.name, subname)<EOL>self.logger.info('<STR_LIT>', name, delta)<EOL>return statsd.Client._send(self, {name: '<STR_LIT>' % delta})<EOL>
|
Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword delta: The delta to add to/remove from the counter
:type delta: int
|
f11597:c0:m0
|
def increment(self, subname=None, delta=<NUM_LIT:1>):
|
return self._send(subname, int(delta))<EOL>
|
Increment the counter with `delta`
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword delta: The delta to add to the counter
:type delta: int
>>> counter = Counter('application_name')
>>> counter.increment('counter_name', 10)
True
>>> counter.increment(delta=10)
True
>>> counter.increment('counter_name')
True
|
f11597:c0:m1
|
def decrement(self, subname=None, delta=<NUM_LIT:1>):
|
return self._send(subname, -int(delta))<EOL>
|
Decrement the counter with `delta`
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword delta: The delta to remove from the counter
:type delta: int
>>> counter = Counter('application_name')
>>> counter.decrement('counter_name', 10)
True
>>> counter.decrement(delta=10)
True
>>> counter.decrement('counter_name')
True
|
f11597:c0:m2
|
def __add__(self, delta):
|
self.increment(delta=delta)<EOL>return self<EOL>
|
Increment the counter with `delta`
:keyword delta: The delta to add to the counter
:type delta: int
|
f11597:c0:m3
|
def __sub__(self, delta):
|
self.decrement(delta=delta)<EOL>return self<EOL>
|
Decrement the counter with `delta`
:keyword delta: The delta to remove from the counter
:type delta: int
|
f11597:c0:m4
|
def start(self):
|
assert self._start is None, (<EOL>'<STR_LIT>')<EOL>self._last = self._start = time.time()<EOL>return self<EOL>
|
Start the timer and store the start time, this can only be executed
once per instance
It returns the timer instance so it can be chained when instantiating
the timer instance like this:
``timer = Timer('application_name').start()``
|
f11598:c0:m1
|
def send(self, subname, delta):
|
ms = delta * <NUM_LIT:1000><EOL>if ms > self.min_send_threshold:<EOL><INDENT>name = self._get_name(self.name, subname)<EOL>self.logger.info('<STR_LIT>', name, ms)<EOL>return statsd.Client._send(self, {name: '<STR_LIT>' % ms})<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>
|
Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword delta: The time delta (time.time() - time.time()) to report
:type delta: float
|
f11598:c0:m2
|
def intermediate(self, subname):
|
t = time.time()<EOL>response = self.send(subname, t - self._last)<EOL>self._last = t<EOL>return response<EOL>
|
Send the time that has passed since our last measurement
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
|
f11598:c0:m3
|
def stop(self, subname='<STR_LIT>'):
|
assert self._stop is None, (<EOL>'<STR_LIT>')<EOL>self._stop = time.time()<EOL>return self.send(subname, self._stop - self._start)<EOL>
|
Stop the timer and send the total since `start()` was run
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
|
f11598:c0:m4
|
def __enter__(self):
|
self.start()<EOL>return self<EOL>
|
Make a context manager out of self to measure time execution in a block
of code.
:return: statsd.timer.Timer
|
f11598:c0:m5
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
self.stop()<EOL>
|
Stop measuring time sending total metric, while exiting block of code.
:param exc_type:
:param exc_val:
:param exc_tb:
:return:
|
f11598:c0:m6
|
def decorate(self, function_or_name):
|
if callable(function_or_name):<EOL><INDENT>return self._decorate(function_or_name.__name__, function_or_name)<EOL><DEDENT>else:<EOL><INDENT>return partial(self._decorate, function_or_name)<EOL><DEDENT>
|
Decorate a function to time the execution
The method can be called with or without a name. If no name is given
the function defaults to the name of the function.
:keyword function_or_name: The name to post to or the function to wrap
>>> from statsd import Timer
>>> timer = Timer('application_name')
>>>
>>> @timer.decorate
... def some_function():
... # resulting timer name: application_name.some_function
... pass
>>>
>>> @timer.decorate('my_timer')
... def some_other_function():
... # resulting timer name: application_name.my_timer
... pass
|
f11598:c0:m8
|
@contextlib.contextmanager<EOL><INDENT>def time(self, subname=None, class_=None):<DEDENT>
|
if class_ is None:<EOL><INDENT>class_ = Timer<EOL><DEDENT>timer = self.get_client(subname, class_)<EOL>timer.start()<EOL>yield<EOL>timer.stop('<STR_LIT>')<EOL>
|
Returns a context manager to time execution of a block of code.
:keyword subname: The subname to report data to
:type subname: str
:keyword class_: The :class:`~statsd.client.Client` subclass to use
(e.g. :class:`~statsd.timer.Timer` or
:class:`~statsd.counter.Counter`)
:type class_: :class:`~statsd.client.Client`
>>> from statsd import Timer
>>> timer = Timer('application_name')
>>>
>>> with timer.time():
... # resulting timer name: application_name
... pass
>>>
>>>
>>> with timer.time('context_timer'):
... # resulting timer name: application_name.context_timer
... pass
|
f11598:c0:m9
|
def get_client(self, name=None, class_=None):
|
<EOL>name = self._get_name(self.name, name)<EOL>if not class_:<EOL><INDENT>class_ = self.__class__<EOL><DEDENT>return class_(<EOL>name=name,<EOL>connection=self.connection,<EOL>)<EOL>
|
Get a (sub-)client with a separate namespace
This way you can create a global/app based client with subclients
per class/function
:keyword name: The name to use, if the name for this client was `spam`
and the `name` argument is `eggs` than the resulting name will be
`spam.eggs`
:type name: str
:keyword class_: The :class:`~statsd.client.Client` subclass to use
(e.g. :class:`~statsd.timer.Timer` or
:class:`~statsd.counter.Counter`)
:type class_: :class:`~statsd.client.Client`
|
f11600:c0:m2
|
def get_average(self, name=None):
|
return self.get_client(name=name, class_=statsd.Average)<EOL>
|
Shortcut for getting an :class:`~statsd.average.Average` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
|
f11600:c0:m3
|
def get_counter(self, name=None):
|
return self.get_client(name=name, class_=statsd.Counter)<EOL>
|
Shortcut for getting a :class:`~statsd.counter.Counter` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
|
f11600:c0:m4
|
def get_gauge(self, name=None):
|
return self.get_client(name=name, class_=statsd.Gauge)<EOL>
|
Shortcut for getting a :class:`~statsd.gauge.Gauge` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
|
f11600:c0:m5
|
def get_raw(self, name=None):
|
return self.get_client(name=name, class_=statsd.Raw)<EOL>
|
Shortcut for getting a :class:`~statsd.raw.Raw` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
|
f11600:c0:m6
|
def get_timer(self, name=None):
|
return self.get_client(name=name, class_=statsd.Timer)<EOL>
|
Shortcut for getting a :class:`~statsd.timer.Timer` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
|
f11600:c0:m7
|
def send(self, subname, value):
|
name = self._get_name(self.name, subname)<EOL>self.logger.info('<STR_LIT>', name, value)<EOL>return statsd.Client._send(self, {name: '<STR_LIT>' % value})<EOL>
|
Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:keyword value: The raw value to send
|
f11602:c0:m0
|
def _send(self, subname, value):
|
name = self._get_name(self.name, subname)<EOL>self.logger.info('<STR_LIT>', name, value)<EOL>return statsd.Client._send(self, {name: '<STR_LIT>' % value})<EOL>
|
Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword value: The gauge value to send
|
f11603:c0:m0
|
def send(self, subname, value):
|
assert isinstance(value, compat.NUM_TYPES)<EOL>return self._send(subname, value)<EOL>
|
Send the data to statsd via self.connection
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword value: The gauge value to send
|
f11603:c0:m1
|
def increment(self, subname=None, delta=<NUM_LIT:1>):
|
delta = int(delta)<EOL>sign = "<STR_LIT:+>" if delta >= <NUM_LIT:0> else "<STR_LIT>"<EOL>return self._send(subname, "<STR_LIT>" % (sign, delta))<EOL>
|
Increment the gauge with `delta`
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword delta: The delta to add to the gauge
:type delta: int
>>> gauge = Gauge('application_name')
>>> gauge.increment('gauge_name', 10)
True
>>> gauge.increment(delta=10)
True
>>> gauge.increment('gauge_name')
True
|
f11603:c0:m2
|
def decrement(self, subname=None, delta=<NUM_LIT:1>):
|
delta = -int(delta)<EOL>sign = "<STR_LIT:+>" if delta >= <NUM_LIT:0> else "<STR_LIT>"<EOL>return self._send(subname, "<STR_LIT>" % (sign, delta))<EOL>
|
Decrement the gauge with `delta`
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword delta: The delta to remove from the gauge
:type delta: int
>>> gauge = Gauge('application_name')
>>> gauge.decrement('gauge_name', 10)
True
>>> gauge.decrement(delta=10)
True
>>> gauge.decrement('gauge_name')
True
|
f11603:c0:m3
|
def __add__(self, delta):
|
self.increment(delta=delta)<EOL>return self<EOL>
|
Increment the gauge with `delta`
:keyword delta: The delta to add to the gauge
:type delta: int
>>> gauge = Gauge('application_name')
>>> gauge += 5
|
f11603:c0:m4
|
def __sub__(self, delta):
|
self.decrement(delta=delta)<EOL>return self<EOL>
|
Decrement the gauge with `delta`
:keyword delta: The delta to remove from the gauge
:type delta: int
>>> gauge = Gauge('application_name')
>>> gauge -= 5
|
f11603:c0:m5
|
def set(self, subname, value):
|
assert isinstance(value, compat.NUM_TYPES)<EOL>if value < <NUM_LIT:0>:<EOL><INDENT>self._send(subname, <NUM_LIT:0>)<EOL><DEDENT>return self._send(subname, value)<EOL>
|
Set the data ignoring the sign, ie set("test", -1) will set "test"
exactly to -1 (not decrement it by 1)
See https://github.com/etsy/statsd/blob/master/docs/metric_types.md
"Adding a sign to the gauge value will change the value, rather
than setting it.
gaugor:-10|g
gaugor:+4|g
So if gaugor was 333, those commands would set it to 333 - 10 + 4, or
327.
Note: This implies you can't explicitly set a gauge to a negative
number without first setting it to zero."
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
:keyword value: The new gauge value
|
f11603:c0:m6
|
def integers(num, minimum, maximum, base=<NUM_LIT:10>):<EOL>
|
function = '<STR_LIT>'<EOL>num, minimum, maximum = list(map(int, [num, minimum, maximum]))<EOL>if (<NUM_LIT:1> <= num <= <NUM_LIT:10> ** <NUM_LIT:4>) is False:<EOL><INDENT>print('<STR_LIT>' % num)<EOL>return<EOL><DEDENT>if (-<NUM_LIT:10> ** <NUM_LIT:9> <= minimum <= <NUM_LIT:10> ** <NUM_LIT:9>) is False:<EOL><INDENT>print('<STR_LIT>' % minimum)<EOL>return<EOL><DEDENT>if (-<NUM_LIT:10> ** <NUM_LIT:9> <= maximum <= <NUM_LIT:10> ** <NUM_LIT:9>) is False:<EOL><INDENT>print('<STR_LIT>' % maximum)<EOL>return<EOL><DEDENT>if maximum < minimum:<EOL><INDENT>print('<STR_LIT>' % (maximum, minimum))<EOL>return<EOL><DEDENT>base = int(base)<EOL>if base not in [<NUM_LIT:2>, <NUM_LIT:8>, <NUM_LIT:10>, <NUM_LIT:16>]:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>opts = {'<STR_LIT>': num,<EOL>'<STR_LIT>': minimum,<EOL>'<STR_LIT>': maximum,<EOL>'<STR_LIT>': <NUM_LIT:1>,<EOL>'<STR_LIT>': base,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>integers = get_http(RANDOM_URL, function, opts)<EOL>integers_arr = str_to_arr(integers)<EOL>return integers_arr<EOL>
|
Random integers within specified interval.
The integer generator generates truly random integers in the specified
interval.
Parameters
----------
num : int, bounds=[1, 1E4]
Total number of integers in returned array.
minimum : int, bounds=[-1E9, 1E9]
Minimum value (inclusive) of returned integers.
maximum : int, bounds=[-1E9, 1E9]
Maximum value (inclusive) of returned integers.
base: int, values=[2, 8, 10, 16], default=10
Base used to print numbers in array, the default is decimal
representation (base=10).
Returns
-------
integers : array
A 1D numpy array containing integers between the specified
bounds.
Examples
--------
Generate an array of 10 integers with values between -100 and 100,
inclusive:
>>> integers(10, -100, 100)
A coin toss, where heads=1 and tails=0, with multiple flips (flips should
be an odd number):
>>> sum(integers(5, 0, 1))
|
f11607:m0
|
def sequence(minimum, maximum):
|
function = '<STR_LIT>'<EOL>opts = {'<STR_LIT>': minimum,<EOL>'<STR_LIT>': maximum,<EOL>'<STR_LIT>': <NUM_LIT:1>,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>deal = get_http(RANDOM_URL, function, opts)<EOL>deal_arr = str_to_arr(deal)<EOL>return deal_arr<EOL>
|
Randomize a sequence of integers.
|
f11607:m1
|
def string(num, length, digits=False, upper=True, lower=True, unique=False):
|
function = '<STR_LIT>'<EOL>digits = convert(digits)<EOL>upper = convert(upper)<EOL>lower = convert(lower)<EOL>unique = convert(unique)<EOL>opts = {'<STR_LIT>': num,<EOL>'<STR_LIT>': length,<EOL>'<STR_LIT>': digits,<EOL>'<STR_LIT>': upper,<EOL>'<STR_LIT>': lower,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>seq = get_http(RANDOM_URL, function, opts)<EOL>seq = seq.strip().split('<STR_LIT:\n>') <EOL>return seq<EOL>
|
Random strings.
|
f11607:m2
|
def quota(ip=None):
|
<EOL>url = '<STR_LIT>'<EOL>data = urlopen(url)<EOL>credit = int(data.read().strip())<EOL>if data.code == <NUM_LIT:200>:<EOL><INDENT>return credit<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % data.code<EOL><DEDENT>
|
Check your quota.
|
f11607:m3
|
def get_http(base_url, function, opts):
|
url = (os.path.join(base_url, function) + '<STR_LIT>' + urlencode(opts))<EOL>data = urlopen(url)<EOL>if data.code != <NUM_LIT:200>:<EOL><INDENT>raise ValueError("<STR_LIT>" + str(data.code))<EOL><DEDENT>return data.read()<EOL>
|
HTTP request generator.
|
f11607:m4
|
def str_to_arr(string):
|
arr = np.fromstring(string, sep='<STR_LIT:\n>', dtype='<STR_LIT:int>')<EOL>return arr<EOL>
|
Converts string to numpy array.
|
f11607:m5
|
def language_to_locale(language):
|
tokens = language.split('<STR_LIT:->')<EOL>if len(tokens) == <NUM_LIT:1>:<EOL><INDENT>return tokens[<NUM_LIT:0>]<EOL><DEDENT>return "<STR_LIT>" % (tokens[<NUM_LIT:0>], tokens[<NUM_LIT:1>].upper())<EOL>
|
Converts django's `LANGUAGE_CODE` settings to a proper locale code.
|
f11627:m0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.