id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
242,800 | cdeboever3/cdpybio | cdpybio/star.py | _make_sj_out_dict | def _make_sj_out_dict(fns, jxns=None, define_sample_name=None):
"""Read multiple sj_outs, return dict with keys as sample names and values
as sj_out dataframes.
Parameters
----------
fns : list of strs of filenames or file handles
List of filename of the SJ.out.tab files to read in
jxns : set
If provided, only keep junctions in this set.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. The sample names
will be used as the column names. If this is not provided, the columns
will be named as the input files.
Returns
-------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
"""
if define_sample_name == None:
define_sample_name = lambda x: x
else:
assert len(set([define_sample_name(x) for x in fns])) == len(fns)
sj_outD = dict()
for fn in fns:
sample = define_sample_name(fn)
df = read_sj_out_tab(fn)
# Remove any junctions that don't have any uniquely mapped junction
# reads. Even if a junction passes the cutoff in other samples, we are
# only concerned with unique counts.
df = df[df.unique_junction_reads > 0]
index = (df.chrom + ':' + df.start.astype(str) + '-'
+ df.end.astype(str))
assert len(index) == len(set(index))
df.index = index
# If jxns is provided, only keep those.
if jxns:
df = df.ix[set(df.index) & jxns]
sj_outD[sample] = df
return sj_outD | python | def _make_sj_out_dict(fns, jxns=None, define_sample_name=None):
"""Read multiple sj_outs, return dict with keys as sample names and values
as sj_out dataframes.
Parameters
----------
fns : list of strs of filenames or file handles
List of filename of the SJ.out.tab files to read in
jxns : set
If provided, only keep junctions in this set.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. The sample names
will be used as the column names. If this is not provided, the columns
will be named as the input files.
Returns
-------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
"""
if define_sample_name == None:
define_sample_name = lambda x: x
else:
assert len(set([define_sample_name(x) for x in fns])) == len(fns)
sj_outD = dict()
for fn in fns:
sample = define_sample_name(fn)
df = read_sj_out_tab(fn)
# Remove any junctions that don't have any uniquely mapped junction
# reads. Even if a junction passes the cutoff in other samples, we are
# only concerned with unique counts.
df = df[df.unique_junction_reads > 0]
index = (df.chrom + ':' + df.start.astype(str) + '-'
+ df.end.astype(str))
assert len(index) == len(set(index))
df.index = index
# If jxns is provided, only keep those.
if jxns:
df = df.ix[set(df.index) & jxns]
sj_outD[sample] = df
return sj_outD | [
"def",
"_make_sj_out_dict",
"(",
"fns",
",",
"jxns",
"=",
"None",
",",
"define_sample_name",
"=",
"None",
")",
":",
"if",
"define_sample_name",
"==",
"None",
":",
"define_sample_name",
"=",
"lambda",
"x",
":",
"x",
"else",
":",
"assert",
"len",
"(",
"set",... | Read multiple sj_outs, return dict with keys as sample names and values
as sj_out dataframes.
Parameters
----------
fns : list of strs of filenames or file handles
List of filename of the SJ.out.tab files to read in
jxns : set
If provided, only keep junctions in this set.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. The sample names
will be used as the column names. If this is not provided, the columns
will be named as the input files.
Returns
-------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes | [
"Read",
"multiple",
"sj_outs",
"return",
"dict",
"with",
"keys",
"as",
"sample",
"names",
"and",
"values",
"as",
"sj_out",
"dataframes",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L89-L135 |
242,801 | cdeboever3/cdpybio | cdpybio/star.py | _make_sj_out_panel | def _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff=20):
"""Filter junctions from many sj_out files and make panel.
Parameters
----------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
total_jxn_cov_cutoff : int
If the unique read coverage of a junction summed over all samples is not
greater than or equal to this value, the junction will not be included
in the final output.
Returns
-------
sj_outP : pandas.Panel
Panel where each dataframe corresponds to an sj_out file filtered to
remove low coverage junctions. Each dataframe has COUNT_COLS =
('unique_junction_reads', 'multimap_junction_reads', 'max_overhang')
annotDF : pandas.DataFrame
Dataframe with values ANNOTATION_COLS = ('chrom', 'start',
'end', 'intron_motif', 'annotated') that are otherwise
duplicated in the panel.
"""
# num_jxns = dict()
# # set of all junctions
# jxnS = reduce(lambda x,y: set(x) | set(y),
# [ sj_outD[k].index for k in sj_outD.keys() ])
# jxn_keepS = set()
# jxn_setsD = dict()
# for k in sj_outD.keys():
# jxn_setsD[k] = frozenset(sj_outD[k].index)
# for j in jxnS:
# if sum([ sj_outD[k].ix[j,'unique_junction_reads'] for k in sj_outD.keys()
# if j in jxn_setsD[k] ]) >= total_jxn_cov_cutoff:
# jxn_keepS.add(j)
# for k in sj_outD.keys():
# sj_outD[k] = sj_outD[k].ix[jxn_keepS]
sj_outP = pd.Panel(sj_outD)
for col in ['unique_junction_reads', 'multimap_junction_reads',
'max_overhang']:
sj_outP.ix[:,:,col] = sj_outP.ix[:,:,col].fillna(0)
# Some dataframes will be missing information like intron_motif etc. for
# junctions that were not observed in that sample. The info is somewhere in
# the panel though so we can get it.
annotDF = reduce(pd.DataFrame.combine_first,
[ sj_outP.ix[item,:,ANNOTATION_COLS].dropna() for item in
sj_outP.items ])
annotDF['start'] = annotDF['start'].astype(int)
annotDF['end'] = annotDF['end'].astype(int)
annotDF['annotated'] = annotDF['annotated'].astype(bool)
# Sort annotation and panel
annotDF = annotDF.sort_values(by=['chrom', 'start', 'end'])
sj_outP = sj_outP.ix[:, annotDF.index, :]
sj_outP = sj_outP.ix[:,:,COUNT_COLS].astype(int)
return sj_outP, annotDF | python | def _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff=20):
"""Filter junctions from many sj_out files and make panel.
Parameters
----------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
total_jxn_cov_cutoff : int
If the unique read coverage of a junction summed over all samples is not
greater than or equal to this value, the junction will not be included
in the final output.
Returns
-------
sj_outP : pandas.Panel
Panel where each dataframe corresponds to an sj_out file filtered to
remove low coverage junctions. Each dataframe has COUNT_COLS =
('unique_junction_reads', 'multimap_junction_reads', 'max_overhang')
annotDF : pandas.DataFrame
Dataframe with values ANNOTATION_COLS = ('chrom', 'start',
'end', 'intron_motif', 'annotated') that are otherwise
duplicated in the panel.
"""
# num_jxns = dict()
# # set of all junctions
# jxnS = reduce(lambda x,y: set(x) | set(y),
# [ sj_outD[k].index for k in sj_outD.keys() ])
# jxn_keepS = set()
# jxn_setsD = dict()
# for k in sj_outD.keys():
# jxn_setsD[k] = frozenset(sj_outD[k].index)
# for j in jxnS:
# if sum([ sj_outD[k].ix[j,'unique_junction_reads'] for k in sj_outD.keys()
# if j in jxn_setsD[k] ]) >= total_jxn_cov_cutoff:
# jxn_keepS.add(j)
# for k in sj_outD.keys():
# sj_outD[k] = sj_outD[k].ix[jxn_keepS]
sj_outP = pd.Panel(sj_outD)
for col in ['unique_junction_reads', 'multimap_junction_reads',
'max_overhang']:
sj_outP.ix[:,:,col] = sj_outP.ix[:,:,col].fillna(0)
# Some dataframes will be missing information like intron_motif etc. for
# junctions that were not observed in that sample. The info is somewhere in
# the panel though so we can get it.
annotDF = reduce(pd.DataFrame.combine_first,
[ sj_outP.ix[item,:,ANNOTATION_COLS].dropna() for item in
sj_outP.items ])
annotDF['start'] = annotDF['start'].astype(int)
annotDF['end'] = annotDF['end'].astype(int)
annotDF['annotated'] = annotDF['annotated'].astype(bool)
# Sort annotation and panel
annotDF = annotDF.sort_values(by=['chrom', 'start', 'end'])
sj_outP = sj_outP.ix[:, annotDF.index, :]
sj_outP = sj_outP.ix[:,:,COUNT_COLS].astype(int)
return sj_outP, annotDF | [
"def",
"_make_sj_out_panel",
"(",
"sj_outD",
",",
"total_jxn_cov_cutoff",
"=",
"20",
")",
":",
"# num_jxns = dict()",
"# # set of all junctions",
"# jxnS = reduce(lambda x,y: set(x) | set(y),",
"# [ sj_outD[k].index for k in sj_outD.keys() ])",
"# jxn_keepS = set()",
"# j... | Filter junctions from many sj_out files and make panel.
Parameters
----------
sj_outD : dict
Dict whose keys are sample names and values are sj_out dataframes
total_jxn_cov_cutoff : int
If the unique read coverage of a junction summed over all samples is not
greater than or equal to this value, the junction will not be included
in the final output.
Returns
-------
sj_outP : pandas.Panel
Panel where each dataframe corresponds to an sj_out file filtered to
remove low coverage junctions. Each dataframe has COUNT_COLS =
('unique_junction_reads', 'multimap_junction_reads', 'max_overhang')
annotDF : pandas.DataFrame
Dataframe with values ANNOTATION_COLS = ('chrom', 'start',
'end', 'intron_motif', 'annotated') that are otherwise
duplicated in the panel. | [
"Filter",
"junctions",
"from",
"many",
"sj_out",
"files",
"and",
"make",
"panel",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L137-L200 |
242,802 | cdeboever3/cdpybio | cdpybio/star.py | read_external_annotation | def read_external_annotation(fn):
"""Read file with junctions from some database. This does not have to be the
same splice junction database used with STAR.
Parameters
----------
fn : filename str
File with splice junctions from annotation. The file should have a
header and contain the following columns: 'gene', 'chrom', 'start',
'end', 'strand', 'chrom:start', 'chrom:end', 'donor', 'acceptor',
'intron'.
Returns
-------
extDF : pandas.DataFrame
DataFrame indexed by splice junction
stats : list of strings
Human readable statistics about the external database.
"""
assert os.path.exists(fn)
extDF = pd.read_table(fn, index_col=0, header=0)
total_num = extDF.shape[0]
# In rare cases, a splice junction might be used by more than one gene. For
# my purposes, these cases are confounding, so I will remove all such splice
# junctions.
intron_count = extDF.intron.value_counts()
extDF['intron_count'] = extDF.intron.apply(lambda x: intron_count.ix[x])
extDF = extDF[extDF.intron_count == 1]
extDF = extDF.drop('intron_count', axis=1)
stats = []
stats.append('External database stats')
stats.append('Read external annotation\t{}'.format(fn))
stats.append('Total number of junctions\t{:,}'.format(total_num))
stats.append(('Number of junctions used in only one '
'gene\t{:,}').format(extDF.shape[0]))
return extDF, stats | python | def read_external_annotation(fn):
"""Read file with junctions from some database. This does not have to be the
same splice junction database used with STAR.
Parameters
----------
fn : filename str
File with splice junctions from annotation. The file should have a
header and contain the following columns: 'gene', 'chrom', 'start',
'end', 'strand', 'chrom:start', 'chrom:end', 'donor', 'acceptor',
'intron'.
Returns
-------
extDF : pandas.DataFrame
DataFrame indexed by splice junction
stats : list of strings
Human readable statistics about the external database.
"""
assert os.path.exists(fn)
extDF = pd.read_table(fn, index_col=0, header=0)
total_num = extDF.shape[0]
# In rare cases, a splice junction might be used by more than one gene. For
# my purposes, these cases are confounding, so I will remove all such splice
# junctions.
intron_count = extDF.intron.value_counts()
extDF['intron_count'] = extDF.intron.apply(lambda x: intron_count.ix[x])
extDF = extDF[extDF.intron_count == 1]
extDF = extDF.drop('intron_count', axis=1)
stats = []
stats.append('External database stats')
stats.append('Read external annotation\t{}'.format(fn))
stats.append('Total number of junctions\t{:,}'.format(total_num))
stats.append(('Number of junctions used in only one '
'gene\t{:,}').format(extDF.shape[0]))
return extDF, stats | [
"def",
"read_external_annotation",
"(",
"fn",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
"extDF",
"=",
"pd",
".",
"read_table",
"(",
"fn",
",",
"index_col",
"=",
"0",
",",
"header",
"=",
"0",
")",
"total_num",
"=",
"extDF",... | Read file with junctions from some database. This does not have to be the
same splice junction database used with STAR.
Parameters
----------
fn : filename str
File with splice junctions from annotation. The file should have a
header and contain the following columns: 'gene', 'chrom', 'start',
'end', 'strand', 'chrom:start', 'chrom:end', 'donor', 'acceptor',
'intron'.
Returns
-------
extDF : pandas.DataFrame
DataFrame indexed by splice junction
stats : list of strings
Human readable statistics about the external database. | [
"Read",
"file",
"with",
"junctions",
"from",
"some",
"database",
".",
"This",
"does",
"not",
"have",
"to",
"be",
"the",
"same",
"splice",
"junction",
"database",
"used",
"with",
"STAR",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L202-L242 |
242,803 | cdeboever3/cdpybio | cdpybio/star.py | combine_sj_out | def combine_sj_out(
fns,
external_db,
total_jxn_cov_cutoff=20,
define_sample_name=None,
verbose=False,
):
"""Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list of strings
Filenames of SJ.out.tab files to combine.
external_db : str
Filename of splice junction information from external database. The file
should have a header and contained the following columns 'gene',
'chrom', 'start', 'end', 'strand', 'chrom:start', 'chrom:end', 'donor',
'acceptor', 'intron'.
total_jxn_cov_cutoff : int
Discard junctions with less than this many reads summed over all
samples.
define_sample_name : function
A function mapping the SJ.out.tab filenames to sample names.
Returns
-------
countDF : pandas.DataFrame
Number of unique junction spanning reads for each junction that passed
filtering criteria.
annotDF : pandas.DataFrame
Annotation information for junctions that passed filtering criteria.
stats : list of strings
Human readable statistics.
"""
if verbose:
import sys
# I'll start by figuring out which junctions we will keep.
counts = _total_jxn_counts(fns)
jxns = set(counts[counts >= total_jxn_cov_cutoff].index)
if verbose:
sys.stderr.write('Counting done\n')
stats = []
sj_outD = _make_sj_out_dict(fns, jxns=jxns,
define_sample_name=define_sample_name)
stats.append('Number of junctions in SJ.out file per sample')
for k in sj_outD.keys():
stats.append('{0}\t{1:,}'.format(k, sj_outD[k].shape[0]))
stats.append('')
if verbose:
sys.stderr.write('Dict done\n')
sj_outP, annotDF = _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff)
stats.append('SJ.out panel size\t{0}'.format(sj_outP.shape))
stats.append('')
if verbose:
sys.stderr.write('Panel done\n')
extDF, ext_stats = read_external_annotation(external_db)
stats += ext_stats
stats.append('')
if verbose:
sys.stderr.write('DB read done\n')
countsDF, annotDF, filter_stats = _filter_jxns_donor_acceptor(sj_outP,
annotDF,
extDF)
if verbose:
sys.stderr.write('Filter done\n')
annotDF = _find_novel_donor_acceptor_dist(annotDF, extDF)
if verbose:
sys.stderr.write('Dist done\n')
stats += filter_stats
return countsDF, annotDF, stats | python | def combine_sj_out(
fns,
external_db,
total_jxn_cov_cutoff=20,
define_sample_name=None,
verbose=False,
):
"""Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list of strings
Filenames of SJ.out.tab files to combine.
external_db : str
Filename of splice junction information from external database. The file
should have a header and contained the following columns 'gene',
'chrom', 'start', 'end', 'strand', 'chrom:start', 'chrom:end', 'donor',
'acceptor', 'intron'.
total_jxn_cov_cutoff : int
Discard junctions with less than this many reads summed over all
samples.
define_sample_name : function
A function mapping the SJ.out.tab filenames to sample names.
Returns
-------
countDF : pandas.DataFrame
Number of unique junction spanning reads for each junction that passed
filtering criteria.
annotDF : pandas.DataFrame
Annotation information for junctions that passed filtering criteria.
stats : list of strings
Human readable statistics.
"""
if verbose:
import sys
# I'll start by figuring out which junctions we will keep.
counts = _total_jxn_counts(fns)
jxns = set(counts[counts >= total_jxn_cov_cutoff].index)
if verbose:
sys.stderr.write('Counting done\n')
stats = []
sj_outD = _make_sj_out_dict(fns, jxns=jxns,
define_sample_name=define_sample_name)
stats.append('Number of junctions in SJ.out file per sample')
for k in sj_outD.keys():
stats.append('{0}\t{1:,}'.format(k, sj_outD[k].shape[0]))
stats.append('')
if verbose:
sys.stderr.write('Dict done\n')
sj_outP, annotDF = _make_sj_out_panel(sj_outD, total_jxn_cov_cutoff)
stats.append('SJ.out panel size\t{0}'.format(sj_outP.shape))
stats.append('')
if verbose:
sys.stderr.write('Panel done\n')
extDF, ext_stats = read_external_annotation(external_db)
stats += ext_stats
stats.append('')
if verbose:
sys.stderr.write('DB read done\n')
countsDF, annotDF, filter_stats = _filter_jxns_donor_acceptor(sj_outP,
annotDF,
extDF)
if verbose:
sys.stderr.write('Filter done\n')
annotDF = _find_novel_donor_acceptor_dist(annotDF, extDF)
if verbose:
sys.stderr.write('Dist done\n')
stats += filter_stats
return countsDF, annotDF, stats | [
"def",
"combine_sj_out",
"(",
"fns",
",",
"external_db",
",",
"total_jxn_cov_cutoff",
"=",
"20",
",",
"define_sample_name",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
")",
":",
"if",
"verbose",
":",
"import",
"sys",
"# I'll start by figuring out which junctio... | Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list of strings
Filenames of SJ.out.tab files to combine.
external_db : str
Filename of splice junction information from external database. The file
should have a header and contained the following columns 'gene',
'chrom', 'start', 'end', 'strand', 'chrom:start', 'chrom:end', 'donor',
'acceptor', 'intron'.
total_jxn_cov_cutoff : int
Discard junctions with less than this many reads summed over all
samples.
define_sample_name : function
A function mapping the SJ.out.tab filenames to sample names.
Returns
-------
countDF : pandas.DataFrame
Number of unique junction spanning reads for each junction that passed
filtering criteria.
annotDF : pandas.DataFrame
Annotation information for junctions that passed filtering criteria.
stats : list of strings
Human readable statistics. | [
"Combine",
"SJ",
".",
"out",
".",
"tab",
"files",
"from",
"STAR",
"by",
"filtering",
"based",
"on",
"coverage",
"and",
"comparing",
"to",
"an",
"external",
"annotation",
"to",
"discover",
"novel",
"junctions",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L451-L533 |
242,804 | cdeboever3/cdpybio | cdpybio/star.py | _total_jxn_counts | def _total_jxn_counts(fns):
"""Count the total unique coverage junction for junctions in a set of
SJ.out.tab files."""
df = pd.read_table(fns[0], header=None, names=COLUMN_NAMES)
df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' +
df.end.astype(int).astype(str))
counts = df.unique_junction_reads
for fn in fns[1:]:
df = pd.read_table(fn, header=None, names=COLUMN_NAMES)
df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' +
df.end.astype(int).astype(str))
counts = counts.add(df.unique_junction_reads, fill_value=0)
return counts | python | def _total_jxn_counts(fns):
"""Count the total unique coverage junction for junctions in a set of
SJ.out.tab files."""
df = pd.read_table(fns[0], header=None, names=COLUMN_NAMES)
df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' +
df.end.astype(int).astype(str))
counts = df.unique_junction_reads
for fn in fns[1:]:
df = pd.read_table(fn, header=None, names=COLUMN_NAMES)
df.index = (df.chrom + ':' + df.start.astype(int).astype(str) + '-' +
df.end.astype(int).astype(str))
counts = counts.add(df.unique_junction_reads, fill_value=0)
return counts | [
"def",
"_total_jxn_counts",
"(",
"fns",
")",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"fns",
"[",
"0",
"]",
",",
"header",
"=",
"None",
",",
"names",
"=",
"COLUMN_NAMES",
")",
"df",
".",
"index",
"=",
"(",
"df",
".",
"chrom",
"+",
"':'",
"+"... | Count the total unique coverage junction for junctions in a set of
SJ.out.tab files. | [
"Count",
"the",
"total",
"unique",
"coverage",
"junction",
"for",
"junctions",
"in",
"a",
"set",
"of",
"SJ",
".",
"out",
".",
"tab",
"files",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L535-L547 |
242,805 | cdeboever3/cdpybio | cdpybio/star.py | _make_splice_targets_dict | def _make_splice_targets_dict(df, feature, strand):
"""Make dict mapping each donor to the location of all acceptors it splices
to or each acceptor to all donors it splices from.
Parameters
----------
df : pandas.DataFrame
Dataframe with splice junction information from external database
containing columns 'gene', 'chrom', 'start', 'end', 'strand',
'chrom:start', 'chrom:end', 'donor', 'acceptor', 'intron'.
feature : string
Either 'donor' or 'acceptor'.
strand : string
Either '+' or '-'.
Returns
-------
d : dict
If feature='donor', dict whose keys are all distinct donors in df and
whose values are the distinct locations (integers) of the acceptors that
donor splices to in a numpy array. If feature='acceptor', dict whose
keys are all distinct acceptors in df and whose values are the distinct
locations (integers) of the donors that acceptor splices from in a numpy
array.
"""
g = df[df.strand == strand].groupby(feature)
d = dict()
if strand == '+':
if feature == 'donor':
target = 'end'
if feature == 'acceptor':
target = 'start'
if strand == '-':
if feature == 'donor':
target = 'start'
if feature == 'acceptor':
target = 'end'
for k in g.groups.keys():
d[k] = np.array(list(set(df.ix[g.groups[k], target])))
d[k].sort()
return d | python | def _make_splice_targets_dict(df, feature, strand):
"""Make dict mapping each donor to the location of all acceptors it splices
to or each acceptor to all donors it splices from.
Parameters
----------
df : pandas.DataFrame
Dataframe with splice junction information from external database
containing columns 'gene', 'chrom', 'start', 'end', 'strand',
'chrom:start', 'chrom:end', 'donor', 'acceptor', 'intron'.
feature : string
Either 'donor' or 'acceptor'.
strand : string
Either '+' or '-'.
Returns
-------
d : dict
If feature='donor', dict whose keys are all distinct donors in df and
whose values are the distinct locations (integers) of the acceptors that
donor splices to in a numpy array. If feature='acceptor', dict whose
keys are all distinct acceptors in df and whose values are the distinct
locations (integers) of the donors that acceptor splices from in a numpy
array.
"""
g = df[df.strand == strand].groupby(feature)
d = dict()
if strand == '+':
if feature == 'donor':
target = 'end'
if feature == 'acceptor':
target = 'start'
if strand == '-':
if feature == 'donor':
target = 'start'
if feature == 'acceptor':
target = 'end'
for k in g.groups.keys():
d[k] = np.array(list(set(df.ix[g.groups[k], target])))
d[k].sort()
return d | [
"def",
"_make_splice_targets_dict",
"(",
"df",
",",
"feature",
",",
"strand",
")",
":",
"g",
"=",
"df",
"[",
"df",
".",
"strand",
"==",
"strand",
"]",
".",
"groupby",
"(",
"feature",
")",
"d",
"=",
"dict",
"(",
")",
"if",
"strand",
"==",
"'+'",
":"... | Make dict mapping each donor to the location of all acceptors it splices
to or each acceptor to all donors it splices from.
Parameters
----------
df : pandas.DataFrame
Dataframe with splice junction information from external database
containing columns 'gene', 'chrom', 'start', 'end', 'strand',
'chrom:start', 'chrom:end', 'donor', 'acceptor', 'intron'.
feature : string
Either 'donor' or 'acceptor'.
strand : string
Either '+' or '-'.
Returns
-------
d : dict
If feature='donor', dict whose keys are all distinct donors in df and
whose values are the distinct locations (integers) of the acceptors that
donor splices to in a numpy array. If feature='acceptor', dict whose
keys are all distinct acceptors in df and whose values are the distinct
locations (integers) of the donors that acceptor splices from in a numpy
array. | [
"Make",
"dict",
"mapping",
"each",
"donor",
"to",
"the",
"location",
"of",
"all",
"acceptors",
"it",
"splices",
"to",
"or",
"each",
"acceptor",
"to",
"all",
"donors",
"it",
"splices",
"from",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L549-L593 |
242,806 | cdeboever3/cdpybio | cdpybio/star.py | _read_log | def _read_log(fn, define_sample_name=None):
"""Read STAR Log.final.out file.
Parameters
----------
fn : string
Path to Log.final.out file.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. The sample name
will be used as the column name. If not provided, the column name will
be the filename.
Returns
-------
df : pandas.DataFrame
DataFrame with info from log file.
"""
if define_sample_name == None:
define_sample_name = lambda x: x
df = pd.read_table(fn, '|', header=None).dropna()
df.index = df.ix[:,0].apply(lambda x: x.strip())
df = pd.DataFrame(df.ix[:,1].apply(lambda x: x.strip()))
if define_sample_name:
df.columns = [define_sample_name(fn)]
else:
df.columns = [fn]
return df | python | def _read_log(fn, define_sample_name=None):
"""Read STAR Log.final.out file.
Parameters
----------
fn : string
Path to Log.final.out file.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. The sample name
will be used as the column name. If not provided, the column name will
be the filename.
Returns
-------
df : pandas.DataFrame
DataFrame with info from log file.
"""
if define_sample_name == None:
define_sample_name = lambda x: x
df = pd.read_table(fn, '|', header=None).dropna()
df.index = df.ix[:,0].apply(lambda x: x.strip())
df = pd.DataFrame(df.ix[:,1].apply(lambda x: x.strip()))
if define_sample_name:
df.columns = [define_sample_name(fn)]
else:
df.columns = [fn]
return df | [
"def",
"_read_log",
"(",
"fn",
",",
"define_sample_name",
"=",
"None",
")",
":",
"if",
"define_sample_name",
"==",
"None",
":",
"define_sample_name",
"=",
"lambda",
"x",
":",
"x",
"df",
"=",
"pd",
".",
"read_table",
"(",
"fn",
",",
"'|'",
",",
"header",
... | Read STAR Log.final.out file.
Parameters
----------
fn : string
Path to Log.final.out file.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. The sample name
will be used as the column name. If not provided, the column name will
be the filename.
Returns
-------
df : pandas.DataFrame
DataFrame with info from log file. | [
"Read",
"STAR",
"Log",
".",
"final",
".",
"out",
"file",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L755-L784 |
242,807 | cdeboever3/cdpybio | cdpybio/star.py | make_logs_df | def make_logs_df(fns, define_sample_name=None):
"""Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. The sample names
will be used as the column names. If this is not provided, the columns
will be named as the input files.
Returns
-------
df : pandas.DataFrame
DataFrame with info from log file.
"""
dfs = []
for fn in fns:
dfs.append(_read_log(fn,
define_sample_name=define_sample_name))
df = pd.concat(dfs,axis=1)
df = df.T
for label in [
'Mapping speed, Million of reads per hour',
'Number of input reads',
'Average input read length',
'Uniquely mapped reads number',
'Average mapped length',
'Number of splices: Total',
'Number of splices: GT/AG',
'Number of splices: GC/AG',
'Number of splices: AT/AC',
'Number of splices: Non-canonical',
'Number of reads mapped to multiple loci',
'Number of reads mapped to too many loci']:
df[label] = df[label].astype(float)
for label in [
'Uniquely mapped reads %',
'Mismatch rate per base, %',
'Deletion rate per base',
'Insertion rate per base',
'% of reads mapped to multiple loci',
'% of reads mapped to too many loci',
'% of reads unmapped: too many mismatches',
'% of reads unmapped: too short',
'% of reads unmapped: other']:
df[label] = df[label].apply(lambda x: x.strip('%')).astype(float)
return df | python | def make_logs_df(fns, define_sample_name=None):
"""Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. The sample names
will be used as the column names. If this is not provided, the columns
will be named as the input files.
Returns
-------
df : pandas.DataFrame
DataFrame with info from log file.
"""
dfs = []
for fn in fns:
dfs.append(_read_log(fn,
define_sample_name=define_sample_name))
df = pd.concat(dfs,axis=1)
df = df.T
for label in [
'Mapping speed, Million of reads per hour',
'Number of input reads',
'Average input read length',
'Uniquely mapped reads number',
'Average mapped length',
'Number of splices: Total',
'Number of splices: GT/AG',
'Number of splices: GC/AG',
'Number of splices: AT/AC',
'Number of splices: Non-canonical',
'Number of reads mapped to multiple loci',
'Number of reads mapped to too many loci']:
df[label] = df[label].astype(float)
for label in [
'Uniquely mapped reads %',
'Mismatch rate per base, %',
'Deletion rate per base',
'Insertion rate per base',
'% of reads mapped to multiple loci',
'% of reads mapped to too many loci',
'% of reads unmapped: too many mismatches',
'% of reads unmapped: too short',
'% of reads unmapped: other']:
df[label] = df[label].apply(lambda x: x.strip('%')).astype(float)
return df | [
"def",
"make_logs_df",
"(",
"fns",
",",
"define_sample_name",
"=",
"None",
")",
":",
"dfs",
"=",
"[",
"]",
"for",
"fn",
"in",
"fns",
":",
"dfs",
".",
"append",
"(",
"_read_log",
"(",
"fn",
",",
"define_sample_name",
"=",
"define_sample_name",
")",
")",
... | Make pandas DataFrame from multiple STAR Log.final.out files.
Parameters
----------
fns : string
List of paths to Log.final.out files.
define_sample_name : function that takes string as input
Function mapping filename to sample name. For instance, you may have the
sample name in the path and use a regex to extract it. The sample names
will be used as the column names. If this is not provided, the columns
will be named as the input files.
Returns
-------
df : pandas.DataFrame
DataFrame with info from log file. | [
"Make",
"pandas",
"DataFrame",
"from",
"multiple",
"STAR",
"Log",
".",
"final",
".",
"out",
"files",
"."
] | 38efdf0e11d01bc00a135921cb91a19c03db5d5c | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/star.py#L786-L838 |
242,808 | mariocesar/pengbot | examples/bob.py | uptime | def uptime():
"""Uptime of the host machine"""
from datetime import timedelta
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_string = str(timedelta(seconds=uptime_seconds))
bob.says(uptime_string) | python | def uptime():
"""Uptime of the host machine"""
from datetime import timedelta
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_string = str(timedelta(seconds=uptime_seconds))
bob.says(uptime_string) | [
"def",
"uptime",
"(",
")",
":",
"from",
"datetime",
"import",
"timedelta",
"with",
"open",
"(",
"'/proc/uptime'",
",",
"'r'",
")",
"as",
"f",
":",
"uptime_seconds",
"=",
"float",
"(",
"f",
".",
"readline",
"(",
")",
".",
"split",
"(",
")",
"[",
"0",
... | Uptime of the host machine | [
"Uptime",
"of",
"the",
"host",
"machine"
] | 070854f92ac1314ee56f7f6cb9d27430b8f0fda8 | https://github.com/mariocesar/pengbot/blob/070854f92ac1314ee56f7f6cb9d27430b8f0fda8/examples/bob.py#L112-L120 |
242,809 | firstprayer/monsql | monsql/query.py | value_to_sql_str | def value_to_sql_str(v):
"""
transform a python variable to the appropriate representation in SQL
"""
if v is None:
return 'null'
if type(v) in (types.IntType, types.FloatType, types.LongType):
return str(v)
if type(v) in (types.StringType, types.UnicodeType):
return "'%s'" %(v.replace(u"'", u"\\'"))
if isinstance(v, datetime):
return "'%s'" %(v.strftime("%Y-%m-%d %H:%M:%S"))
if isinstance(v, date):
return "'%s'" %(v.strftime("%Y-%m-%d"))
return str(v) | python | def value_to_sql_str(v):
"""
transform a python variable to the appropriate representation in SQL
"""
if v is None:
return 'null'
if type(v) in (types.IntType, types.FloatType, types.LongType):
return str(v)
if type(v) in (types.StringType, types.UnicodeType):
return "'%s'" %(v.replace(u"'", u"\\'"))
if isinstance(v, datetime):
return "'%s'" %(v.strftime("%Y-%m-%d %H:%M:%S"))
if isinstance(v, date):
return "'%s'" %(v.strftime("%Y-%m-%d"))
return str(v) | [
"def",
"value_to_sql_str",
"(",
"v",
")",
":",
"if",
"v",
"is",
"None",
":",
"return",
"'null'",
"if",
"type",
"(",
"v",
")",
"in",
"(",
"types",
".",
"IntType",
",",
"types",
".",
"FloatType",
",",
"types",
".",
"LongType",
")",
":",
"return",
"st... | transform a python variable to the appropriate representation in SQL | [
"transform",
"a",
"python",
"variable",
"to",
"the",
"appropriate",
"representation",
"in",
"SQL"
] | 6285c15b574c8664046eae2edfeb548c7b173efd | https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/query.py#L51-L70 |
242,810 | fr33jc/bang | bang/config.py | find_component_tarball | def find_component_tarball(bucket, comp_name, comp_config):
"""
Returns True if the component tarball is found in the bucket.
Otherwise, returns False.
"""
values = {
'name': comp_name,
'version': comp_config['version'],
'platform': comp_config['platform'],
}
template = comp_config.get('archive_template')
if template:
key_name = template % values
else:
key_name = '%(name)s/%(name)s-%(version)s.tar.gz' % values
if not bucket.get_key(key_name):
log.error('%s not found' % key_name)
return False
return True | python | def find_component_tarball(bucket, comp_name, comp_config):
"""
Returns True if the component tarball is found in the bucket.
Otherwise, returns False.
"""
values = {
'name': comp_name,
'version': comp_config['version'],
'platform': comp_config['platform'],
}
template = comp_config.get('archive_template')
if template:
key_name = template % values
else:
key_name = '%(name)s/%(name)s-%(version)s.tar.gz' % values
if not bucket.get_key(key_name):
log.error('%s not found' % key_name)
return False
return True | [
"def",
"find_component_tarball",
"(",
"bucket",
",",
"comp_name",
",",
"comp_config",
")",
":",
"values",
"=",
"{",
"'name'",
":",
"comp_name",
",",
"'version'",
":",
"comp_config",
"[",
"'version'",
"]",
",",
"'platform'",
":",
"comp_config",
"[",
"'platform'... | Returns True if the component tarball is found in the bucket.
Otherwise, returns False. | [
"Returns",
"True",
"if",
"the",
"component",
"tarball",
"is",
"found",
"in",
"the",
"bucket",
"."
] | 8f000713f88d2a9a8c1193b63ca10a6578560c16 | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/config.py#L43-L62 |
242,811 | fr33jc/bang | bang/config.py | Config._prepare_servers | def _prepare_servers(self):
"""
Prepare the variables that are exposed to the servers.
Most attributes in the server config are used directly. However, due
to variations in how cloud providers treat regions and availability
zones, this method allows either the ``availability_zone`` or the
``region_name`` to be used as the target availability zone for a
server. If both are specified, then ``availability_zone`` is used. If
``availability_zone`` is not specified in the server config, then the
``region_name`` value is used as the target availability zone.
"""
stack = {
A.NAME: self[A.NAME],
A.VERSION: self[A.VERSION],
}
for server in self.get(R.SERVERS, []):
# default cloud values
if A.PROVIDER in server:
if A.server.LAUNCH_TIMEOUT not in server:
server[A.server.LAUNCH_TIMEOUT] = DEFAULT_LAUNCH_TIMEOUT_S
if A.server.POST_DELAY not in server:
server[A.server.POST_DELAY] = DEFAULT_LAUNCH_TIMEOUT_S
if A.server.AZ not in server:
server[A.server.AZ] = server[A.server.REGION]
# distribute the config scope attributes
svars = {
A.STACK: stack,
A.SERVER_CLASS: server[A.NAME],
}
for scope in server.get(A.server.SCOPES, []):
# allow scopes to be defined inline
if isinstance(scope, collections.Mapping):
svars.update(scope)
else:
svars[scope] = self[scope]
# make all of the launch-time attributes (e.g. disk_image_id,
# launch_timeout_s, ssh_key_name, etc...) available as facts in
# case you need them in a playbook.
sattrs = server.copy()
sattrs.pop(A.server.SCOPES, None)
svars[A.server.BANG_ATTRS] = sattrs
server[A.server.VARS] = svars | python | def _prepare_servers(self):
"""
Prepare the variables that are exposed to the servers.
Most attributes in the server config are used directly. However, due
to variations in how cloud providers treat regions and availability
zones, this method allows either the ``availability_zone`` or the
``region_name`` to be used as the target availability zone for a
server. If both are specified, then ``availability_zone`` is used. If
``availability_zone`` is not specified in the server config, then the
``region_name`` value is used as the target availability zone.
"""
stack = {
A.NAME: self[A.NAME],
A.VERSION: self[A.VERSION],
}
for server in self.get(R.SERVERS, []):
# default cloud values
if A.PROVIDER in server:
if A.server.LAUNCH_TIMEOUT not in server:
server[A.server.LAUNCH_TIMEOUT] = DEFAULT_LAUNCH_TIMEOUT_S
if A.server.POST_DELAY not in server:
server[A.server.POST_DELAY] = DEFAULT_LAUNCH_TIMEOUT_S
if A.server.AZ not in server:
server[A.server.AZ] = server[A.server.REGION]
# distribute the config scope attributes
svars = {
A.STACK: stack,
A.SERVER_CLASS: server[A.NAME],
}
for scope in server.get(A.server.SCOPES, []):
# allow scopes to be defined inline
if isinstance(scope, collections.Mapping):
svars.update(scope)
else:
svars[scope] = self[scope]
# make all of the launch-time attributes (e.g. disk_image_id,
# launch_timeout_s, ssh_key_name, etc...) available as facts in
# case you need them in a playbook.
sattrs = server.copy()
sattrs.pop(A.server.SCOPES, None)
svars[A.server.BANG_ATTRS] = sattrs
server[A.server.VARS] = svars | [
"def",
"_prepare_servers",
"(",
"self",
")",
":",
"stack",
"=",
"{",
"A",
".",
"NAME",
":",
"self",
"[",
"A",
".",
"NAME",
"]",
",",
"A",
".",
"VERSION",
":",
"self",
"[",
"A",
".",
"VERSION",
"]",
",",
"}",
"for",
"server",
"in",
"self",
".",
... | Prepare the variables that are exposed to the servers.
Most attributes in the server config are used directly. However, due
to variations in how cloud providers treat regions and availability
zones, this method allows either the ``availability_zone`` or the
``region_name`` to be used as the target availability zone for a
server. If both are specified, then ``availability_zone`` is used. If
``availability_zone`` is not specified in the server config, then the
``region_name`` value is used as the target availability zone. | [
"Prepare",
"the",
"variables",
"that",
"are",
"exposed",
"to",
"the",
"servers",
"."
] | 8f000713f88d2a9a8c1193b63ca10a6578560c16 | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/config.py#L308-L354 |
242,812 | fr33jc/bang | bang/config.py | Config._prepare_load_balancers | def _prepare_load_balancers(self):
"""
Prepare load balancer variables
"""
stack = {
A.NAME: self[A.NAME],
A.VERSION: self[A.VERSION],
}
for load_balancer in self.get(R.LOAD_BALANCERS, []):
svars = {A.STACK: stack}
load_balancer[A.loadbalancer.VARS] = svars | python | def _prepare_load_balancers(self):
"""
Prepare load balancer variables
"""
stack = {
A.NAME: self[A.NAME],
A.VERSION: self[A.VERSION],
}
for load_balancer in self.get(R.LOAD_BALANCERS, []):
svars = {A.STACK: stack}
load_balancer[A.loadbalancer.VARS] = svars | [
"def",
"_prepare_load_balancers",
"(",
"self",
")",
":",
"stack",
"=",
"{",
"A",
".",
"NAME",
":",
"self",
"[",
"A",
".",
"NAME",
"]",
",",
"A",
".",
"VERSION",
":",
"self",
"[",
"A",
".",
"VERSION",
"]",
",",
"}",
"for",
"load_balancer",
"in",
"... | Prepare load balancer variables | [
"Prepare",
"load",
"balancer",
"variables"
] | 8f000713f88d2a9a8c1193b63ca10a6578560c16 | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/config.py#L356-L367 |
242,813 | fr33jc/bang | bang/config.py | Config.prepare | def prepare(self):
"""
Reorganizes the data such that the deployment logic can find it all
where it expects to be.
The raw configuration file is intended to be as human-friendly as
possible partly through the following mechanisms:
- In order to minimize repetition, any attributes that are common
to all server configurations can be specified in the
``server_common_attributes`` stanza even though the stanza itself
does not map directly to a deployable resource.
- For reference locality, each security group stanza contains its
list of rules even though rules are actually created in a
separate stage from the groups themselves.
In order to make the :class:`Config` object more useful to the program
logic, this method performs the following transformations:
- Distributes the ``server_common_attributes`` among all the
members of the ``servers`` stanza.
- Extracts security group rules to a top-level key, and
interpolates all source and target values.
"""
# TODO: take server_common_attributes and disperse it among the various
# server stanzas
# First stage - turn all the dicts (SERVER, SECGROUP, DATABASE, LOADBAL)
# into lists now they're merged properly
for stanza_key, name_key in (
(R.SERVERS, A.server.NAME),
(R.SERVER_SECURITY_GROUPS, A.secgroup.NAME),
(R.LOAD_BALANCERS, A.loadbalancer.NAME),
(R.DATABASES, A.database.NAME),
(R.BUCKETS, A.NAME),
(R.QUEUES, A.NAME)):
self[stanza_key] = self._convert_to_list(stanza_key, name_key)
self._prepare_ssh_keys()
self._prepare_secgroups()
self._prepare_tags()
self._prepare_dbs()
self._prepare_servers()
self._prepare_load_balancers()
self._prepare_ansible() | python | def prepare(self):
"""
Reorganizes the data such that the deployment logic can find it all
where it expects to be.
The raw configuration file is intended to be as human-friendly as
possible partly through the following mechanisms:
- In order to minimize repetition, any attributes that are common
to all server configurations can be specified in the
``server_common_attributes`` stanza even though the stanza itself
does not map directly to a deployable resource.
- For reference locality, each security group stanza contains its
list of rules even though rules are actually created in a
separate stage from the groups themselves.
In order to make the :class:`Config` object more useful to the program
logic, this method performs the following transformations:
- Distributes the ``server_common_attributes`` among all the
members of the ``servers`` stanza.
- Extracts security group rules to a top-level key, and
interpolates all source and target values.
"""
# TODO: take server_common_attributes and disperse it among the various
# server stanzas
# First stage - turn all the dicts (SERVER, SECGROUP, DATABASE, LOADBAL)
# into lists now they're merged properly
for stanza_key, name_key in (
(R.SERVERS, A.server.NAME),
(R.SERVER_SECURITY_GROUPS, A.secgroup.NAME),
(R.LOAD_BALANCERS, A.loadbalancer.NAME),
(R.DATABASES, A.database.NAME),
(R.BUCKETS, A.NAME),
(R.QUEUES, A.NAME)):
self[stanza_key] = self._convert_to_list(stanza_key, name_key)
self._prepare_ssh_keys()
self._prepare_secgroups()
self._prepare_tags()
self._prepare_dbs()
self._prepare_servers()
self._prepare_load_balancers()
self._prepare_ansible() | [
"def",
"prepare",
"(",
"self",
")",
":",
"# TODO: take server_common_attributes and disperse it among the various",
"# server stanzas",
"# First stage - turn all the dicts (SERVER, SECGROUP, DATABASE, LOADBAL)",
"# into lists now they're merged properly",
"for",
"stanza_key",
",",
"name_ke... | Reorganizes the data such that the deployment logic can find it all
where it expects to be.
The raw configuration file is intended to be as human-friendly as
possible partly through the following mechanisms:
- In order to minimize repetition, any attributes that are common
to all server configurations can be specified in the
``server_common_attributes`` stanza even though the stanza itself
does not map directly to a deployable resource.
- For reference locality, each security group stanza contains its
list of rules even though rules are actually created in a
separate stage from the groups themselves.
In order to make the :class:`Config` object more useful to the program
logic, this method performs the following transformations:
- Distributes the ``server_common_attributes`` among all the
members of the ``servers`` stanza.
- Extracts security group rules to a top-level key, and
interpolates all source and target values. | [
"Reorganizes",
"the",
"data",
"such",
"that",
"the",
"deployment",
"logic",
"can",
"find",
"it",
"all",
"where",
"it",
"expects",
"to",
"be",
"."
] | 8f000713f88d2a9a8c1193b63ca10a6578560c16 | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/config.py#L381-L426 |
242,814 | fr33jc/bang | bang/config.py | Config.autoinc | def autoinc(self):
"""
Conditionally updates the stack version in the file associated with
this config.
This handles both official releases (i.e. QA configs), and release
candidates. Assumptions about version:
- Official release versions are MAJOR.minor, where MAJOR and minor
are both non-negative integers. E.g.
2.9
2.10
2.11
3.0
3.1
3.2
etc...
- Release candidate versions are MAJOR.minor-rc.N, where MAJOR,
minor, and N are all non-negative integers.
3.5-rc.1
3.5-rc.2
"""
if not self.get('autoinc_version'):
return
oldver = self['version']
newver = bump_version_tail(oldver)
config_path = self.filepath
temp_fd, temp_name = tempfile.mkstemp(
dir=os.path.dirname(config_path),
)
with open(config_path) as old:
with os.fdopen(temp_fd, 'w') as new:
for oldline in old:
if oldline.startswith('version:'):
new.write("version: '%s'\n" % newver)
continue
new.write(oldline)
# no need to backup the old file, it's under version control anyway -
# right???
log.info('Incrementing stack version %s -> %s' % (oldver, newver))
os.rename(temp_name, config_path) | python | def autoinc(self):
"""
Conditionally updates the stack version in the file associated with
this config.
This handles both official releases (i.e. QA configs), and release
candidates. Assumptions about version:
- Official release versions are MAJOR.minor, where MAJOR and minor
are both non-negative integers. E.g.
2.9
2.10
2.11
3.0
3.1
3.2
etc...
- Release candidate versions are MAJOR.minor-rc.N, where MAJOR,
minor, and N are all non-negative integers.
3.5-rc.1
3.5-rc.2
"""
if not self.get('autoinc_version'):
return
oldver = self['version']
newver = bump_version_tail(oldver)
config_path = self.filepath
temp_fd, temp_name = tempfile.mkstemp(
dir=os.path.dirname(config_path),
)
with open(config_path) as old:
with os.fdopen(temp_fd, 'w') as new:
for oldline in old:
if oldline.startswith('version:'):
new.write("version: '%s'\n" % newver)
continue
new.write(oldline)
# no need to backup the old file, it's under version control anyway -
# right???
log.info('Incrementing stack version %s -> %s' % (oldver, newver))
os.rename(temp_name, config_path) | [
"def",
"autoinc",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"get",
"(",
"'autoinc_version'",
")",
":",
"return",
"oldver",
"=",
"self",
"[",
"'version'",
"]",
"newver",
"=",
"bump_version_tail",
"(",
"oldver",
")",
"config_path",
"=",
"self",
".",... | Conditionally updates the stack version in the file associated with
this config.
This handles both official releases (i.e. QA configs), and release
candidates. Assumptions about version:
- Official release versions are MAJOR.minor, where MAJOR and minor
are both non-negative integers. E.g.
2.9
2.10
2.11
3.0
3.1
3.2
etc...
- Release candidate versions are MAJOR.minor-rc.N, where MAJOR,
minor, and N are all non-negative integers.
3.5-rc.1
3.5-rc.2 | [
"Conditionally",
"updates",
"the",
"stack",
"version",
"in",
"the",
"file",
"associated",
"with",
"this",
"config",
"."
] | 8f000713f88d2a9a8c1193b63ca10a6578560c16 | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/config.py#L437-L484 |
242,815 | Rafiot/PubSubLogger | pubsublogger/subscriber.py | setup | def setup(name, path='log', enable_debug=False):
"""
Prepare a NestedSetup.
:param name: the channel name
:param path: the path where the logs will be written
:param enable_debug: do we want to save the message at the DEBUG level
:return a nested Setup
"""
path_tmpl = os.path.join(path, '{name}_{level}.log')
info = path_tmpl.format(name=name, level='info')
warn = path_tmpl.format(name=name, level='warn')
err = path_tmpl.format(name=name, level='err')
crit = path_tmpl.format(name=name, level='crit')
# a nested handler setup can be used to configure more complex setups
setup = [
# make sure we never bubble up to the stderr handler
# if we run out of setup handling
NullHandler(),
# then write messages that are at least info to to a logfile
TimedRotatingFileHandler(info, level='INFO', encoding='utf-8',
date_format='%Y-%m-%d'),
# then write messages that are at least warnings to to a logfile
TimedRotatingFileHandler(warn, level='WARNING', encoding='utf-8',
date_format='%Y-%m-%d'),
# then write messages that are at least errors to to a logfile
TimedRotatingFileHandler(err, level='ERROR', encoding='utf-8',
date_format='%Y-%m-%d'),
# then write messages that are at least critical errors to to a logfile
TimedRotatingFileHandler(crit, level='CRITICAL', encoding='utf-8',
date_format='%Y-%m-%d'),
]
if enable_debug:
debug = path_tmpl.format(name=name, level='debug')
setup.insert(1, TimedRotatingFileHandler(debug, level='DEBUG',
encoding='utf-8', date_format='%Y-%m-%d'))
if src_server is not None and smtp_server is not None \
and smtp_port != 0 and len(dest_mails) != 0:
mail_tmpl = '{name}_error@{src}'
from_mail = mail_tmpl.format(name=name, src=src_server)
subject = 'Error in {}'.format(name)
# errors should then be delivered by mail and also be kept
# in the application log, so we let them bubble up.
setup.append(MailHandler(from_mail, dest_mails, subject,
level='ERROR', bubble=True,
server_addr=(smtp_server, smtp_port)))
return NestedSetup(setup) | python | def setup(name, path='log', enable_debug=False):
"""
Prepare a NestedSetup.
:param name: the channel name
:param path: the path where the logs will be written
:param enable_debug: do we want to save the message at the DEBUG level
:return a nested Setup
"""
path_tmpl = os.path.join(path, '{name}_{level}.log')
info = path_tmpl.format(name=name, level='info')
warn = path_tmpl.format(name=name, level='warn')
err = path_tmpl.format(name=name, level='err')
crit = path_tmpl.format(name=name, level='crit')
# a nested handler setup can be used to configure more complex setups
setup = [
# make sure we never bubble up to the stderr handler
# if we run out of setup handling
NullHandler(),
# then write messages that are at least info to to a logfile
TimedRotatingFileHandler(info, level='INFO', encoding='utf-8',
date_format='%Y-%m-%d'),
# then write messages that are at least warnings to to a logfile
TimedRotatingFileHandler(warn, level='WARNING', encoding='utf-8',
date_format='%Y-%m-%d'),
# then write messages that are at least errors to to a logfile
TimedRotatingFileHandler(err, level='ERROR', encoding='utf-8',
date_format='%Y-%m-%d'),
# then write messages that are at least critical errors to to a logfile
TimedRotatingFileHandler(crit, level='CRITICAL', encoding='utf-8',
date_format='%Y-%m-%d'),
]
if enable_debug:
debug = path_tmpl.format(name=name, level='debug')
setup.insert(1, TimedRotatingFileHandler(debug, level='DEBUG',
encoding='utf-8', date_format='%Y-%m-%d'))
if src_server is not None and smtp_server is not None \
and smtp_port != 0 and len(dest_mails) != 0:
mail_tmpl = '{name}_error@{src}'
from_mail = mail_tmpl.format(name=name, src=src_server)
subject = 'Error in {}'.format(name)
# errors should then be delivered by mail and also be kept
# in the application log, so we let them bubble up.
setup.append(MailHandler(from_mail, dest_mails, subject,
level='ERROR', bubble=True,
server_addr=(smtp_server, smtp_port)))
return NestedSetup(setup) | [
"def",
"setup",
"(",
"name",
",",
"path",
"=",
"'log'",
",",
"enable_debug",
"=",
"False",
")",
":",
"path_tmpl",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'{name}_{level}.log'",
")",
"info",
"=",
"path_tmpl",
".",
"format",
"(",
"name",
... | Prepare a NestedSetup.
:param name: the channel name
:param path: the path where the logs will be written
:param enable_debug: do we want to save the message at the DEBUG level
:return a nested Setup | [
"Prepare",
"a",
"NestedSetup",
"."
] | 4f28ad673f42ee2ec7792d414d325aef9a56da53 | https://github.com/Rafiot/PubSubLogger/blob/4f28ad673f42ee2ec7792d414d325aef9a56da53/pubsublogger/subscriber.py#L43-L91 |
242,816 | Rafiot/PubSubLogger | pubsublogger/subscriber.py | mail_setup | def mail_setup(path):
"""
Set the variables to be able to send emails.
:param path: path to the config file
"""
global dest_mails
global smtp_server
global smtp_port
global src_server
config = configparser.RawConfigParser()
config.readfp(path)
dest_mails = config.get('mail', 'dest_mail').split(',')
smtp_server = config.get('mail', 'smtp_server')
smtp_port = config.get('mail', 'smtp_port')
src_server = config.get('mail', 'src_server') | python | def mail_setup(path):
"""
Set the variables to be able to send emails.
:param path: path to the config file
"""
global dest_mails
global smtp_server
global smtp_port
global src_server
config = configparser.RawConfigParser()
config.readfp(path)
dest_mails = config.get('mail', 'dest_mail').split(',')
smtp_server = config.get('mail', 'smtp_server')
smtp_port = config.get('mail', 'smtp_port')
src_server = config.get('mail', 'src_server') | [
"def",
"mail_setup",
"(",
"path",
")",
":",
"global",
"dest_mails",
"global",
"smtp_server",
"global",
"smtp_port",
"global",
"src_server",
"config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"config",
".",
"readfp",
"(",
"path",
")",
"dest_mails",
... | Set the variables to be able to send emails.
:param path: path to the config file | [
"Set",
"the",
"variables",
"to",
"be",
"able",
"to",
"send",
"emails",
"."
] | 4f28ad673f42ee2ec7792d414d325aef9a56da53 | https://github.com/Rafiot/PubSubLogger/blob/4f28ad673f42ee2ec7792d414d325aef9a56da53/pubsublogger/subscriber.py#L94-L109 |
242,817 | Rafiot/PubSubLogger | pubsublogger/subscriber.py | run | def run(log_name, path, debug=False, mail=None, timeout=0):
"""
Run a subscriber and pass the messages to the logbook setup.
Stays alive as long as the pubsub instance listen to something.
:param log_name: the channel to listen to
:param path: the path where the log files will be written
:param debug: True if you want to save the debug messages too
:param mail: Path to the config file for the mails
"""
global pubsub
global channel
channel = log_name
if use_tcp_socket:
r = redis.StrictRedis(host=hostname, port=port)
else:
r = redis.StrictRedis(unix_socket_path=unix_socket)
pubsub = r.pubsub()
pubsub.psubscribe(channel + '.*')
if timeout != 0:
deadline = time.time() + timeout
logger = Logger(channel)
if mail is not None:
mail_setup(mail)
if os.path.exists(path) and not os.path.isdir(path):
raise Exception("The path you want to use to save the file is invalid (not a directory).")
if not os.path.exists(path):
os.mkdir(path)
with setup(channel, path, debug):
while True:
msg = pubsub.get_message()
if msg:
if msg['type'] == 'pmessage':
level = msg['channel'].decode('utf-8').split('.')[1]
message = msg['data']
try:
message = message.decode('utf-8')
except:
pass
logger.log(level, message)
time.sleep(0.01)
if timeout > 0:
if time.time() >= deadline:
break | python | def run(log_name, path, debug=False, mail=None, timeout=0):
"""
Run a subscriber and pass the messages to the logbook setup.
Stays alive as long as the pubsub instance listen to something.
:param log_name: the channel to listen to
:param path: the path where the log files will be written
:param debug: True if you want to save the debug messages too
:param mail: Path to the config file for the mails
"""
global pubsub
global channel
channel = log_name
if use_tcp_socket:
r = redis.StrictRedis(host=hostname, port=port)
else:
r = redis.StrictRedis(unix_socket_path=unix_socket)
pubsub = r.pubsub()
pubsub.psubscribe(channel + '.*')
if timeout != 0:
deadline = time.time() + timeout
logger = Logger(channel)
if mail is not None:
mail_setup(mail)
if os.path.exists(path) and not os.path.isdir(path):
raise Exception("The path you want to use to save the file is invalid (not a directory).")
if not os.path.exists(path):
os.mkdir(path)
with setup(channel, path, debug):
while True:
msg = pubsub.get_message()
if msg:
if msg['type'] == 'pmessage':
level = msg['channel'].decode('utf-8').split('.')[1]
message = msg['data']
try:
message = message.decode('utf-8')
except:
pass
logger.log(level, message)
time.sleep(0.01)
if timeout > 0:
if time.time() >= deadline:
break | [
"def",
"run",
"(",
"log_name",
",",
"path",
",",
"debug",
"=",
"False",
",",
"mail",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"global",
"pubsub",
"global",
"channel",
"channel",
"=",
"log_name",
"if",
"use_tcp_socket",
":",
"r",
"=",
"redis",
... | Run a subscriber and pass the messages to the logbook setup.
Stays alive as long as the pubsub instance listen to something.
:param log_name: the channel to listen to
:param path: the path where the log files will be written
:param debug: True if you want to save the debug messages too
:param mail: Path to the config file for the mails | [
"Run",
"a",
"subscriber",
"and",
"pass",
"the",
"messages",
"to",
"the",
"logbook",
"setup",
".",
"Stays",
"alive",
"as",
"long",
"as",
"the",
"pubsub",
"instance",
"listen",
"to",
"something",
"."
] | 4f28ad673f42ee2ec7792d414d325aef9a56da53 | https://github.com/Rafiot/PubSubLogger/blob/4f28ad673f42ee2ec7792d414d325aef9a56da53/pubsublogger/subscriber.py#L112-L158 |
242,818 | tylertrussell/flake8-docstrings-catnado | flake8_docstrings.py | pep257Checker.parse_options | def parse_options(cls, options):
"""Pass options through to this plugin."""
cls.ignore_decorators = options.ignore_decorators
cls.exclude_from_doctest = options.exclude_from_doctest
if not isinstance(cls.exclude_from_doctest, list):
cls.exclude_from_doctest = [cls.exclude_from_doctest] | python | def parse_options(cls, options):
"""Pass options through to this plugin."""
cls.ignore_decorators = options.ignore_decorators
cls.exclude_from_doctest = options.exclude_from_doctest
if not isinstance(cls.exclude_from_doctest, list):
cls.exclude_from_doctest = [cls.exclude_from_doctest] | [
"def",
"parse_options",
"(",
"cls",
",",
"options",
")",
":",
"cls",
".",
"ignore_decorators",
"=",
"options",
".",
"ignore_decorators",
"cls",
".",
"exclude_from_doctest",
"=",
"options",
".",
"exclude_from_doctest",
"if",
"not",
"isinstance",
"(",
"cls",
".",
... | Pass options through to this plugin. | [
"Pass",
"options",
"through",
"to",
"this",
"plugin",
"."
] | 76a9e202a93c8dfb11994c95911487b3722d75c9 | https://github.com/tylertrussell/flake8-docstrings-catnado/blob/76a9e202a93c8dfb11994c95911487b3722d75c9/flake8_docstrings.py#L75-L80 |
242,819 | tylertrussell/flake8-docstrings-catnado | flake8_docstrings.py | pep257Checker.load_source | def load_source(self):
"""Load the source for the specified file."""
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pycodestyle.stdin_get_value()
else:
with pep257.tokenize_open(self.filename) as fd:
self.source = fd.read() | python | def load_source(self):
"""Load the source for the specified file."""
if self.filename in self.STDIN_NAMES:
self.filename = 'stdin'
self.source = pycodestyle.stdin_get_value()
else:
with pep257.tokenize_open(self.filename) as fd:
self.source = fd.read() | [
"def",
"load_source",
"(",
"self",
")",
":",
"if",
"self",
".",
"filename",
"in",
"self",
".",
"STDIN_NAMES",
":",
"self",
".",
"filename",
"=",
"'stdin'",
"self",
".",
"source",
"=",
"pycodestyle",
".",
"stdin_get_value",
"(",
")",
"else",
":",
"with",
... | Load the source for the specified file. | [
"Load",
"the",
"source",
"for",
"the",
"specified",
"file",
"."
] | 76a9e202a93c8dfb11994c95911487b3722d75c9 | https://github.com/tylertrussell/flake8-docstrings-catnado/blob/76a9e202a93c8dfb11994c95911487b3722d75c9/flake8_docstrings.py#L114-L121 |
242,820 | GMadorell/abris | abris_transform/abris.py | Abris.prepare | def prepare(self, data_source):
"""
Called with the training data.
@param data_source: Either a pandas.DataFrame or a file-like object.
"""
dataframe = self.__get_dataframe(data_source, use_target=True)
self.__config.get_data_model().set_features_types_from_dataframe(dataframe)
dataframe = self.__cleaner.prepare(dataframe)
return self.__transformer.prepare(dataframe) | python | def prepare(self, data_source):
"""
Called with the training data.
@param data_source: Either a pandas.DataFrame or a file-like object.
"""
dataframe = self.__get_dataframe(data_source, use_target=True)
self.__config.get_data_model().set_features_types_from_dataframe(dataframe)
dataframe = self.__cleaner.prepare(dataframe)
return self.__transformer.prepare(dataframe) | [
"def",
"prepare",
"(",
"self",
",",
"data_source",
")",
":",
"dataframe",
"=",
"self",
".",
"__get_dataframe",
"(",
"data_source",
",",
"use_target",
"=",
"True",
")",
"self",
".",
"__config",
".",
"get_data_model",
"(",
")",
".",
"set_features_types_from_data... | Called with the training data.
@param data_source: Either a pandas.DataFrame or a file-like object. | [
"Called",
"with",
"the",
"training",
"data",
"."
] | 0d8ab7ec506835a45fae6935d129f5d7e6937bb2 | https://github.com/GMadorell/abris/blob/0d8ab7ec506835a45fae6935d129f5d7e6937bb2/abris_transform/abris.py#L22-L30 |
242,821 | jlesquembre/jlle | jlle/releaser/utils.py | fix_rst_heading | def fix_rst_heading(heading, below):
"""If the 'below' line looks like a reST line, give it the correct length.
This allows for different characters being used as header lines.
"""
if len(below) == 0:
return below
first = below[0]
if first not in '-=`~':
return below
if not len(below) == len([char for char in below
if char == first]):
# The line is not uniformly the same character
return below
below = first * len(heading)
return below | python | def fix_rst_heading(heading, below):
"""If the 'below' line looks like a reST line, give it the correct length.
This allows for different characters being used as header lines.
"""
if len(below) == 0:
return below
first = below[0]
if first not in '-=`~':
return below
if not len(below) == len([char for char in below
if char == first]):
# The line is not uniformly the same character
return below
below = first * len(heading)
return below | [
"def",
"fix_rst_heading",
"(",
"heading",
",",
"below",
")",
":",
"if",
"len",
"(",
"below",
")",
"==",
"0",
":",
"return",
"below",
"first",
"=",
"below",
"[",
"0",
"]",
"if",
"first",
"not",
"in",
"'-=`~'",
":",
"return",
"below",
"if",
"not",
"l... | If the 'below' line looks like a reST line, give it the correct length.
This allows for different characters being used as header lines. | [
"If",
"the",
"below",
"line",
"looks",
"like",
"a",
"reST",
"line",
"give",
"it",
"the",
"correct",
"length",
"."
] | 3645d8f203708355853ef911f4b887ae4d794826 | https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/utils.py#L108-L123 |
242,822 | jlesquembre/jlle | jlle/releaser/utils.py | sanity_check | def sanity_check(vcs):
"""Do sanity check before making changes
Check that we are not on a tag and/or do not have local changes.
Returns True when all is fine.
"""
if not vcs.is_clean_checkout():
q = ("This is NOT a clean checkout. You are on a tag or you have "
"local changes.\n"
"Are you sure you want to continue?")
if not ask(q, default=False):
sys.exit(1) | python | def sanity_check(vcs):
"""Do sanity check before making changes
Check that we are not on a tag and/or do not have local changes.
Returns True when all is fine.
"""
if not vcs.is_clean_checkout():
q = ("This is NOT a clean checkout. You are on a tag or you have "
"local changes.\n"
"Are you sure you want to continue?")
if not ask(q, default=False):
sys.exit(1) | [
"def",
"sanity_check",
"(",
"vcs",
")",
":",
"if",
"not",
"vcs",
".",
"is_clean_checkout",
"(",
")",
":",
"q",
"=",
"(",
"\"This is NOT a clean checkout. You are on a tag or you have \"",
"\"local changes.\\n\"",
"\"Are you sure you want to continue?\"",
")",
"if",
"not",... | Do sanity check before making changes
Check that we are not on a tag and/or do not have local changes.
Returns True when all is fine. | [
"Do",
"sanity",
"check",
"before",
"making",
"changes"
] | 3645d8f203708355853ef911f4b887ae4d794826 | https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/utils.py#L223-L235 |
242,823 | jlesquembre/jlle | jlle/releaser/utils.py | check_recommended_files | def check_recommended_files(data, vcs):
"""Do check for recommended files.
Returns True when all is fine.
"""
main_files = os.listdir(data['workingdir'])
if not 'setup.py' in main_files and not 'setup.cfg' in main_files:
# Not a python package. We have no recommendations.
return True
if not 'MANIFEST.in' in main_files and not 'MANIFEST' in main_files:
q = ("This package is missing a MANIFEST.in file. This file is "
"recommended. "
"See http://docs.python.org/distutils/sourcedist.html"
" for more info. Sample contents:"
"\n"
"recursive-include main_directory *"
"recursive-include docs *"
"include *"
"global-exclude *.pyc"
"\n"
"You may want to quit and fix this.")
if not vcs.is_setuptools_helper_package_installed():
q += "Installing %s may help too.\n" % \
vcs.setuptools_helper_package
# We could ask, but simply printing it is nicer. Well, okay,
# let's avoid some broken eggs on PyPI, per
# https://github.com/zestsoftware/zest.releaser/issues/10
q += "Do you want to continue with the release?"
if not ask(q, default=False):
return False
print(q)
return True | python | def check_recommended_files(data, vcs):
"""Do check for recommended files.
Returns True when all is fine.
"""
main_files = os.listdir(data['workingdir'])
if not 'setup.py' in main_files and not 'setup.cfg' in main_files:
# Not a python package. We have no recommendations.
return True
if not 'MANIFEST.in' in main_files and not 'MANIFEST' in main_files:
q = ("This package is missing a MANIFEST.in file. This file is "
"recommended. "
"See http://docs.python.org/distutils/sourcedist.html"
" for more info. Sample contents:"
"\n"
"recursive-include main_directory *"
"recursive-include docs *"
"include *"
"global-exclude *.pyc"
"\n"
"You may want to quit and fix this.")
if not vcs.is_setuptools_helper_package_installed():
q += "Installing %s may help too.\n" % \
vcs.setuptools_helper_package
# We could ask, but simply printing it is nicer. Well, okay,
# let's avoid some broken eggs on PyPI, per
# https://github.com/zestsoftware/zest.releaser/issues/10
q += "Do you want to continue with the release?"
if not ask(q, default=False):
return False
print(q)
return True | [
"def",
"check_recommended_files",
"(",
"data",
",",
"vcs",
")",
":",
"main_files",
"=",
"os",
".",
"listdir",
"(",
"data",
"[",
"'workingdir'",
"]",
")",
"if",
"not",
"'setup.py'",
"in",
"main_files",
"and",
"not",
"'setup.cfg'",
"in",
"main_files",
":",
"... | Do check for recommended files.
Returns True when all is fine. | [
"Do",
"check",
"for",
"recommended",
"files",
"."
] | 3645d8f203708355853ef911f4b887ae4d794826 | https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/utils.py#L238-L270 |
242,824 | jlesquembre/jlle | jlle/releaser/utils.py | cleanup_version | def cleanup_version(version):
"""Check if the version looks like a development version."""
for w in WRONG_IN_VERSION:
if version.find(w) != -1:
logger.debug("Version indicates development: %s.", version)
version = version[:version.find(w)].strip()
logger.debug("Removing debug indicators: %r", version)
version = version.rstrip('.') # 1.0.dev0 -> 1.0. -> 1.0
return version | python | def cleanup_version(version):
"""Check if the version looks like a development version."""
for w in WRONG_IN_VERSION:
if version.find(w) != -1:
logger.debug("Version indicates development: %s.", version)
version = version[:version.find(w)].strip()
logger.debug("Removing debug indicators: %r", version)
version = version.rstrip('.') # 1.0.dev0 -> 1.0. -> 1.0
return version | [
"def",
"cleanup_version",
"(",
"version",
")",
":",
"for",
"w",
"in",
"WRONG_IN_VERSION",
":",
"if",
"version",
".",
"find",
"(",
"w",
")",
"!=",
"-",
"1",
":",
"logger",
".",
"debug",
"(",
"\"Version indicates development: %s.\"",
",",
"version",
")",
"ve... | Check if the version looks like a development version. | [
"Check",
"if",
"the",
"version",
"looks",
"like",
"a",
"development",
"version",
"."
] | 3645d8f203708355853ef911f4b887ae4d794826 | https://github.com/jlesquembre/jlle/blob/3645d8f203708355853ef911f4b887ae4d794826/jlle/releaser/utils.py#L284-L292 |
242,825 | JNRowe/jnrbase | jnrbase/pager.py | pager | def pager(__text: str, *, pager: Optional[str] = 'less'):
"""Pass output through pager.
See :manpage:`less(1)`, if you wish to configure the default pager. For
example, you may wish to check ``FRSX`` options.
Args:
__text: Text to page
pager: Pager to use
"""
if pager:
run([pager, ], input=__text.encode())
else:
print(__text) | python | def pager(__text: str, *, pager: Optional[str] = 'less'):
"""Pass output through pager.
See :manpage:`less(1)`, if you wish to configure the default pager. For
example, you may wish to check ``FRSX`` options.
Args:
__text: Text to page
pager: Pager to use
"""
if pager:
run([pager, ], input=__text.encode())
else:
print(__text) | [
"def",
"pager",
"(",
"__text",
":",
"str",
",",
"*",
",",
"pager",
":",
"Optional",
"[",
"str",
"]",
"=",
"'less'",
")",
":",
"if",
"pager",
":",
"run",
"(",
"[",
"pager",
",",
"]",
",",
"input",
"=",
"__text",
".",
"encode",
"(",
")",
")",
"... | Pass output through pager.
See :manpage:`less(1)`, if you wish to configure the default pager. For
example, you may wish to check ``FRSX`` options.
Args:
__text: Text to page
pager: Pager to use | [
"Pass",
"output",
"through",
"pager",
"."
] | ae505ef69a9feb739b5f4e62c5a8e6533104d3ea | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/pager.py#L26-L39 |
242,826 | zeromake/aiko | aiko/application.py | Application.listen | def listen(self, **kwargs: Any) -> Server:
"""
bind host, port or sock
"""
loop = cast(asyncio.AbstractEventLoop, self._loop)
return (yield from loop.create_server(
lambda: self._protocol(
loop=loop,
handle=self._handle,
requset_charset=self.requset_charset,
response_charset=self.response_charset,
),
**kwargs,
)) | python | def listen(self, **kwargs: Any) -> Server:
"""
bind host, port or sock
"""
loop = cast(asyncio.AbstractEventLoop, self._loop)
return (yield from loop.create_server(
lambda: self._protocol(
loop=loop,
handle=self._handle,
requset_charset=self.requset_charset,
response_charset=self.response_charset,
),
**kwargs,
)) | [
"def",
"listen",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Server",
":",
"loop",
"=",
"cast",
"(",
"asyncio",
".",
"AbstractEventLoop",
",",
"self",
".",
"_loop",
")",
"return",
"(",
"yield",
"from",
"loop",
".",
"create_server",
... | bind host, port or sock | [
"bind",
"host",
"port",
"or",
"sock"
] | 53b246fa88652466a9e38ac3d1a99a6198195b0f | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/application.py#L128-L141 |
242,827 | armstrong/armstrong.hatband | armstrong/hatband/views/search.py | TypeAndModelQueryMixin.type_and_model_to_query | def type_and_model_to_query(self, request):
"""
Return JSON for an individual Model instance
If the required parameters are wrong, return 400 Bad Request
If the parameters are correct but there is no data, return empty JSON
"""
try:
content_type_id = request.GET["content_type_id"]
object_id = request.GET["object_id"]
except KeyError:
return HttpResponseBadRequest()
try:
content_type = ContentType.objects.get(pk=content_type_id)
model = content_type.model_class()
result = model.objects.get(pk=object_id)
except ObjectDoesNotExist:
data = ""
else:
data = '%s: "%d: %s"' % (content_type.model, result.pk, result)
return JsonResponse({"query": data}) | python | def type_and_model_to_query(self, request):
"""
Return JSON for an individual Model instance
If the required parameters are wrong, return 400 Bad Request
If the parameters are correct but there is no data, return empty JSON
"""
try:
content_type_id = request.GET["content_type_id"]
object_id = request.GET["object_id"]
except KeyError:
return HttpResponseBadRequest()
try:
content_type = ContentType.objects.get(pk=content_type_id)
model = content_type.model_class()
result = model.objects.get(pk=object_id)
except ObjectDoesNotExist:
data = ""
else:
data = '%s: "%d: %s"' % (content_type.model, result.pk, result)
return JsonResponse({"query": data}) | [
"def",
"type_and_model_to_query",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"content_type_id",
"=",
"request",
".",
"GET",
"[",
"\"content_type_id\"",
"]",
"object_id",
"=",
"request",
".",
"GET",
"[",
"\"object_id\"",
"]",
"except",
"KeyError",
":",
... | Return JSON for an individual Model instance
If the required parameters are wrong, return 400 Bad Request
If the parameters are correct but there is no data, return empty JSON | [
"Return",
"JSON",
"for",
"an",
"individual",
"Model",
"instance"
] | b34027c85a8ccfe2ee37aa9348d98e143d300082 | https://github.com/armstrong/armstrong.hatband/blob/b34027c85a8ccfe2ee37aa9348d98e143d300082/armstrong/hatband/views/search.py#L151-L174 |
242,828 | vinu76jsr/pipsort | lib/pipsort/core/_config.py | _Config.load | def load(self, paths, params=None):
""" Load data from configuration files.
Configuration values are read from a sequence of one or more YAML
files. Files are read in the given order, and a duplicate value will
overwrite the existing value.
The optional 'params' argument is a dict-like object to use for
parameter substitution in the config files. Any text matching "%key;"
will be replaced with the value for 'key' in params.
"""
def replace(match):
""" Callback for re.sub to do parameter replacement. """
# This allows for multi-pattern substitution in a single pass.
return params[match.group(0)]
params = {r"%{:s};".format(key): val for (key, val)
in params.iteritems()} if params else {}
regex = compile("|".join(params) or r"^(?!)")
for path in paths:
with open(path, "r") as stream:
# Global text substitution is used for parameter replacement.
# Two drawbacks of this are 1) the entire config file has to be
# read into memory first; 2) it might be nice if comments were
# excluded from replacement. A more elegant (but complex)
# approach would be to use PyYAML's various hooks to do the
# substitution as the file is parsed.
logger.info("reading config data from {:s}".format(path))
yaml = regex.sub(replace, stream.read())
try:
self.update(load(yaml))
except TypeError: # load() returned None
logger.warn("config file '{:s}' is empty".format(yaml))
return | python | def load(self, paths, params=None):
""" Load data from configuration files.
Configuration values are read from a sequence of one or more YAML
files. Files are read in the given order, and a duplicate value will
overwrite the existing value.
The optional 'params' argument is a dict-like object to use for
parameter substitution in the config files. Any text matching "%key;"
will be replaced with the value for 'key' in params.
"""
def replace(match):
""" Callback for re.sub to do parameter replacement. """
# This allows for multi-pattern substitution in a single pass.
return params[match.group(0)]
params = {r"%{:s};".format(key): val for (key, val)
in params.iteritems()} if params else {}
regex = compile("|".join(params) or r"^(?!)")
for path in paths:
with open(path, "r") as stream:
# Global text substitution is used for parameter replacement.
# Two drawbacks of this are 1) the entire config file has to be
# read into memory first; 2) it might be nice if comments were
# excluded from replacement. A more elegant (but complex)
# approach would be to use PyYAML's various hooks to do the
# substitution as the file is parsed.
logger.info("reading config data from {:s}".format(path))
yaml = regex.sub(replace, stream.read())
try:
self.update(load(yaml))
except TypeError: # load() returned None
logger.warn("config file '{:s}' is empty".format(yaml))
return | [
"def",
"load",
"(",
"self",
",",
"paths",
",",
"params",
"=",
"None",
")",
":",
"def",
"replace",
"(",
"match",
")",
":",
"\"\"\" Callback for re.sub to do parameter replacement. \"\"\"",
"# This allows for multi-pattern substitution in a single pass.",
"return",
"params",
... | Load data from configuration files.
Configuration values are read from a sequence of one or more YAML
files. Files are read in the given order, and a duplicate value will
overwrite the existing value.
The optional 'params' argument is a dict-like object to use for
parameter substitution in the config files. Any text matching "%key;"
will be replaced with the value for 'key' in params. | [
"Load",
"data",
"from",
"configuration",
"files",
"."
] | 71ead1269de85ee0255741390bf1da85d81b7d16 | https://github.com/vinu76jsr/pipsort/blob/71ead1269de85ee0255741390bf1da85d81b7d16/lib/pipsort/core/_config.py#L48-L82 |
242,829 | universalcore/unicore.distribute | unicore/distribute/utils.py | get_repositories | def get_repositories(path):
"""
Return an array of tuples with the name and path for
repositories found in a directory.
:param str path:
The path to find repositories in
:returns: tuple
"""
return [get_repository(os.path.join(path, subdir))
for subdir in os.listdir(path)
if os.path.isdir(
os.path.join(path, subdir, '.git'))] | python | def get_repositories(path):
"""
Return an array of tuples with the name and path for
repositories found in a directory.
:param str path:
The path to find repositories in
:returns: tuple
"""
return [get_repository(os.path.join(path, subdir))
for subdir in os.listdir(path)
if os.path.isdir(
os.path.join(path, subdir, '.git'))] | [
"def",
"get_repositories",
"(",
"path",
")",
":",
"return",
"[",
"get_repository",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"subdir",
")",
")",
"for",
"subdir",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"if",
"os",
".",
"path",
".... | Return an array of tuples with the name and path for
repositories found in a directory.
:param str path:
The path to find repositories in
:returns: tuple | [
"Return",
"an",
"array",
"of",
"tuples",
"with",
"the",
"name",
"and",
"path",
"for",
"repositories",
"found",
"in",
"a",
"directory",
"."
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L72-L84 |
242,830 | universalcore/unicore.distribute | unicore/distribute/utils.py | get_repository_names | def get_repository_names(path):
"""
Return an array of the path name for
repositories found in a directory.
:param str path:
The path to find repositories in
:returns: array
"""
return [subdir
for subdir in os.listdir(path)
if os.path.isdir(os.path.join(path, subdir, '.git'))] | python | def get_repository_names(path):
"""
Return an array of the path name for
repositories found in a directory.
:param str path:
The path to find repositories in
:returns: array
"""
return [subdir
for subdir in os.listdir(path)
if os.path.isdir(os.path.join(path, subdir, '.git'))] | [
"def",
"get_repository_names",
"(",
"path",
")",
":",
"return",
"[",
"subdir",
"for",
"subdir",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"subdir",
",... | Return an array of the path name for
repositories found in a directory.
:param str path:
The path to find repositories in
:returns: array | [
"Return",
"an",
"array",
"of",
"the",
"path",
"name",
"for",
"repositories",
"found",
"in",
"a",
"directory",
"."
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L87-L98 |
242,831 | universalcore/unicore.distribute | unicore/distribute/utils.py | list_schemas | def list_schemas(repo):
"""
Return a list of parsed avro schemas as dictionaries.
:param Repo repo:
The git repository.
:returns: dict
"""
schema_files = glob.glob(
os.path.join(repo.working_dir, '_schemas', '*.avsc'))
schemas = {}
for schema_file in schema_files:
with open(schema_file, 'r') as fp:
schema = json.load(fp)
schemas['%(namespace)s.%(name)s' % schema] = schema
return schemas | python | def list_schemas(repo):
"""
Return a list of parsed avro schemas as dictionaries.
:param Repo repo:
The git repository.
:returns: dict
"""
schema_files = glob.glob(
os.path.join(repo.working_dir, '_schemas', '*.avsc'))
schemas = {}
for schema_file in schema_files:
with open(schema_file, 'r') as fp:
schema = json.load(fp)
schemas['%(namespace)s.%(name)s' % schema] = schema
return schemas | [
"def",
"list_schemas",
"(",
"repo",
")",
":",
"schema_files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"repo",
".",
"working_dir",
",",
"'_schemas'",
",",
"'*.avsc'",
")",
")",
"schemas",
"=",
"{",
"}",
"for",
"schema_file",
... | Return a list of parsed avro schemas as dictionaries.
:param Repo repo:
The git repository.
:returns: dict | [
"Return",
"a",
"list",
"of",
"parsed",
"avro",
"schemas",
"as",
"dictionaries",
"."
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L126-L141 |
242,832 | universalcore/unicore.distribute | unicore/distribute/utils.py | list_content_types | def list_content_types(repo):
"""
Return a list of content types in a repository.
:param Repo repo:
The git repository.
:returns: list
"""
schema_files = glob.glob(
os.path.join(repo.working_dir, '_schemas', '*.avsc'))
return [os.path.splitext(os.path.basename(schema_file))[0]
for schema_file in schema_files] | python | def list_content_types(repo):
"""
Return a list of content types in a repository.
:param Repo repo:
The git repository.
:returns: list
"""
schema_files = glob.glob(
os.path.join(repo.working_dir, '_schemas', '*.avsc'))
return [os.path.splitext(os.path.basename(schema_file))[0]
for schema_file in schema_files] | [
"def",
"list_content_types",
"(",
"repo",
")",
":",
"schema_files",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"repo",
".",
"working_dir",
",",
"'_schemas'",
",",
"'*.avsc'",
")",
")",
"return",
"[",
"os",
".",
"path",
".",
"... | Return a list of content types in a repository.
:param Repo repo:
The git repository.
:returns: list | [
"Return",
"a",
"list",
"of",
"content",
"types",
"in",
"a",
"repository",
"."
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L144-L155 |
242,833 | universalcore/unicore.distribute | unicore/distribute/utils.py | get_schema | def get_schema(repo, content_type):
"""
Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict
"""
try:
with open(
os.path.join(repo.working_dir,
'_schemas',
'%s.avsc' % (content_type,)), 'r') as fp:
data = fp.read()
return avro.schema.parse(data)
except IOError: # pragma: no cover
raise NotFound('Schema does not exist.') | python | def get_schema(repo, content_type):
"""
Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict
"""
try:
with open(
os.path.join(repo.working_dir,
'_schemas',
'%s.avsc' % (content_type,)), 'r') as fp:
data = fp.read()
return avro.schema.parse(data)
except IOError: # pragma: no cover
raise NotFound('Schema does not exist.') | [
"def",
"get_schema",
"(",
"repo",
",",
"content_type",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"repo",
".",
"working_dir",
",",
"'_schemas'",
",",
"'%s.avsc'",
"%",
"(",
"content_type",
",",
")",
")",
",",
"'r'... | Return a schema for a content type in a repository.
:param Repo repo:
The git repository.
:returns: dict | [
"Return",
"a",
"schema",
"for",
"a",
"content",
"type",
"in",
"a",
"repository",
"."
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L158-L174 |
242,834 | universalcore/unicore.distribute | unicore/distribute/utils.py | get_mapping | def get_mapping(repo, content_type):
"""
Return an ES mapping for a content type in a repository.
:param Repo repo:
This git repository.
:returns: dict
"""
try:
with open(
os.path.join(repo.working_dir,
'_mappings',
'%s.json' % (content_type,)), 'r') as fp:
return json.load(fp)
except IOError:
raise NotFound('Mapping does not exist.') | python | def get_mapping(repo, content_type):
"""
Return an ES mapping for a content type in a repository.
:param Repo repo:
This git repository.
:returns: dict
"""
try:
with open(
os.path.join(repo.working_dir,
'_mappings',
'%s.json' % (content_type,)), 'r') as fp:
return json.load(fp)
except IOError:
raise NotFound('Mapping does not exist.') | [
"def",
"get_mapping",
"(",
"repo",
",",
"content_type",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"repo",
".",
"working_dir",
",",
"'_mappings'",
",",
"'%s.json'",
"%",
"(",
"content_type",
",",
")",
")",
",",
"'... | Return an ES mapping for a content type in a repository.
:param Repo repo:
This git repository.
:returns: dict | [
"Return",
"an",
"ES",
"mapping",
"for",
"a",
"content",
"type",
"in",
"a",
"repository",
"."
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L177-L192 |
242,835 | universalcore/unicore.distribute | unicore/distribute/utils.py | format_repo | def format_repo(repo):
"""
Return a dictionary representing the repository
It returns ``None`` for things we do not support or are not
relevant.
:param str repo_name:
The name of the repository.
:param git.Repo repo:
The repository object.
:param str base_url:
The base URL for the repository's links.
:returns: dict
"""
commit = repo.commit()
return {
'name': os.path.basename(repo.working_dir),
'branch': repo.active_branch.name,
'commit': commit.hexsha,
'timestamp': datetime.fromtimestamp(
commit.committed_date).isoformat(),
'author': '%s <%s>' % (commit.author.name, commit.author.email),
'schemas': list_schemas(repo)
} | python | def format_repo(repo):
"""
Return a dictionary representing the repository
It returns ``None`` for things we do not support or are not
relevant.
:param str repo_name:
The name of the repository.
:param git.Repo repo:
The repository object.
:param str base_url:
The base URL for the repository's links.
:returns: dict
"""
commit = repo.commit()
return {
'name': os.path.basename(repo.working_dir),
'branch': repo.active_branch.name,
'commit': commit.hexsha,
'timestamp': datetime.fromtimestamp(
commit.committed_date).isoformat(),
'author': '%s <%s>' % (commit.author.name, commit.author.email),
'schemas': list_schemas(repo)
} | [
"def",
"format_repo",
"(",
"repo",
")",
":",
"commit",
"=",
"repo",
".",
"commit",
"(",
")",
"return",
"{",
"'name'",
":",
"os",
".",
"path",
".",
"basename",
"(",
"repo",
".",
"working_dir",
")",
",",
"'branch'",
":",
"repo",
".",
"active_branch",
"... | Return a dictionary representing the repository
It returns ``None`` for things we do not support or are not
relevant.
:param str repo_name:
The name of the repository.
:param git.Repo repo:
The repository object.
:param str base_url:
The base URL for the repository's links.
:returns: dict | [
"Return",
"a",
"dictionary",
"representing",
"the",
"repository"
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L195-L220 |
242,836 | universalcore/unicore.distribute | unicore/distribute/utils.py | format_diffindex | def format_diffindex(diff_index):
"""
Return a JSON formattable representation of a DiffIndex.
Returns a generator that returns dictionaries representing the changes.
.. code::
[
{
'type': 'A',
'path': 'path/to/added/file.txt',
},
{
'type': 'D',
'path': 'path/to/deleted/file.txt',
},
{
'type': 'M',
'path': 'path/to/modified/file.txt',
},
{
'type': 'R',
'rename_from': 'original/path/to/file.txt',
'rename_to': 'new/path/to/file.txt',
},
]
:returns: generator
"""
for diff in diff_index:
if diff.new_file:
yield format_diff_A(diff)
elif diff.deleted_file:
yield format_diff_D(diff)
elif diff.renamed:
yield format_diff_R(diff)
elif diff.a_blob and diff.b_blob and diff.a_blob != diff.b_blob:
yield format_diff_M(diff) | python | def format_diffindex(diff_index):
"""
Return a JSON formattable representation of a DiffIndex.
Returns a generator that returns dictionaries representing the changes.
.. code::
[
{
'type': 'A',
'path': 'path/to/added/file.txt',
},
{
'type': 'D',
'path': 'path/to/deleted/file.txt',
},
{
'type': 'M',
'path': 'path/to/modified/file.txt',
},
{
'type': 'R',
'rename_from': 'original/path/to/file.txt',
'rename_to': 'new/path/to/file.txt',
},
]
:returns: generator
"""
for diff in diff_index:
if diff.new_file:
yield format_diff_A(diff)
elif diff.deleted_file:
yield format_diff_D(diff)
elif diff.renamed:
yield format_diff_R(diff)
elif diff.a_blob and diff.b_blob and diff.a_blob != diff.b_blob:
yield format_diff_M(diff) | [
"def",
"format_diffindex",
"(",
"diff_index",
")",
":",
"for",
"diff",
"in",
"diff_index",
":",
"if",
"diff",
".",
"new_file",
":",
"yield",
"format_diff_A",
"(",
"diff",
")",
"elif",
"diff",
".",
"deleted_file",
":",
"yield",
"format_diff_D",
"(",
"diff",
... | Return a JSON formattable representation of a DiffIndex.
Returns a generator that returns dictionaries representing the changes.
.. code::
[
{
'type': 'A',
'path': 'path/to/added/file.txt',
},
{
'type': 'D',
'path': 'path/to/deleted/file.txt',
},
{
'type': 'M',
'path': 'path/to/modified/file.txt',
},
{
'type': 'R',
'rename_from': 'original/path/to/file.txt',
'rename_to': 'new/path/to/file.txt',
},
]
:returns: generator | [
"Return",
"a",
"JSON",
"formattable",
"representation",
"of",
"a",
"DiffIndex",
"."
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L252-L290 |
242,837 | universalcore/unicore.distribute | unicore/distribute/utils.py | format_content_type | def format_content_type(repo, content_type):
"""
Return a list of all content objects for a given content type
in a repository.
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: list
"""
storage_manager = StorageManager(repo)
model_class = load_model_class(repo, content_type)
return [dict(model_obj)
for model_obj in storage_manager.iterate(model_class)] | python | def format_content_type(repo, content_type):
"""
Return a list of all content objects for a given content type
in a repository.
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: list
"""
storage_manager = StorageManager(repo)
model_class = load_model_class(repo, content_type)
return [dict(model_obj)
for model_obj in storage_manager.iterate(model_class)] | [
"def",
"format_content_type",
"(",
"repo",
",",
"content_type",
")",
":",
"storage_manager",
"=",
"StorageManager",
"(",
"repo",
")",
"model_class",
"=",
"load_model_class",
"(",
"repo",
",",
"content_type",
")",
"return",
"[",
"dict",
"(",
"model_obj",
")",
"... | Return a list of all content objects for a given content type
in a repository.
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: list | [
"Return",
"a",
"list",
"of",
"all",
"content",
"objects",
"for",
"a",
"given",
"content",
"type",
"in",
"a",
"repository",
"."
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L293-L307 |
242,838 | universalcore/unicore.distribute | unicore/distribute/utils.py | format_content_type_object | def format_content_type_object(repo, content_type, uuid):
"""
Return a content object from a repository for a given content_type
and uuid
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: dict
"""
try:
storage_manager = StorageManager(repo)
model_class = load_model_class(repo, content_type)
return dict(storage_manager.get(model_class, uuid))
except GitCommandError:
raise NotFound('Object does not exist.') | python | def format_content_type_object(repo, content_type, uuid):
"""
Return a content object from a repository for a given content_type
and uuid
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: dict
"""
try:
storage_manager = StorageManager(repo)
model_class = load_model_class(repo, content_type)
return dict(storage_manager.get(model_class, uuid))
except GitCommandError:
raise NotFound('Object does not exist.') | [
"def",
"format_content_type_object",
"(",
"repo",
",",
"content_type",
",",
"uuid",
")",
":",
"try",
":",
"storage_manager",
"=",
"StorageManager",
"(",
"repo",
")",
"model_class",
"=",
"load_model_class",
"(",
"repo",
",",
"content_type",
")",
"return",
"dict",... | Return a content object from a repository for a given content_type
and uuid
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: dict | [
"Return",
"a",
"content",
"object",
"from",
"a",
"repository",
"for",
"a",
"given",
"content_type",
"and",
"uuid"
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L310-L326 |
242,839 | universalcore/unicore.distribute | unicore/distribute/utils.py | format_repo_status | def format_repo_status(repo):
"""
Return a dictionary representing the repository status
It returns ``None`` for things we do not support or are not
relevant.
:param str repo_name:
The name of the repository.
:returns: dict
"""
commit = repo.commit()
return {
'name': os.path.basename(repo.working_dir),
'commit': commit.hexsha,
'timestamp': datetime.fromtimestamp(
commit.committed_date).isoformat(),
} | python | def format_repo_status(repo):
"""
Return a dictionary representing the repository status
It returns ``None`` for things we do not support or are not
relevant.
:param str repo_name:
The name of the repository.
:returns: dict
"""
commit = repo.commit()
return {
'name': os.path.basename(repo.working_dir),
'commit': commit.hexsha,
'timestamp': datetime.fromtimestamp(
commit.committed_date).isoformat(),
} | [
"def",
"format_repo_status",
"(",
"repo",
")",
":",
"commit",
"=",
"repo",
".",
"commit",
"(",
")",
"return",
"{",
"'name'",
":",
"os",
".",
"path",
".",
"basename",
"(",
"repo",
".",
"working_dir",
")",
",",
"'commit'",
":",
"commit",
".",
"hexsha",
... | Return a dictionary representing the repository status
It returns ``None`` for things we do not support or are not
relevant.
:param str repo_name:
The name of the repository.
:returns: dict | [
"Return",
"a",
"dictionary",
"representing",
"the",
"repository",
"status"
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L329-L347 |
242,840 | universalcore/unicore.distribute | unicore/distribute/utils.py | save_content_type_object | def save_content_type_object(repo, schema, uuid, data):
"""
Save an object as a certain content type
"""
storage_manager = StorageManager(repo)
model_class = deserialize(schema,
module_name=schema['namespace'])
model = model_class(data)
commit = storage_manager.store(model, 'Updated via PUT request.')
return commit, model | python | def save_content_type_object(repo, schema, uuid, data):
"""
Save an object as a certain content type
"""
storage_manager = StorageManager(repo)
model_class = deserialize(schema,
module_name=schema['namespace'])
model = model_class(data)
commit = storage_manager.store(model, 'Updated via PUT request.')
return commit, model | [
"def",
"save_content_type_object",
"(",
"repo",
",",
"schema",
",",
"uuid",
",",
"data",
")",
":",
"storage_manager",
"=",
"StorageManager",
"(",
"repo",
")",
"model_class",
"=",
"deserialize",
"(",
"schema",
",",
"module_name",
"=",
"schema",
"[",
"'namespace... | Save an object as a certain content type | [
"Save",
"an",
"object",
"as",
"a",
"certain",
"content",
"type"
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L350-L359 |
242,841 | universalcore/unicore.distribute | unicore/distribute/utils.py | delete_content_type_object | def delete_content_type_object(repo, content_type, uuid):
"""
Delete an object of a certain content type
"""
storage_manager = StorageManager(repo)
model_class = load_model_class(repo, content_type)
model = storage_manager.get(model_class, uuid)
commit = storage_manager.delete(model, 'Deleted via DELETE request.')
return commit, model | python | def delete_content_type_object(repo, content_type, uuid):
"""
Delete an object of a certain content type
"""
storage_manager = StorageManager(repo)
model_class = load_model_class(repo, content_type)
model = storage_manager.get(model_class, uuid)
commit = storage_manager.delete(model, 'Deleted via DELETE request.')
return commit, model | [
"def",
"delete_content_type_object",
"(",
"repo",
",",
"content_type",
",",
"uuid",
")",
":",
"storage_manager",
"=",
"StorageManager",
"(",
"repo",
")",
"model_class",
"=",
"load_model_class",
"(",
"repo",
",",
"content_type",
")",
"model",
"=",
"storage_manager"... | Delete an object of a certain content type | [
"Delete",
"an",
"object",
"of",
"a",
"certain",
"content",
"type"
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L362-L370 |
242,842 | universalcore/unicore.distribute | unicore/distribute/utils.py | load_model_class | def load_model_class(repo, content_type):
"""
Return a model class for a content type in a repository.
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: class
"""
schema = get_schema(repo, content_type).to_json()
return deserialize(schema, module_name=schema['namespace']) | python | def load_model_class(repo, content_type):
"""
Return a model class for a content type in a repository.
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: class
"""
schema = get_schema(repo, content_type).to_json()
return deserialize(schema, module_name=schema['namespace']) | [
"def",
"load_model_class",
"(",
"repo",
",",
"content_type",
")",
":",
"schema",
"=",
"get_schema",
"(",
"repo",
",",
"content_type",
")",
".",
"to_json",
"(",
")",
"return",
"deserialize",
"(",
"schema",
",",
"module_name",
"=",
"schema",
"[",
"'namespace'"... | Return a model class for a content type in a repository.
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: class | [
"Return",
"a",
"model",
"class",
"for",
"a",
"content",
"type",
"in",
"a",
"repository",
"."
] | f3216fefd9df5aef31b3d1b666eb3f79db032d98 | https://github.com/universalcore/unicore.distribute/blob/f3216fefd9df5aef31b3d1b666eb3f79db032d98/unicore/distribute/utils.py#L409-L420 |
242,843 | binilinlquad/bing-search-api | bing_search_api/api.py | BingSearchAPI.search_composite | def search_composite(self, query, source, payload=None):
'''Shortcut search with composite source'''
source = '+'.join(source)
if payload is None:
payload = dict(Sources=quote(source))
else:
payload['Sources'] = quote(source)
return self.search(query, 'Composite', payload) | python | def search_composite(self, query, source, payload=None):
'''Shortcut search with composite source'''
source = '+'.join(source)
if payload is None:
payload = dict(Sources=quote(source))
else:
payload['Sources'] = quote(source)
return self.search(query, 'Composite', payload) | [
"def",
"search_composite",
"(",
"self",
",",
"query",
",",
"source",
",",
"payload",
"=",
"None",
")",
":",
"source",
"=",
"'+'",
".",
"join",
"(",
"source",
")",
"if",
"payload",
"is",
"None",
":",
"payload",
"=",
"dict",
"(",
"Sources",
"=",
"quote... | Shortcut search with composite source | [
"Shortcut",
"search",
"with",
"composite",
"source"
] | c3a296ad7d0050dc929eda9d9760df5c15faa51a | https://github.com/binilinlquad/bing-search-api/blob/c3a296ad7d0050dc929eda9d9760df5c15faa51a/bing_search_api/api.py#L62-L71 |
242,844 | pop/GrindStone | grindstone/lib.py | key_of | def key_of(d):
"""
Returns the key of a single element dict.
"""
if len(d) > 1 and not type(d) == dict():
raise ValueError('key_of(d) may only except single element dict')
else:
return keys_of(d)[0] | python | def key_of(d):
"""
Returns the key of a single element dict.
"""
if len(d) > 1 and not type(d) == dict():
raise ValueError('key_of(d) may only except single element dict')
else:
return keys_of(d)[0] | [
"def",
"key_of",
"(",
"d",
")",
":",
"if",
"len",
"(",
"d",
")",
">",
"1",
"and",
"not",
"type",
"(",
"d",
")",
"==",
"dict",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'key_of(d) may only except single element dict'",
")",
"else",
":",
"return",
"key... | Returns the key of a single element dict. | [
"Returns",
"the",
"key",
"of",
"a",
"single",
"element",
"dict",
"."
] | 1c788389689faa3f9b223763eb1c946f59ab972a | https://github.com/pop/GrindStone/blob/1c788389689faa3f9b223763eb1c946f59ab972a/grindstone/lib.py#L12-L19 |
242,845 | pop/GrindStone | grindstone/lib.py | GrindStone.open_grindstone | def open_grindstone(self):
"""
Opens a grindstone file and populates the grindstone with it's
contents.
Returns an empty grindstone json object if a file does not exist.
"""
try:
with open(self.grindstone_path, 'r') as f:
# Try opening the file
return json.loads(f.read())
# If the file is empty
except json.decoder.JSONDecodeError:
# Default return empty object with empty tasks list
return {'tasks': []}
# The file does not yet exist
except FileNotFoundError:
# Default return empty object with empty tasks list
return {'tasks': []} | python | def open_grindstone(self):
"""
Opens a grindstone file and populates the grindstone with it's
contents.
Returns an empty grindstone json object if a file does not exist.
"""
try:
with open(self.grindstone_path, 'r') as f:
# Try opening the file
return json.loads(f.read())
# If the file is empty
except json.decoder.JSONDecodeError:
# Default return empty object with empty tasks list
return {'tasks': []}
# The file does not yet exist
except FileNotFoundError:
# Default return empty object with empty tasks list
return {'tasks': []} | [
"def",
"open_grindstone",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"grindstone_path",
",",
"'r'",
")",
"as",
"f",
":",
"# Try opening the file",
"return",
"json",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
")",
"# If the... | Opens a grindstone file and populates the grindstone with it's
contents.
Returns an empty grindstone json object if a file does not exist. | [
"Opens",
"a",
"grindstone",
"file",
"and",
"populates",
"the",
"grindstone",
"with",
"it",
"s",
"contents",
".",
"Returns",
"an",
"empty",
"grindstone",
"json",
"object",
"if",
"a",
"file",
"does",
"not",
"exist",
"."
] | 1c788389689faa3f9b223763eb1c946f59ab972a | https://github.com/pop/GrindStone/blob/1c788389689faa3f9b223763eb1c946f59ab972a/grindstone/lib.py#L49-L66 |
242,846 | pop/GrindStone | grindstone/lib.py | GrindStone.delete_task | def delete_task(self, task=None):
"""
Deletes a given task by name.
"""
# Iterate over the list of tasks
for t in self.grindstone['tasks']:
# If they key of the task matches the task given
if key_of(t) == task:
# Remove that task
self.grindstone['tasks'].remove(t)
# Return True because something did happen
return True
# Return false because nothing happened
return False | python | def delete_task(self, task=None):
"""
Deletes a given task by name.
"""
# Iterate over the list of tasks
for t in self.grindstone['tasks']:
# If they key of the task matches the task given
if key_of(t) == task:
# Remove that task
self.grindstone['tasks'].remove(t)
# Return True because something did happen
return True
# Return false because nothing happened
return False | [
"def",
"delete_task",
"(",
"self",
",",
"task",
"=",
"None",
")",
":",
"# Iterate over the list of tasks",
"for",
"t",
"in",
"self",
".",
"grindstone",
"[",
"'tasks'",
"]",
":",
"# If they key of the task matches the task given",
"if",
"key_of",
"(",
"t",
")",
"... | Deletes a given task by name. | [
"Deletes",
"a",
"given",
"task",
"by",
"name",
"."
] | 1c788389689faa3f9b223763eb1c946f59ab972a | https://github.com/pop/GrindStone/blob/1c788389689faa3f9b223763eb1c946f59ab972a/grindstone/lib.py#L86-L99 |
242,847 | pop/GrindStone | grindstone/lib.py | GrindStone.write_grindstone | def write_grindstone(self):
"""
Writes self.gs to self.grindstone_path.
"""
with open(self.grindstone_path, 'w') as f:
# Write the JSON dump of the file
f.write(json.dumps(self.grindstone)) | python | def write_grindstone(self):
"""
Writes self.gs to self.grindstone_path.
"""
with open(self.grindstone_path, 'w') as f:
# Write the JSON dump of the file
f.write(json.dumps(self.grindstone)) | [
"def",
"write_grindstone",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"grindstone_path",
",",
"'w'",
")",
"as",
"f",
":",
"# Write the JSON dump of the file",
"f",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"grindstone",
")",
... | Writes self.gs to self.grindstone_path. | [
"Writes",
"self",
".",
"gs",
"to",
"self",
".",
"grindstone_path",
"."
] | 1c788389689faa3f9b223763eb1c946f59ab972a | https://github.com/pop/GrindStone/blob/1c788389689faa3f9b223763eb1c946f59ab972a/grindstone/lib.py#L102-L108 |
242,848 | scivision/histutils | histutils/timedmc.py | datetime2unix | def datetime2unix(T):
"""
converts datetime to UT1 unix epoch time
"""
T = atleast_1d(T)
ut1_unix = empty(T.shape, dtype=float)
for i, t in enumerate(T):
if isinstance(t, (datetime, datetime64)):
pass
elif isinstance(t, str):
try:
ut1_unix[i] = float(t) # it was ut1_unix in a string
continue
except ValueError:
t = parse(t) # datetime in a string
elif isinstance(t, (float, int)): # assuming ALL are ut1_unix already
return T
else:
raise TypeError('I only accept datetime or parseable date string')
# ut1 seconds since unix epoch, need [] for error case
ut1_unix[i] = forceutc(t).timestamp()
return ut1_unix | python | def datetime2unix(T):
"""
converts datetime to UT1 unix epoch time
"""
T = atleast_1d(T)
ut1_unix = empty(T.shape, dtype=float)
for i, t in enumerate(T):
if isinstance(t, (datetime, datetime64)):
pass
elif isinstance(t, str):
try:
ut1_unix[i] = float(t) # it was ut1_unix in a string
continue
except ValueError:
t = parse(t) # datetime in a string
elif isinstance(t, (float, int)): # assuming ALL are ut1_unix already
return T
else:
raise TypeError('I only accept datetime or parseable date string')
# ut1 seconds since unix epoch, need [] for error case
ut1_unix[i] = forceutc(t).timestamp()
return ut1_unix | [
"def",
"datetime2unix",
"(",
"T",
")",
":",
"T",
"=",
"atleast_1d",
"(",
"T",
")",
"ut1_unix",
"=",
"empty",
"(",
"T",
".",
"shape",
",",
"dtype",
"=",
"float",
")",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"T",
")",
":",
"if",
"isinstance",... | converts datetime to UT1 unix epoch time | [
"converts",
"datetime",
"to",
"UT1",
"unix",
"epoch",
"time"
] | 859a91d3894cb57faed34881c6ea16130b90571e | https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/timedmc.py#L69-L93 |
242,849 | tshlabs/tunic | tunic/install.py | _is_iterable | def _is_iterable(val):
"""Ensure that a value is iterable and not some sort of string"""
try:
iter(val)
except (ValueError, TypeError):
return False
else:
return not isinstance(val, basestring) | python | def _is_iterable(val):
"""Ensure that a value is iterable and not some sort of string"""
try:
iter(val)
except (ValueError, TypeError):
return False
else:
return not isinstance(val, basestring) | [
"def",
"_is_iterable",
"(",
"val",
")",
":",
"try",
":",
"iter",
"(",
"val",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"False",
"else",
":",
"return",
"not",
"isinstance",
"(",
"val",
",",
"basestring",
")"
] | Ensure that a value is iterable and not some sort of string | [
"Ensure",
"that",
"a",
"value",
"is",
"iterable",
"and",
"not",
"some",
"sort",
"of",
"string"
] | 621f4398d59a9c9eb8dd602beadff11616048aa0 | https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/install.py#L23-L30 |
242,850 | tshlabs/tunic | tunic/install.py | download_url | def download_url(url, destination, retries=None, retry_delay=None, runner=None):
"""Download the given URL with wget to the provided path. The command is
run via Fabric on the current remote machine. Therefore, the destination
path should be for the remote machine.
:param str url: URL to download onto the remote machine
:param str destination: Path to download the URL to on the remote
machine
:param int retries: Max number of times to retry downloads after a failure
:param float retry_delay: Number of seconds between download retries
:param FabRunner runner: Optional runner to use for executing commands.
:return: The results of the wget call
"""
runner = runner if runner is not None else FabRunner()
return try_repeatedly(
lambda: runner.run("wget --quiet --output-document '{0}' '{1}'".format(destination, url)),
max_retries=retries,
delay=retry_delay
) | python | def download_url(url, destination, retries=None, retry_delay=None, runner=None):
"""Download the given URL with wget to the provided path. The command is
run via Fabric on the current remote machine. Therefore, the destination
path should be for the remote machine.
:param str url: URL to download onto the remote machine
:param str destination: Path to download the URL to on the remote
machine
:param int retries: Max number of times to retry downloads after a failure
:param float retry_delay: Number of seconds between download retries
:param FabRunner runner: Optional runner to use for executing commands.
:return: The results of the wget call
"""
runner = runner if runner is not None else FabRunner()
return try_repeatedly(
lambda: runner.run("wget --quiet --output-document '{0}' '{1}'".format(destination, url)),
max_retries=retries,
delay=retry_delay
) | [
"def",
"download_url",
"(",
"url",
",",
"destination",
",",
"retries",
"=",
"None",
",",
"retry_delay",
"=",
"None",
",",
"runner",
"=",
"None",
")",
":",
"runner",
"=",
"runner",
"if",
"runner",
"is",
"not",
"None",
"else",
"FabRunner",
"(",
")",
"ret... | Download the given URL with wget to the provided path. The command is
run via Fabric on the current remote machine. Therefore, the destination
path should be for the remote machine.
:param str url: URL to download onto the remote machine
:param str destination: Path to download the URL to on the remote
machine
:param int retries: Max number of times to retry downloads after a failure
:param float retry_delay: Number of seconds between download retries
:param FabRunner runner: Optional runner to use for executing commands.
:return: The results of the wget call | [
"Download",
"the",
"given",
"URL",
"with",
"wget",
"to",
"the",
"provided",
"path",
".",
"The",
"command",
"is",
"run",
"via",
"Fabric",
"on",
"the",
"current",
"remote",
"machine",
".",
"Therefore",
"the",
"destination",
"path",
"should",
"be",
"for",
"th... | 621f4398d59a9c9eb8dd602beadff11616048aa0 | https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/install.py#L287-L305 |
242,851 | tshlabs/tunic | tunic/install.py | VirtualEnvInstallation._get_install_sources | def _get_install_sources(self):
"""Construct arguments to use alternative package indexes if
there were sources supplied, empty string if there were not.
"""
if not self._sources:
return ''
parts = ['--no-index']
for source in self._sources:
parts.append("--find-links '{0}'".format(source))
return ' '.join(parts) | python | def _get_install_sources(self):
"""Construct arguments to use alternative package indexes if
there were sources supplied, empty string if there were not.
"""
if not self._sources:
return ''
parts = ['--no-index']
for source in self._sources:
parts.append("--find-links '{0}'".format(source))
return ' '.join(parts) | [
"def",
"_get_install_sources",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_sources",
":",
"return",
"''",
"parts",
"=",
"[",
"'--no-index'",
"]",
"for",
"source",
"in",
"self",
".",
"_sources",
":",
"parts",
".",
"append",
"(",
"\"--find-links '{0}'... | Construct arguments to use alternative package indexes if
there were sources supplied, empty string if there were not. | [
"Construct",
"arguments",
"to",
"use",
"alternative",
"package",
"indexes",
"if",
"there",
"were",
"sources",
"supplied",
"empty",
"string",
"if",
"there",
"were",
"not",
"."
] | 621f4398d59a9c9eb8dd602beadff11616048aa0 | https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/install.py#L95-L104 |
242,852 | tshlabs/tunic | tunic/install.py | VirtualEnvInstallation.install | def install(self, release_id, upgrade=False):
"""Install target packages into a virtual environment.
If the virtual environment for the given release ID does not
exist on the remote system, it will be created. The virtual
environment will be created according to the standard Tunic
directory structure (see :doc:`design`).
If ``upgrade=True`` is passed, packages will be updated to the
most recent version if they are already installed in the virtual
environment.
:param str release_id: Timestamp-based identifier for this
deployment. If this ID corresponds to a virtual environment
that already exists, packages will be installed into this
environment.
:param bool upgrade: Should packages be updated if they are
already installed in the virtual environment.
:return: The results of running the installation command using
Fabric. Note that this return value is a decorated version
of a string that contains additional meta data about the
result of the command, in addition to the output generated.
:rtype: str
"""
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("{0} '{1}'".format(self._venv_path, release_path))
cmd = [os.path.join(release_path, 'bin', 'pip'), 'install']
if upgrade:
cmd.append('--upgrade')
sources = self._get_install_sources()
if sources:
cmd.append(sources)
cmd.extend("'{0}'".format(package) for package in self._packages)
return self._runner.run(' '.join(cmd)) | python | def install(self, release_id, upgrade=False):
"""Install target packages into a virtual environment.
If the virtual environment for the given release ID does not
exist on the remote system, it will be created. The virtual
environment will be created according to the standard Tunic
directory structure (see :doc:`design`).
If ``upgrade=True`` is passed, packages will be updated to the
most recent version if they are already installed in the virtual
environment.
:param str release_id: Timestamp-based identifier for this
deployment. If this ID corresponds to a virtual environment
that already exists, packages will be installed into this
environment.
:param bool upgrade: Should packages be updated if they are
already installed in the virtual environment.
:return: The results of running the installation command using
Fabric. Note that this return value is a decorated version
of a string that contains additional meta data about the
result of the command, in addition to the output generated.
:rtype: str
"""
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("{0} '{1}'".format(self._venv_path, release_path))
cmd = [os.path.join(release_path, 'bin', 'pip'), 'install']
if upgrade:
cmd.append('--upgrade')
sources = self._get_install_sources()
if sources:
cmd.append(sources)
cmd.extend("'{0}'".format(package) for package in self._packages)
return self._runner.run(' '.join(cmd)) | [
"def",
"install",
"(",
"self",
",",
"release_id",
",",
"upgrade",
"=",
"False",
")",
":",
"release_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_releases",
",",
"release_id",
")",
"if",
"not",
"self",
".",
"_runner",
".",
"exists",
... | Install target packages into a virtual environment.
If the virtual environment for the given release ID does not
exist on the remote system, it will be created. The virtual
environment will be created according to the standard Tunic
directory structure (see :doc:`design`).
If ``upgrade=True`` is passed, packages will be updated to the
most recent version if they are already installed in the virtual
environment.
:param str release_id: Timestamp-based identifier for this
deployment. If this ID corresponds to a virtual environment
that already exists, packages will be installed into this
environment.
:param bool upgrade: Should packages be updated if they are
already installed in the virtual environment.
:return: The results of running the installation command using
Fabric. Note that this return value is a decorated version
of a string that contains additional meta data about the
result of the command, in addition to the output generated.
:rtype: str | [
"Install",
"target",
"packages",
"into",
"a",
"virtual",
"environment",
"."
] | 621f4398d59a9c9eb8dd602beadff11616048aa0 | https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/install.py#L106-L143 |
242,853 | tshlabs/tunic | tunic/install.py | StaticFileInstallation.install | def install(self, release_id):
"""Install the contents of the local directory into a release directory.
If the directory for the given release ID does not exist on the remote
system, it will be created. The directory will be created according to
the standard Tunic directory structure (see :doc:`design`).
Note that the name and path of the local directory is irrelevant, only
the contents of the specified directory will be transferred to the remote
server. The contents will end up as children of the release directory on
the remote server.
:param str release_id: Timestamp-based identifier for this
deployment. If this ID corresponds to a directory that already
exists, contents of the local directory will be copied into
this directory.
:return: The results of the ``put`` command using Fabric. This return
value is an iterable of the paths of all files uploaded on the remote
server.
"""
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("mkdir -p '{0}'".format(release_path))
# Make sure to remove any user supplied globs or trailing slashes
# so that we can ensure exactly the glob behavior we want from the
# put command.
local_path = self._local_path.strip('*').strip(os.path.sep)
return self._runner.put(os.path.join(local_path, '*'), release_path) | python | def install(self, release_id):
"""Install the contents of the local directory into a release directory.
If the directory for the given release ID does not exist on the remote
system, it will be created. The directory will be created according to
the standard Tunic directory structure (see :doc:`design`).
Note that the name and path of the local directory is irrelevant, only
the contents of the specified directory will be transferred to the remote
server. The contents will end up as children of the release directory on
the remote server.
:param str release_id: Timestamp-based identifier for this
deployment. If this ID corresponds to a directory that already
exists, contents of the local directory will be copied into
this directory.
:return: The results of the ``put`` command using Fabric. This return
value is an iterable of the paths of all files uploaded on the remote
server.
"""
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("mkdir -p '{0}'".format(release_path))
# Make sure to remove any user supplied globs or trailing slashes
# so that we can ensure exactly the glob behavior we want from the
# put command.
local_path = self._local_path.strip('*').strip(os.path.sep)
return self._runner.put(os.path.join(local_path, '*'), release_path) | [
"def",
"install",
"(",
"self",
",",
"release_id",
")",
":",
"release_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_releases",
",",
"release_id",
")",
"if",
"not",
"self",
".",
"_runner",
".",
"exists",
"(",
"release_path",
")",
":",
... | Install the contents of the local directory into a release directory.
If the directory for the given release ID does not exist on the remote
system, it will be created. The directory will be created according to
the standard Tunic directory structure (see :doc:`design`).
Note that the name and path of the local directory is irrelevant, only
the contents of the specified directory will be transferred to the remote
server. The contents will end up as children of the release directory on
the remote server.
:param str release_id: Timestamp-based identifier for this
deployment. If this ID corresponds to a directory that already
exists, contents of the local directory will be copied into
this directory.
:return: The results of the ``put`` command using Fabric. This return
value is an iterable of the paths of all files uploaded on the remote
server. | [
"Install",
"the",
"contents",
"of",
"the",
"local",
"directory",
"into",
"a",
"release",
"directory",
"."
] | 621f4398d59a9c9eb8dd602beadff11616048aa0 | https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/install.py#L181-L209 |
242,854 | tshlabs/tunic | tunic/install.py | LocalArtifactInstallation.install | def install(self, release_id):
"""Install the local artifact into the remote release directory, optionally
with a different name than the artifact had locally.
If the directory for the given release ID does not exist on the remote
system, it will be created. The directory will be created according to
the standard Tunic directory structure (see :doc:`design`).
:param str release_id: Timestamp-based identifier for this deployment.
:param int retries: Max number of times to retry downloads after a failure
:param float retry_delay: Number of seconds between download retries
:return: The results of the ``put`` command using Fabric. This return
value is an iterable of the paths of all files uploaded on the remote
server.
"""
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("mkdir -p '{0}'".format(release_path))
# The artifact can optionally be renamed when being uploaded to
# remote server. Useful for when we need a consistent name for
# each deploy on the remote server but the local artifact includes
# version numbers or something.
if self._remote_name is not None:
destination = os.path.join(release_path, self._remote_name)
else:
destination = release_path
return self._runner.put(self._local_file, destination, mirror_local_mode=True) | python | def install(self, release_id):
"""Install the local artifact into the remote release directory, optionally
with a different name than the artifact had locally.
If the directory for the given release ID does not exist on the remote
system, it will be created. The directory will be created according to
the standard Tunic directory structure (see :doc:`design`).
:param str release_id: Timestamp-based identifier for this deployment.
:param int retries: Max number of times to retry downloads after a failure
:param float retry_delay: Number of seconds between download retries
:return: The results of the ``put`` command using Fabric. This return
value is an iterable of the paths of all files uploaded on the remote
server.
"""
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("mkdir -p '{0}'".format(release_path))
# The artifact can optionally be renamed when being uploaded to
# remote server. Useful for when we need a consistent name for
# each deploy on the remote server but the local artifact includes
# version numbers or something.
if self._remote_name is not None:
destination = os.path.join(release_path, self._remote_name)
else:
destination = release_path
return self._runner.put(self._local_file, destination, mirror_local_mode=True) | [
"def",
"install",
"(",
"self",
",",
"release_id",
")",
":",
"release_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_releases",
",",
"release_id",
")",
"if",
"not",
"self",
".",
"_runner",
".",
"exists",
"(",
"release_path",
")",
":",
... | Install the local artifact into the remote release directory, optionally
with a different name than the artifact had locally.
If the directory for the given release ID does not exist on the remote
system, it will be created. The directory will be created according to
the standard Tunic directory structure (see :doc:`design`).
:param str release_id: Timestamp-based identifier for this deployment.
:param int retries: Max number of times to retry downloads after a failure
:param float retry_delay: Number of seconds between download retries
:return: The results of the ``put`` command using Fabric. This return
value is an iterable of the paths of all files uploaded on the remote
server. | [
"Install",
"the",
"local",
"artifact",
"into",
"the",
"remote",
"release",
"directory",
"optionally",
"with",
"a",
"different",
"name",
"than",
"the",
"artifact",
"had",
"locally",
"."
] | 621f4398d59a9c9eb8dd602beadff11616048aa0 | https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/install.py#L256-L284 |
242,855 | tshlabs/tunic | tunic/install.py | HttpArtifactInstallation._get_file_from_url | def _get_file_from_url(url):
"""Get the filename part of the path component from a URL."""
path = urlparse(url).path
if not path:
raise ValueError("Could not extract path from URL '{0}'".format(url))
name = os.path.basename(path)
if not name:
raise ValueError("Could not extract file name from path '{0}'".format(path))
return name | python | def _get_file_from_url(url):
"""Get the filename part of the path component from a URL."""
path = urlparse(url).path
if not path:
raise ValueError("Could not extract path from URL '{0}'".format(url))
name = os.path.basename(path)
if not name:
raise ValueError("Could not extract file name from path '{0}'".format(path))
return name | [
"def",
"_get_file_from_url",
"(",
"url",
")",
":",
"path",
"=",
"urlparse",
"(",
"url",
")",
".",
"path",
"if",
"not",
"path",
":",
"raise",
"ValueError",
"(",
"\"Could not extract path from URL '{0}'\"",
".",
"format",
"(",
"url",
")",
")",
"name",
"=",
"... | Get the filename part of the path component from a URL. | [
"Get",
"the",
"filename",
"part",
"of",
"the",
"path",
"component",
"from",
"a",
"URL",
"."
] | 621f4398d59a9c9eb8dd602beadff11616048aa0 | https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/install.py#L388-L396 |
242,856 | tshlabs/tunic | tunic/install.py | HttpArtifactInstallation.install | def install(self, release_id):
"""Download and install an artifact into the remote release directory,
optionally with a different name the the artifact had.
If the directory for the given release ID does not exist on the remote
system, it will be created. The directory will be created according to
the standard Tunic directory structure (see :doc:`design`).
:param str release_id: Timestamp-based identifier for this deployment.
:return: The results of the download function being run. This return value
should be the result of running a command with Fabric. By default
this will be the result of running ``wget``.
"""
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("mkdir -p '{0}'".format(release_path))
# The artifact can optionally be renamed to something specific when
# downloaded on the remote server. In that case use the provided name
# in the download path. Otherwise, just use the last component of
# of the URL we're downloading.
if self._remote_name is not None:
destination = os.path.join(release_path, self._remote_name)
else:
destination = os.path.join(release_path, self._get_file_from_url(self._artifact_url))
# Note that although the default implementation of a download method
# accepts a FabRunner instance, we aren't passing our instance here.
# The reason being, that's only needed for testing the download_url
# method. If we were testing class, we'd mock out the download method
# anyway. So, it's not part of the public API of the download interface
# and we don't deal with it here.
return self._downloader(
self._artifact_url,
destination,
retries=self._retries,
retry_delay=self._retry_delay
) | python | def install(self, release_id):
"""Download and install an artifact into the remote release directory,
optionally with a different name the the artifact had.
If the directory for the given release ID does not exist on the remote
system, it will be created. The directory will be created according to
the standard Tunic directory structure (see :doc:`design`).
:param str release_id: Timestamp-based identifier for this deployment.
:return: The results of the download function being run. This return value
should be the result of running a command with Fabric. By default
this will be the result of running ``wget``.
"""
release_path = os.path.join(self._releases, release_id)
if not self._runner.exists(release_path):
self._runner.run("mkdir -p '{0}'".format(release_path))
# The artifact can optionally be renamed to something specific when
# downloaded on the remote server. In that case use the provided name
# in the download path. Otherwise, just use the last component of
# of the URL we're downloading.
if self._remote_name is not None:
destination = os.path.join(release_path, self._remote_name)
else:
destination = os.path.join(release_path, self._get_file_from_url(self._artifact_url))
# Note that although the default implementation of a download method
# accepts a FabRunner instance, we aren't passing our instance here.
# The reason being, that's only needed for testing the download_url
# method. If we were testing class, we'd mock out the download method
# anyway. So, it's not part of the public API of the download interface
# and we don't deal with it here.
return self._downloader(
self._artifact_url,
destination,
retries=self._retries,
retry_delay=self._retry_delay
) | [
"def",
"install",
"(",
"self",
",",
"release_id",
")",
":",
"release_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_releases",
",",
"release_id",
")",
"if",
"not",
"self",
".",
"_runner",
".",
"exists",
"(",
"release_path",
")",
":",
... | Download and install an artifact into the remote release directory,
optionally with a different name the the artifact had.
If the directory for the given release ID does not exist on the remote
system, it will be created. The directory will be created according to
the standard Tunic directory structure (see :doc:`design`).
:param str release_id: Timestamp-based identifier for this deployment.
:return: The results of the download function being run. This return value
should be the result of running a command with Fabric. By default
this will be the result of running ``wget``. | [
"Download",
"and",
"install",
"an",
"artifact",
"into",
"the",
"remote",
"release",
"directory",
"optionally",
"with",
"a",
"different",
"name",
"the",
"the",
"artifact",
"had",
"."
] | 621f4398d59a9c9eb8dd602beadff11616048aa0 | https://github.com/tshlabs/tunic/blob/621f4398d59a9c9eb8dd602beadff11616048aa0/tunic/install.py#L398-L435 |
242,857 | mrstephenneal/dirutility | dirutility/walk/walk.py | pool_process | def pool_process(func, iterable, process_name='Pool processing', cpus=cpu_count()):
"""
Apply a function to each element in an iterable and return a result list.
:param func: A function that returns a value
:param iterable: A list or set of elements to be passed to the func as the singular parameter
:param process_name: Name of the process, for printing purposes only
:param cpus: Number of CPUs
:return: Result list
"""
with Timer('\t{0} ({1}) completed in'.format(process_name, str(func))):
pool = Pool(cpus)
vals = pool.map(func, iterable)
pool.close()
return vals | python | def pool_process(func, iterable, process_name='Pool processing', cpus=cpu_count()):
"""
Apply a function to each element in an iterable and return a result list.
:param func: A function that returns a value
:param iterable: A list or set of elements to be passed to the func as the singular parameter
:param process_name: Name of the process, for printing purposes only
:param cpus: Number of CPUs
:return: Result list
"""
with Timer('\t{0} ({1}) completed in'.format(process_name, str(func))):
pool = Pool(cpus)
vals = pool.map(func, iterable)
pool.close()
return vals | [
"def",
"pool_process",
"(",
"func",
",",
"iterable",
",",
"process_name",
"=",
"'Pool processing'",
",",
"cpus",
"=",
"cpu_count",
"(",
")",
")",
":",
"with",
"Timer",
"(",
"'\\t{0} ({1}) completed in'",
".",
"format",
"(",
"process_name",
",",
"str",
"(",
"... | Apply a function to each element in an iterable and return a result list.
:param func: A function that returns a value
:param iterable: A list or set of elements to be passed to the func as the singular parameter
:param process_name: Name of the process, for printing purposes only
:param cpus: Number of CPUs
:return: Result list | [
"Apply",
"a",
"function",
"to",
"each",
"element",
"in",
"an",
"iterable",
"and",
"return",
"a",
"result",
"list",
"."
] | 339378659e2d7e09c53acfc51c5df745bb0cd517 | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L35-L49 |
242,858 | mrstephenneal/dirutility | dirutility/walk/walk.py | remover | def remover(file_path):
"""Delete a file or directory path only if it exists."""
if os.path.isfile(file_path):
os.remove(file_path)
return True
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
return True
else:
return False | python | def remover(file_path):
"""Delete a file or directory path only if it exists."""
if os.path.isfile(file_path):
os.remove(file_path)
return True
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
return True
else:
return False | [
"def",
"remover",
"(",
"file_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"os",
".",
"remove",
"(",
"file_path",
")",
"return",
"True",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"file_path",
")",
":",
"sh... | Delete a file or directory path only if it exists. | [
"Delete",
"a",
"file",
"or",
"directory",
"path",
"only",
"if",
"it",
"exists",
"."
] | 339378659e2d7e09c53acfc51c5df745bb0cd517 | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L68-L77 |
242,859 | mrstephenneal/dirutility | dirutility/walk/walk.py | creation_date | def creation_date(path_to_file, return_datetime=True):
"""
Retrieve a file's creation date.
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
:param path_to_file: File path
:param return_datetime: Bool, returns value in Datetime format
:return: Creation date
"""
if platform.system() == 'Windows':
created_at = os.path.getctime(path_to_file)
else:
stat = os.stat(path_to_file)
try:
created_at = stat.st_birthtime
except AttributeError:
# We're probably on Linux. No easy way to get creation dates here,
# so we'll settle for when its content was last modified.
created_at = stat.st_mtime
if return_datetime:
return datetime.fromtimestamp(created_at)
else:
return created_at | python | def creation_date(path_to_file, return_datetime=True):
"""
Retrieve a file's creation date.
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
:param path_to_file: File path
:param return_datetime: Bool, returns value in Datetime format
:return: Creation date
"""
if platform.system() == 'Windows':
created_at = os.path.getctime(path_to_file)
else:
stat = os.stat(path_to_file)
try:
created_at = stat.st_birthtime
except AttributeError:
# We're probably on Linux. No easy way to get creation dates here,
# so we'll settle for when its content was last modified.
created_at = stat.st_mtime
if return_datetime:
return datetime.fromtimestamp(created_at)
else:
return created_at | [
"def",
"creation_date",
"(",
"path_to_file",
",",
"return_datetime",
"=",
"True",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"created_at",
"=",
"os",
".",
"path",
".",
"getctime",
"(",
"path_to_file",
")",
"else",
":",
"... | Retrieve a file's creation date.
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
:param path_to_file: File path
:param return_datetime: Bool, returns value in Datetime format
:return: Creation date | [
"Retrieve",
"a",
"file",
"s",
"creation",
"date",
"."
] | 339378659e2d7e09c53acfc51c5df745bb0cd517 | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L80-L107 |
242,860 | mrstephenneal/dirutility | dirutility/walk/walk.py | DirPaths._get_filepaths | def _get_filepaths(self):
"""Filters list of file paths to remove non-included, remove excluded files and concatenate full paths."""
self._printer(str(self.__len__()) + " file paths have been parsed in " + str(self.timer.end))
if self._hash_files:
return pool_hash(self.filepaths)
else:
return self.filepaths | python | def _get_filepaths(self):
"""Filters list of file paths to remove non-included, remove excluded files and concatenate full paths."""
self._printer(str(self.__len__()) + " file paths have been parsed in " + str(self.timer.end))
if self._hash_files:
return pool_hash(self.filepaths)
else:
return self.filepaths | [
"def",
"_get_filepaths",
"(",
"self",
")",
":",
"self",
".",
"_printer",
"(",
"str",
"(",
"self",
".",
"__len__",
"(",
")",
")",
"+",
"\" file paths have been parsed in \"",
"+",
"str",
"(",
"self",
".",
"timer",
".",
"end",
")",
")",
"if",
"self",
"."... | Filters list of file paths to remove non-included, remove excluded files and concatenate full paths. | [
"Filters",
"list",
"of",
"file",
"paths",
"to",
"remove",
"non",
"-",
"included",
"remove",
"excluded",
"files",
"and",
"concatenate",
"full",
"paths",
"."
] | 339378659e2d7e09c53acfc51c5df745bb0cd517 | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L182-L188 |
242,861 | mrstephenneal/dirutility | dirutility/walk/walk.py | DirPaths.files | def files(self):
"""Return list of files in root directory"""
self._printer('\tFiles Walk')
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isfile(full_path):
if not path.startswith('.'):
self.filepaths.append(full_path)
return self._get_filepaths() | python | def files(self):
"""Return list of files in root directory"""
self._printer('\tFiles Walk')
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isfile(full_path):
if not path.startswith('.'):
self.filepaths.append(full_path)
return self._get_filepaths() | [
"def",
"files",
"(",
"self",
")",
":",
"self",
".",
"_printer",
"(",
"'\\tFiles Walk'",
")",
"for",
"directory",
"in",
"self",
".",
"directory",
":",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"full_path",
"=",
"os",
".",
... | Return list of files in root directory | [
"Return",
"list",
"of",
"files",
"in",
"root",
"directory"
] | 339378659e2d7e09c53acfc51c5df745bb0cd517 | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L216-L225 |
242,862 | mrstephenneal/dirutility | dirutility/walk/walk.py | DirPaths.folders | def folders(self):
"""Return list of folders in root directory"""
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isdir(full_path):
if not path.startswith('.'):
self.filepaths.append(full_path)
return self._get_filepaths() | python | def folders(self):
"""Return list of folders in root directory"""
for directory in self.directory:
for path in os.listdir(directory):
full_path = os.path.join(directory, path)
if os.path.isdir(full_path):
if not path.startswith('.'):
self.filepaths.append(full_path)
return self._get_filepaths() | [
"def",
"folders",
"(",
"self",
")",
":",
"for",
"directory",
"in",
"self",
".",
"directory",
":",
"for",
"path",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"path",
... | Return list of folders in root directory | [
"Return",
"list",
"of",
"folders",
"in",
"root",
"directory"
] | 339378659e2d7e09c53acfc51c5df745bb0cd517 | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/walk.py#L227-L235 |
242,863 | drongo-framework/drongo | drongo/app.py | Drongo.url | def url(self, pattern, method=None, name=None):
"""Decorator to map url pattern to the callable.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Examples: "/", "/path/to/resource", "/resoures/{param}"
method (:obj:`str`, :obj:`list` of :obj:`str`, optional): HTTP
methods for the path specied. By default, GET method is added.
Value can be either a single method, by passing a string, or
multiple methods, by passing a list of strings.
name (:obj:`str`): Name for the pattern that can be used for
reverse matching
Note:
A trailing '/' is always assumed in the pattern.
Example:
>>> @app.url(pattern='/path/to/resource', method='GET')
>>> def function(ctx):
>>> return 'Hello world'
See Also:
:func:`drongo.managers.url.UrlManager.add`
"""
def _inner(call):
self._url_manager.add(pattern, method, call, name)
return call
return _inner | python | def url(self, pattern, method=None, name=None):
"""Decorator to map url pattern to the callable.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Examples: "/", "/path/to/resource", "/resoures/{param}"
method (:obj:`str`, :obj:`list` of :obj:`str`, optional): HTTP
methods for the path specied. By default, GET method is added.
Value can be either a single method, by passing a string, or
multiple methods, by passing a list of strings.
name (:obj:`str`): Name for the pattern that can be used for
reverse matching
Note:
A trailing '/' is always assumed in the pattern.
Example:
>>> @app.url(pattern='/path/to/resource', method='GET')
>>> def function(ctx):
>>> return 'Hello world'
See Also:
:func:`drongo.managers.url.UrlManager.add`
"""
def _inner(call):
self._url_manager.add(pattern, method, call, name)
return call
return _inner | [
"def",
"url",
"(",
"self",
",",
"pattern",
",",
"method",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"def",
"_inner",
"(",
"call",
")",
":",
"self",
".",
"_url_manager",
".",
"add",
"(",
"pattern",
",",
"method",
",",
"call",
",",
"name",
"... | Decorator to map url pattern to the callable.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Examples: "/", "/path/to/resource", "/resoures/{param}"
method (:obj:`str`, :obj:`list` of :obj:`str`, optional): HTTP
methods for the path specied. By default, GET method is added.
Value can be either a single method, by passing a string, or
multiple methods, by passing a list of strings.
name (:obj:`str`): Name for the pattern that can be used for
reverse matching
Note:
A trailing '/' is always assumed in the pattern.
Example:
>>> @app.url(pattern='/path/to/resource', method='GET')
>>> def function(ctx):
>>> return 'Hello world'
See Also:
:func:`drongo.managers.url.UrlManager.add` | [
"Decorator",
"to",
"map",
"url",
"pattern",
"to",
"the",
"callable",
"."
] | 487edb370ae329f370bcf3b433ed3f28ba4c1d8c | https://github.com/drongo-framework/drongo/blob/487edb370ae329f370bcf3b433ed3f28ba4c1d8c/drongo/app.py#L86-L115 |
242,864 | shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | GPS.get_exif_data | def get_exif_data(self, image):
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
exif_data = {}
info = image._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "GPSInfo":
gps_data = {}
for t in value:
sub_decoded = GPSTAGS.get(t, t)
gps_data[sub_decoded] = value[t]
exif_data[decoded] = gps_data
else:
exif_data[decoded] = value
return exif_data | python | def get_exif_data(self, image):
"""Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags"""
exif_data = {}
info = image._getexif()
if info:
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
if decoded == "GPSInfo":
gps_data = {}
for t in value:
sub_decoded = GPSTAGS.get(t, t)
gps_data[sub_decoded] = value[t]
exif_data[decoded] = gps_data
else:
exif_data[decoded] = value
return exif_data | [
"def",
"get_exif_data",
"(",
"self",
",",
"image",
")",
":",
"exif_data",
"=",
"{",
"}",
"info",
"=",
"image",
".",
"_getexif",
"(",
")",
"if",
"info",
":",
"for",
"tag",
",",
"value",
"in",
"info",
".",
"items",
"(",
")",
":",
"decoded",
"=",
"T... | Returns a dictionary from the exif data of an PIL Image item. Also converts the GPS Tags | [
"Returns",
"a",
"dictionary",
"from",
"the",
"exif",
"data",
"of",
"an",
"PIL",
"Image",
"item",
".",
"Also",
"converts",
"the",
"GPS",
"Tags"
] | c8da7128ea18ecaa5849f2066d321e70d6f97f70 | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L236-L253 |
242,865 | shi-cong/PYSTUDY | PYSTUDY/image/pillib.py | GPS._convert_to_degress | def _convert_to_degress(self, value):
"""Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
s0 = value[2][0]
s1 = value[2][1]
s = float(s0) / float(s1)
return d + (m / 60.0) + (s / 3600.0) | python | def _convert_to_degress(self, value):
"""Helper function to convert the GPS coordinates stored in the EXIF to degress in float format"""
d0 = value[0][0]
d1 = value[0][1]
d = float(d0) / float(d1)
m0 = value[1][0]
m1 = value[1][1]
m = float(m0) / float(m1)
s0 = value[2][0]
s1 = value[2][1]
s = float(s0) / float(s1)
return d + (m / 60.0) + (s / 3600.0) | [
"def",
"_convert_to_degress",
"(",
"self",
",",
"value",
")",
":",
"d0",
"=",
"value",
"[",
"0",
"]",
"[",
"0",
"]",
"d1",
"=",
"value",
"[",
"0",
"]",
"[",
"1",
"]",
"d",
"=",
"float",
"(",
"d0",
")",
"/",
"float",
"(",
"d1",
")",
"m0",
"=... | Helper function to convert the GPS coordinates stored in the EXIF to degress in float format | [
"Helper",
"function",
"to",
"convert",
"the",
"GPS",
"coordinates",
"stored",
"in",
"the",
"EXIF",
"to",
"degress",
"in",
"float",
"format"
] | c8da7128ea18ecaa5849f2066d321e70d6f97f70 | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/image/pillib.py#L261-L275 |
242,866 | asyncdef/interfaces | asyncdef/interfaces/engine/iselector.py | ISelector.add_reader | def add_reader(
self,
fd: IFileLike,
callback: typing.Callable[[IFileLike], typing.Any],
) -> None:
"""Add a file descriptor to the processor and wait for READ.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
returns a valid file descriptor integer.
callback (typing.Callable[[IFileLike], typing.Any]): A function
that consumes the IFileLike object whenever the READ event is
fired.
"""
raise NotImplementedError() | python | def add_reader(
self,
fd: IFileLike,
callback: typing.Callable[[IFileLike], typing.Any],
) -> None:
"""Add a file descriptor to the processor and wait for READ.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
returns a valid file descriptor integer.
callback (typing.Callable[[IFileLike], typing.Any]): A function
that consumes the IFileLike object whenever the READ event is
fired.
"""
raise NotImplementedError() | [
"def",
"add_reader",
"(",
"self",
",",
"fd",
":",
"IFileLike",
",",
"callback",
":",
"typing",
".",
"Callable",
"[",
"[",
"IFileLike",
"]",
",",
"typing",
".",
"Any",
"]",
",",
")",
"->",
"None",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Add a file descriptor to the processor and wait for READ.
Args:
fd (IFileLike): Any obect that exposes a 'fileno' method that
returns a valid file descriptor integer.
callback (typing.Callable[[IFileLike], typing.Any]): A function
that consumes the IFileLike object whenever the READ event is
fired. | [
"Add",
"a",
"file",
"descriptor",
"to",
"the",
"processor",
"and",
"wait",
"for",
"READ",
"."
] | 17c589c6ab158e3d9977a6d9da6d5ecd44844285 | https://github.com/asyncdef/interfaces/blob/17c589c6ab158e3d9977a6d9da6d5ecd44844285/asyncdef/interfaces/engine/iselector.py#L25-L39 |
242,867 | robertchase/ergaleia | ergaleia/config.py | Config._load | def _load(self, path='config', filetype=None, relaxed=False, ignore=False):
""" load key value pairs from a file
Parameters:
path - path to configuration data (see Note 1)
filetype - type component of dot-delimited path
relaxed - if True, define keys on the fly (see Note 2)
ignore - if True, ignore undefined keys in path
Return:
self
Notes:
1. The path can be:
* an open file object with a readlines method
* a dot delimited path to a file (see normalize_path)
* an os-specific path to a file (relative to cwd)
* an iterable of key=value strings
2. Normally keys read from the file must conform to keys
previously defined for the Config. If the relaxed flag
is True, any keys found in the file will be accepted.
If the ignore flag is True, and kyes found in the file
that are not previously defined are ignored.
"""
for num, line in enumerate(
un_comment(load_lines_from_path(path, filetype)),
start=1,
):
if not line:
continue
try:
key, val = line.split('=', 1)
key = key.strip()
val = val.strip()
if relaxed:
self._define(key)
try:
level, itemname = self.__lookup(key)
except KeyError:
if ignore:
continue
raise
item = level.get(itemname)
if item is None:
raise KeyError(itemname)
item.load(val)
except Exception as e:
args = e.args or ('',)
msg = 'line {} of config: {}'. format(num, args[0])
e.args = (msg,) + args[1:]
raise
return self | python | def _load(self, path='config', filetype=None, relaxed=False, ignore=False):
""" load key value pairs from a file
Parameters:
path - path to configuration data (see Note 1)
filetype - type component of dot-delimited path
relaxed - if True, define keys on the fly (see Note 2)
ignore - if True, ignore undefined keys in path
Return:
self
Notes:
1. The path can be:
* an open file object with a readlines method
* a dot delimited path to a file (see normalize_path)
* an os-specific path to a file (relative to cwd)
* an iterable of key=value strings
2. Normally keys read from the file must conform to keys
previously defined for the Config. If the relaxed flag
is True, any keys found in the file will be accepted.
If the ignore flag is True, and kyes found in the file
that are not previously defined are ignored.
"""
for num, line in enumerate(
un_comment(load_lines_from_path(path, filetype)),
start=1,
):
if not line:
continue
try:
key, val = line.split('=', 1)
key = key.strip()
val = val.strip()
if relaxed:
self._define(key)
try:
level, itemname = self.__lookup(key)
except KeyError:
if ignore:
continue
raise
item = level.get(itemname)
if item is None:
raise KeyError(itemname)
item.load(val)
except Exception as e:
args = e.args or ('',)
msg = 'line {} of config: {}'. format(num, args[0])
e.args = (msg,) + args[1:]
raise
return self | [
"def",
"_load",
"(",
"self",
",",
"path",
"=",
"'config'",
",",
"filetype",
"=",
"None",
",",
"relaxed",
"=",
"False",
",",
"ignore",
"=",
"False",
")",
":",
"for",
"num",
",",
"line",
"in",
"enumerate",
"(",
"un_comment",
"(",
"load_lines_from_path",
... | load key value pairs from a file
Parameters:
path - path to configuration data (see Note 1)
filetype - type component of dot-delimited path
relaxed - if True, define keys on the fly (see Note 2)
ignore - if True, ignore undefined keys in path
Return:
self
Notes:
1. The path can be:
* an open file object with a readlines method
* a dot delimited path to a file (see normalize_path)
* an os-specific path to a file (relative to cwd)
* an iterable of key=value strings
2. Normally keys read from the file must conform to keys
previously defined for the Config. If the relaxed flag
is True, any keys found in the file will be accepted.
If the ignore flag is True, and kyes found in the file
that are not previously defined are ignored. | [
"load",
"key",
"value",
"pairs",
"from",
"a",
"file"
] | df8e9a4b18c563022a503faa27e822c9a5755490 | https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/config.py#L155-L208 |
242,868 | robertchase/ergaleia | ergaleia/config.py | _item.load | def load(self, value):
""" enforce env > value when loading from file """
self.reset(
value,
validator=self.__dict__.get('validator'),
env=self.__dict__.get('env'),
) | python | def load(self, value):
""" enforce env > value when loading from file """
self.reset(
value,
validator=self.__dict__.get('validator'),
env=self.__dict__.get('env'),
) | [
"def",
"load",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"reset",
"(",
"value",
",",
"validator",
"=",
"self",
".",
"__dict__",
".",
"get",
"(",
"'validator'",
")",
",",
"env",
"=",
"self",
".",
"__dict__",
".",
"get",
"(",
"'env'",
")",
... | enforce env > value when loading from file | [
"enforce",
"env",
">",
"value",
"when",
"loading",
"from",
"file"
] | df8e9a4b18c563022a503faa27e822c9a5755490 | https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/config.py#L245-L251 |
242,869 | tBaxter/tango-shared-core | build/lib/tango_shared/models.py | set_img_path | def set_img_path(instance, filename):
"""
Sets upload_to dynamically
"""
upload_path = '/'.join(
['img', instance._meta.app_label, str(now.year), str(now.month), filename]
)
return upload_path | python | def set_img_path(instance, filename):
"""
Sets upload_to dynamically
"""
upload_path = '/'.join(
['img', instance._meta.app_label, str(now.year), str(now.month), filename]
)
return upload_path | [
"def",
"set_img_path",
"(",
"instance",
",",
"filename",
")",
":",
"upload_path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'img'",
",",
"instance",
".",
"_meta",
".",
"app_label",
",",
"str",
"(",
"now",
".",
"year",
")",
",",
"str",
"(",
"now",
".",
"m... | Sets upload_to dynamically | [
"Sets",
"upload_to",
"dynamically"
] | 35fc10aef1ceedcdb4d6d866d44a22efff718812 | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/models.py#L24-L31 |
242,870 | tBaxter/tango-shared-core | build/lib/tango_shared/models.py | BaseUserContentModel.save | def save(self, *args, **kwargs):
"""
Clean text and save formatted version.
"""
self.text = clean_text(self.text)
self.text_formatted = format_text(self.text)
super(BaseUserContentModel, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
Clean text and save formatted version.
"""
self.text = clean_text(self.text)
self.text_formatted = format_text(self.text)
super(BaseUserContentModel, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"text",
"=",
"clean_text",
"(",
"self",
".",
"text",
")",
"self",
".",
"text_formatted",
"=",
"format_text",
"(",
"self",
".",
"text",
")",
"super",
"(",
... | Clean text and save formatted version. | [
"Clean",
"text",
"and",
"save",
"formatted",
"version",
"."
] | 35fc10aef1ceedcdb4d6d866d44a22efff718812 | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/models.py#L151-L157 |
242,871 | treystout/Agner | agner/queue.py | Queue.enqueue | def enqueue(self, job):
"""Enqueue a job for later processing, returns the new length of the queue
"""
if job.queue_name():
raise EnqueueError("job %s already queued!" % job.job_id)
new_len = self.redis.lpush(self.queue_name, job.serialize())
job.notify_queued(self)
return new_len | python | def enqueue(self, job):
"""Enqueue a job for later processing, returns the new length of the queue
"""
if job.queue_name():
raise EnqueueError("job %s already queued!" % job.job_id)
new_len = self.redis.lpush(self.queue_name, job.serialize())
job.notify_queued(self)
return new_len | [
"def",
"enqueue",
"(",
"self",
",",
"job",
")",
":",
"if",
"job",
".",
"queue_name",
"(",
")",
":",
"raise",
"EnqueueError",
"(",
"\"job %s already queued!\"",
"%",
"job",
".",
"job_id",
")",
"new_len",
"=",
"self",
".",
"redis",
".",
"lpush",
"(",
"se... | Enqueue a job for later processing, returns the new length of the queue | [
"Enqueue",
"a",
"job",
"for",
"later",
"processing",
"returns",
"the",
"new",
"length",
"of",
"the",
"queue"
] | db29db9ceed8732e6ffdfc4f4fc1a42bd10b8c85 | https://github.com/treystout/Agner/blob/db29db9ceed8732e6ffdfc4f4fc1a42bd10b8c85/agner/queue.py#L34-L41 |
242,872 | treystout/Agner | agner/queue.py | Queue.next_job | def next_job(self, timeout_seconds=None):
"""Retuns the next job in the queue, or None if is nothing there
"""
if timeout_seconds is not None:
timeout = timeout_seconds
else:
timeout = BLOCK_SECONDS
response = self.lua_next(keys=[self.queue_name])
if not response:
return
job = Job.from_serialized(response)
if not job:
self.log.warn("could not deserialize job from: %s", serialized_job)
return job | python | def next_job(self, timeout_seconds=None):
"""Retuns the next job in the queue, or None if is nothing there
"""
if timeout_seconds is not None:
timeout = timeout_seconds
else:
timeout = BLOCK_SECONDS
response = self.lua_next(keys=[self.queue_name])
if not response:
return
job = Job.from_serialized(response)
if not job:
self.log.warn("could not deserialize job from: %s", serialized_job)
return job | [
"def",
"next_job",
"(",
"self",
",",
"timeout_seconds",
"=",
"None",
")",
":",
"if",
"timeout_seconds",
"is",
"not",
"None",
":",
"timeout",
"=",
"timeout_seconds",
"else",
":",
"timeout",
"=",
"BLOCK_SECONDS",
"response",
"=",
"self",
".",
"lua_next",
"(",
... | Retuns the next job in the queue, or None if is nothing there | [
"Retuns",
"the",
"next",
"job",
"in",
"the",
"queue",
"or",
"None",
"if",
"is",
"nothing",
"there"
] | db29db9ceed8732e6ffdfc4f4fc1a42bd10b8c85 | https://github.com/treystout/Agner/blob/db29db9ceed8732e6ffdfc4f4fc1a42bd10b8c85/agner/queue.py#L43-L58 |
242,873 | maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | generate_headline_from_description | def generate_headline_from_description(sender, instance, *args, **kwargs):
'''
Auto generate the headline of the node from the first lines of the description.
'''
lines = instance.description.split('\n')
headline = truncatewords(lines[0], 20)
if headline[:-3] == '...':
headline = truncatechars(headline.replace(' ...', ''), 250) # Just in case the words exceed char limit.
else:
headline = truncatechars(headline, 250)
instance.headline = headline | python | def generate_headline_from_description(sender, instance, *args, **kwargs):
'''
Auto generate the headline of the node from the first lines of the description.
'''
lines = instance.description.split('\n')
headline = truncatewords(lines[0], 20)
if headline[:-3] == '...':
headline = truncatechars(headline.replace(' ...', ''), 250) # Just in case the words exceed char limit.
else:
headline = truncatechars(headline, 250)
instance.headline = headline | [
"def",
"generate_headline_from_description",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lines",
"=",
"instance",
".",
"description",
".",
"split",
"(",
"'\\n'",
")",
"headline",
"=",
"truncatewords",
"(",
"lines",
... | Auto generate the headline of the node from the first lines of the description. | [
"Auto",
"generate",
"the",
"headline",
"of",
"the",
"node",
"from",
"the",
"first",
"lines",
"of",
"the",
"description",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L22-L32 |
242,874 | maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | story_root_for_new_outline | def story_root_for_new_outline(sender, instance, created, *args, **kwargs):
'''
If a new instance of a Outline is created, also create
the root node of the story tree.
'''
if created and isinstance(instance, Outline):
streeroot = StoryElementNode.add_root(outline=instance, story_element_type='root')
streeroot.save()
instance.refresh_from_db() | python | def story_root_for_new_outline(sender, instance, created, *args, **kwargs):
'''
If a new instance of a Outline is created, also create
the root node of the story tree.
'''
if created and isinstance(instance, Outline):
streeroot = StoryElementNode.add_root(outline=instance, story_element_type='root')
streeroot.save()
instance.refresh_from_db() | [
"def",
"story_root_for_new_outline",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
"and",
"isinstance",
"(",
"instance",
",",
"Outline",
")",
":",
"streeroot",
"=",
"StoryElementNode",
... | If a new instance of a Outline is created, also create
the root node of the story tree. | [
"If",
"a",
"new",
"instance",
"of",
"a",
"Outline",
"is",
"created",
"also",
"create",
"the",
"root",
"node",
"of",
"the",
"story",
"tree",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L36-L44 |
242,875 | maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | story_node_add_arc_element_update_characters_locations | def story_node_add_arc_element_update_characters_locations(sender, instance, created, *args, **kwargs):
'''
If an arc element is added to a story element node, add any missing elements or locations.
'''
arc_node = ArcElementNode.objects.get(pk=instance.pk)
logger.debug('Scanning arc_node %s' % arc_node)
if arc_node.arc_element_type == 'root':
logger.debug("root node. skipping...")
else:
logger.debug('Checking arc node for story element relationship...')
if arc_node.story_element_node:
logger.debug('Found a story element node for arc element...')
# This change was initiated by the arc element node as opposed to the story node.
story_node = arc_node.story_element_node
if arc_node.assoc_characters.count() > 0:
logger.debug('Found %d characters to add...' % arc_node.assoc_characters.count())
for character in arc_node.assoc_characters.all():
story_node.assoc_characters.add(character)
if arc_node.assoc_locations.count() > 0:
logger.debug('Found %d locations to add...' % arc_node.assoc_locations.count())
for location in arc_node.assoc_locations.all():
story_node.assoc_locations.add(location) | python | def story_node_add_arc_element_update_characters_locations(sender, instance, created, *args, **kwargs):
'''
If an arc element is added to a story element node, add any missing elements or locations.
'''
arc_node = ArcElementNode.objects.get(pk=instance.pk)
logger.debug('Scanning arc_node %s' % arc_node)
if arc_node.arc_element_type == 'root':
logger.debug("root node. skipping...")
else:
logger.debug('Checking arc node for story element relationship...')
if arc_node.story_element_node:
logger.debug('Found a story element node for arc element...')
# This change was initiated by the arc element node as opposed to the story node.
story_node = arc_node.story_element_node
if arc_node.assoc_characters.count() > 0:
logger.debug('Found %d characters to add...' % arc_node.assoc_characters.count())
for character in arc_node.assoc_characters.all():
story_node.assoc_characters.add(character)
if arc_node.assoc_locations.count() > 0:
logger.debug('Found %d locations to add...' % arc_node.assoc_locations.count())
for location in arc_node.assoc_locations.all():
story_node.assoc_locations.add(location) | [
"def",
"story_node_add_arc_element_update_characters_locations",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"arc_node",
"=",
"ArcElementNode",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"instance",
"."... | If an arc element is added to a story element node, add any missing elements or locations. | [
"If",
"an",
"arc",
"element",
"is",
"added",
"to",
"a",
"story",
"element",
"node",
"add",
"any",
"missing",
"elements",
"or",
"locations",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L96-L117 |
242,876 | maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_arc_links_same_outline | def validate_arc_links_same_outline(sender, instance, *args, **kwargs):
'''
Evaluates attempts to link an arc to a story node from another outline.
'''
if instance.story_element_node:
if instance.story_element_node.outline != instance.parent_outline:
raise IntegrityError(_('An arc cannot be associated with an story element from another outline.')) | python | def validate_arc_links_same_outline(sender, instance, *args, **kwargs):
'''
Evaluates attempts to link an arc to a story node from another outline.
'''
if instance.story_element_node:
if instance.story_element_node.outline != instance.parent_outline:
raise IntegrityError(_('An arc cannot be associated with an story element from another outline.')) | [
"def",
"validate_arc_links_same_outline",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"story_element_node",
":",
"if",
"instance",
".",
"story_element_node",
".",
"outline",
"!=",
"instance",
".",... | Evaluates attempts to link an arc to a story node from another outline. | [
"Evaluates",
"attempts",
"to",
"link",
"an",
"arc",
"to",
"a",
"story",
"node",
"from",
"another",
"outline",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L121-L127 |
242,877 | maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_character_instance_valid_for_arc | def validate_character_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluate attempts to assign a character instance to ensure it is from same
outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
for apk in pk_set:
arc_node = ArcElementNode.objects.get(pk=apk)
if arc_node.parent_outline != instance.outline:
raise IntegrityError(_('Character Instance and Arc Element must be from same outline.'))
else:
for cpk in pk_set:
char_instance = CharacterInstance.objects.get(pk=cpk)
if char_instance.outline != instance.parent_outline:
raise IntegrityError(_('Character Instance and Arc Element must be from the same outline.')) | python | def validate_character_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluate attempts to assign a character instance to ensure it is from same
outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
for apk in pk_set:
arc_node = ArcElementNode.objects.get(pk=apk)
if arc_node.parent_outline != instance.outline:
raise IntegrityError(_('Character Instance and Arc Element must be from same outline.'))
else:
for cpk in pk_set:
char_instance = CharacterInstance.objects.get(pk=cpk)
if char_instance.outline != instance.parent_outline:
raise IntegrityError(_('Character Instance and Arc Element must be from the same outline.')) | [
"def",
"validate_character_instance_valid_for_arc",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'pre_add'",
":",
"if",
"reverse",
":",
"# Fetch arc ... | Evaluate attempts to assign a character instance to ensure it is from same
outline. | [
"Evaluate",
"attempts",
"to",
"assign",
"a",
"character",
"instance",
"to",
"ensure",
"it",
"is",
"from",
"same",
"outline",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L131-L147 |
242,878 | maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_location_instance_valid_for_arc | def validate_location_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluates attempts to add location instances to arc, ensuring they are from same outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
for apk in pk_set:
arc_node = ArcElementNode.objects.get(pk=apk)
if arc_node.parent_outline != instance.outline:
raise IntegrityError(_('Location instance must be from same outline as arc element.'))
else:
for lpk in pk_set:
loc_instance = LocationInstance.objects.get(pk=lpk)
if loc_instance.outline != instance.parent_outline:
raise IntegrityError(_('Location Instance must be from the same outline as arc element.')) | python | def validate_location_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluates attempts to add location instances to arc, ensuring they are from same outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
for apk in pk_set:
arc_node = ArcElementNode.objects.get(pk=apk)
if arc_node.parent_outline != instance.outline:
raise IntegrityError(_('Location instance must be from same outline as arc element.'))
else:
for lpk in pk_set:
loc_instance = LocationInstance.objects.get(pk=lpk)
if loc_instance.outline != instance.parent_outline:
raise IntegrityError(_('Location Instance must be from the same outline as arc element.')) | [
"def",
"validate_location_instance_valid_for_arc",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'pre_add'",
":",
"if",
"reverse",
":",
"# Fetch arc d... | Evaluates attempts to add location instances to arc, ensuring they are from same outline. | [
"Evaluates",
"attempts",
"to",
"add",
"location",
"instances",
"to",
"arc",
"ensuring",
"they",
"are",
"from",
"same",
"outline",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L151-L166 |
242,879 | maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_character_for_story_element | def validate_character_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that character is from the same outline as the story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.objects.get(pk=spk)
if instance.outline != story_node.outline:
raise IntegrityError(_('Character Instance must be from the same outline as story node.'))
else:
for cpk in pk_set:
char_instance = CharacterInstance.objects.get(pk=cpk)
if char_instance.outline != instance.outline:
raise IntegrityError(_('Character Instance must be from the same outline as story node.')) | python | def validate_character_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that character is from the same outline as the story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.objects.get(pk=spk)
if instance.outline != story_node.outline:
raise IntegrityError(_('Character Instance must be from the same outline as story node.'))
else:
for cpk in pk_set:
char_instance = CharacterInstance.objects.get(pk=cpk)
if char_instance.outline != instance.outline:
raise IntegrityError(_('Character Instance must be from the same outline as story node.')) | [
"def",
"validate_character_for_story_element",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'pre_add'",
":",
"if",
"reverse",
":",
"for",
"spk",
... | Validates that character is from the same outline as the story node. | [
"Validates",
"that",
"character",
"is",
"from",
"the",
"same",
"outline",
"as",
"the",
"story",
"node",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L170-L184 |
242,880 | maceoutliner/django-fiction-outlines | fiction_outlines/receivers.py | validate_location_for_story_element | def validate_location_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that location is from same outline as story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.objects.get(pk=spk)
if instance.outline != story_node.outline:
raise IntegrityError(_('Location must be from same outline as story node.'))
else:
for lpk in pk_set:
loc_instance = LocationInstance.objects.get(pk=lpk)
if instance.outline != loc_instance.outline:
raise IntegrityError(_('Location must be from the same outline as story node.')) | python | def validate_location_for_story_element(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Validates that location is from same outline as story node.
'''
if action == 'pre_add':
if reverse:
for spk in pk_set:
story_node = StoryElementNode.objects.get(pk=spk)
if instance.outline != story_node.outline:
raise IntegrityError(_('Location must be from same outline as story node.'))
else:
for lpk in pk_set:
loc_instance = LocationInstance.objects.get(pk=lpk)
if instance.outline != loc_instance.outline:
raise IntegrityError(_('Location must be from the same outline as story node.')) | [
"def",
"validate_location_for_story_element",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"reverse",
",",
"pk_set",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"==",
"'pre_add'",
":",
"if",
"reverse",
":",
"for",
"spk",
"... | Validates that location is from same outline as story node. | [
"Validates",
"that",
"location",
"is",
"from",
"same",
"outline",
"as",
"story",
"node",
"."
] | 6c58e356af3fbe7b23557643ba27e46eaef9d4e3 | https://github.com/maceoutliner/django-fiction-outlines/blob/6c58e356af3fbe7b23557643ba27e46eaef9d4e3/fiction_outlines/receivers.py#L188-L202 |
242,881 | rsalmaso/django-fluo | fluo/views/base.py | View.options | def options(self, request, *args, **kwargs):
"""
Handles responding to requests for the OPTIONS HTTP verb
"""
response = HttpResponse()
response['Allow'] = ', '.join(self.allowed_methods)
response['Content-Length'] = 0
return response | python | def options(self, request, *args, **kwargs):
"""
Handles responding to requests for the OPTIONS HTTP verb
"""
response = HttpResponse()
response['Allow'] = ', '.join(self.allowed_methods)
response['Content-Length'] = 0
return response | [
"def",
"options",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"HttpResponse",
"(",
")",
"response",
"[",
"'Allow'",
"]",
"=",
"', '",
".",
"join",
"(",
"self",
".",
"allowed_methods",
")",
"respo... | Handles responding to requests for the OPTIONS HTTP verb | [
"Handles",
"responding",
"to",
"requests",
"for",
"the",
"OPTIONS",
"HTTP",
"verb"
] | 1321c1e7d6a912108f79be02a9e7f2108c57f89f | https://github.com/rsalmaso/django-fluo/blob/1321c1e7d6a912108f79be02a9e7f2108c57f89f/fluo/views/base.py#L75-L82 |
242,882 | DasIch/argvard | argvard/utils.py | is_python2_identifier | def is_python2_identifier(possible_identifier):
"""
Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 2.
"""
match = _python2_identifier_re.match(possible_identifier)
return bool(match) and not iskeyword(possible_identifier) | python | def is_python2_identifier(possible_identifier):
"""
Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 2.
"""
match = _python2_identifier_re.match(possible_identifier)
return bool(match) and not iskeyword(possible_identifier) | [
"def",
"is_python2_identifier",
"(",
"possible_identifier",
")",
":",
"match",
"=",
"_python2_identifier_re",
".",
"match",
"(",
"possible_identifier",
")",
"return",
"bool",
"(",
"match",
")",
"and",
"not",
"iskeyword",
"(",
"possible_identifier",
")"
] | Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 2. | [
"Returns",
"True",
"if",
"the",
"given",
"possible_identifier",
"can",
"be",
"used",
"as",
"an",
"identifier",
"in",
"Python",
"2",
"."
] | 2603e323a995e0915ce41fcf49e2a82519556195 | https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/utils.py#L43-L49 |
242,883 | DasIch/argvard | argvard/utils.py | is_python3_identifier | def is_python3_identifier(possible_identifier):
"""
Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 3.
"""
possible_identifier = unicodedata.normalize('NFKC', possible_identifier)
return (
bool(possible_identifier) and
_is_in_id_start(possible_identifier[0]) and
all(map(_is_in_id_continue, possible_identifier[1:]))
) and not iskeyword(possible_identifier) | python | def is_python3_identifier(possible_identifier):
"""
Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 3.
"""
possible_identifier = unicodedata.normalize('NFKC', possible_identifier)
return (
bool(possible_identifier) and
_is_in_id_start(possible_identifier[0]) and
all(map(_is_in_id_continue, possible_identifier[1:]))
) and not iskeyword(possible_identifier) | [
"def",
"is_python3_identifier",
"(",
"possible_identifier",
")",
":",
"possible_identifier",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKC'",
",",
"possible_identifier",
")",
"return",
"(",
"bool",
"(",
"possible_identifier",
")",
"and",
"_is_in_id_start",
"(",
... | Returns `True` if the given `possible_identifier` can be used as an
identifier in Python 3. | [
"Returns",
"True",
"if",
"the",
"given",
"possible_identifier",
"can",
"be",
"used",
"as",
"an",
"identifier",
"in",
"Python",
"3",
"."
] | 2603e323a995e0915ce41fcf49e2a82519556195 | https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/utils.py#L52-L62 |
242,884 | DasIch/argvard | argvard/utils.py | unique | def unique(iterable):
"""
Returns an iterator that yields the first occurence of a hashable item in
`iterable`.
"""
seen = set()
for obj in iterable:
if obj not in seen:
yield obj
seen.add(obj) | python | def unique(iterable):
"""
Returns an iterator that yields the first occurence of a hashable item in
`iterable`.
"""
seen = set()
for obj in iterable:
if obj not in seen:
yield obj
seen.add(obj) | [
"def",
"unique",
"(",
"iterable",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"obj",
"in",
"iterable",
":",
"if",
"obj",
"not",
"in",
"seen",
":",
"yield",
"obj",
"seen",
".",
"add",
"(",
"obj",
")"
] | Returns an iterator that yields the first occurence of a hashable item in
`iterable`. | [
"Returns",
"an",
"iterator",
"that",
"yields",
"the",
"first",
"occurence",
"of",
"a",
"hashable",
"item",
"in",
"iterable",
"."
] | 2603e323a995e0915ce41fcf49e2a82519556195 | https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/utils.py#L87-L96 |
242,885 | krinj/k-util | k_util/region.py | Region.contains | def contains(self, x, y) -> bool:
"""" Checks if the given x, y position is within the area of this region. """
if x < self._left or x > self._right or y < self._top or y > self._bottom:
return False
return True | python | def contains(self, x, y) -> bool:
"""" Checks if the given x, y position is within the area of this region. """
if x < self._left or x > self._right or y < self._top or y > self._bottom:
return False
return True | [
"def",
"contains",
"(",
"self",
",",
"x",
",",
"y",
")",
"->",
"bool",
":",
"if",
"x",
"<",
"self",
".",
"_left",
"or",
"x",
">",
"self",
".",
"_right",
"or",
"y",
"<",
"self",
".",
"_top",
"or",
"y",
">",
"self",
".",
"_bottom",
":",
"return... | Checks if the given x, y position is within the area of this region. | [
"Checks",
"if",
"the",
"given",
"x",
"y",
"position",
"is",
"within",
"the",
"area",
"of",
"this",
"region",
"."
] | b118826b1d6f49ca4e1ca7327d5b171db332ac23 | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L72-L76 |
242,886 | krinj/k-util | k_util/region.py | Region.is_in_bounds | def is_in_bounds(self, width, height) -> bool:
""" Check if this entire region is contained within the bounds of a given stage size."""
if self._top < 0 \
or self._bottom > height \
or self._left < 0 \
or self._right > width:
return False
return True | python | def is_in_bounds(self, width, height) -> bool:
""" Check if this entire region is contained within the bounds of a given stage size."""
if self._top < 0 \
or self._bottom > height \
or self._left < 0 \
or self._right > width:
return False
return True | [
"def",
"is_in_bounds",
"(",
"self",
",",
"width",
",",
"height",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_top",
"<",
"0",
"or",
"self",
".",
"_bottom",
">",
"height",
"or",
"self",
".",
"_left",
"<",
"0",
"or",
"self",
".",
"_right",
">",
"wi... | Check if this entire region is contained within the bounds of a given stage size. | [
"Check",
"if",
"this",
"entire",
"region",
"is",
"contained",
"within",
"the",
"bounds",
"of",
"a",
"given",
"stage",
"size",
"."
] | b118826b1d6f49ca4e1ca7327d5b171db332ac23 | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L78-L85 |
242,887 | krinj/k-util | k_util/region.py | Region.canvas_resize | def canvas_resize(self, scale):
""" Resize this region against the entire axis space. """
self._top *= scale
self._bottom *= scale
self._left *= scale
self._right *= scale
self._calibrate_to_rect() | python | def canvas_resize(self, scale):
""" Resize this region against the entire axis space. """
self._top *= scale
self._bottom *= scale
self._left *= scale
self._right *= scale
self._calibrate_to_rect() | [
"def",
"canvas_resize",
"(",
"self",
",",
"scale",
")",
":",
"self",
".",
"_top",
"*=",
"scale",
"self",
".",
"_bottom",
"*=",
"scale",
"self",
".",
"_left",
"*=",
"scale",
"self",
".",
"_right",
"*=",
"scale",
"self",
".",
"_calibrate_to_rect",
"(",
"... | Resize this region against the entire axis space. | [
"Resize",
"this",
"region",
"against",
"the",
"entire",
"axis",
"space",
"."
] | b118826b1d6f49ca4e1ca7327d5b171db332ac23 | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L97-L103 |
242,888 | krinj/k-util | k_util/region.py | Region.distance | def distance(r1: 'Region', r2: 'Region'):
""" Calculate distance between the x and y of the two regions."""
return math.sqrt((r2.x - r1.x) ** 2 + (r2.y - r1.y) ** 2) | python | def distance(r1: 'Region', r2: 'Region'):
""" Calculate distance between the x and y of the two regions."""
return math.sqrt((r2.x - r1.x) ** 2 + (r2.y - r1.y) ** 2) | [
"def",
"distance",
"(",
"r1",
":",
"'Region'",
",",
"r2",
":",
"'Region'",
")",
":",
"return",
"math",
".",
"sqrt",
"(",
"(",
"r2",
".",
"x",
"-",
"r1",
".",
"x",
")",
"**",
"2",
"+",
"(",
"r2",
".",
"y",
"-",
"r1",
".",
"y",
")",
"**",
"... | Calculate distance between the x and y of the two regions. | [
"Calculate",
"distance",
"between",
"the",
"x",
"and",
"y",
"of",
"the",
"two",
"regions",
"."
] | b118826b1d6f49ca4e1ca7327d5b171db332ac23 | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L240-L242 |
242,889 | krinj/k-util | k_util/region.py | Region.fast_distance | def fast_distance(r1: 'Region', r2: 'Region'):
""" A quicker way of calculating approximate distance. Lower accuracy but faster results."""
return abs(r1.x - r2.x) + abs(r1.y - r2.y) | python | def fast_distance(r1: 'Region', r2: 'Region'):
""" A quicker way of calculating approximate distance. Lower accuracy but faster results."""
return abs(r1.x - r2.x) + abs(r1.y - r2.y) | [
"def",
"fast_distance",
"(",
"r1",
":",
"'Region'",
",",
"r2",
":",
"'Region'",
")",
":",
"return",
"abs",
"(",
"r1",
".",
"x",
"-",
"r2",
".",
"x",
")",
"+",
"abs",
"(",
"r1",
".",
"y",
"-",
"r2",
".",
"y",
")"
] | A quicker way of calculating approximate distance. Lower accuracy but faster results. | [
"A",
"quicker",
"way",
"of",
"calculating",
"approximate",
"distance",
".",
"Lower",
"accuracy",
"but",
"faster",
"results",
"."
] | b118826b1d6f49ca4e1ca7327d5b171db332ac23 | https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L245-L247 |
242,890 | hobson/pug-invest | pug/invest/util.py | rms | def rms(x):
""""Root Mean Square"
Arguments:
x (seq of float): A sequence of numerical values
Returns:
The square root of the average of the squares of the values
math.sqrt(sum(x_i**2 for x_i in x) / len(x))
or
return (np.array(x) ** 2).mean() ** 0.5
>>> rms([0, 2, 4, 4])
3.0
"""
try:
return (np.array(x) ** 2).mean() ** 0.5
except:
x = np.array(dropna(x))
invN = 1.0 / len(x)
return (sum(invN * (x_i ** 2) for x_i in x)) ** .5 | python | def rms(x):
""""Root Mean Square"
Arguments:
x (seq of float): A sequence of numerical values
Returns:
The square root of the average of the squares of the values
math.sqrt(sum(x_i**2 for x_i in x) / len(x))
or
return (np.array(x) ** 2).mean() ** 0.5
>>> rms([0, 2, 4, 4])
3.0
"""
try:
return (np.array(x) ** 2).mean() ** 0.5
except:
x = np.array(dropna(x))
invN = 1.0 / len(x)
return (sum(invN * (x_i ** 2) for x_i in x)) ** .5 | [
"def",
"rms",
"(",
"x",
")",
":",
"try",
":",
"return",
"(",
"np",
".",
"array",
"(",
"x",
")",
"**",
"2",
")",
".",
"mean",
"(",
")",
"**",
"0.5",
"except",
":",
"x",
"=",
"np",
".",
"array",
"(",
"dropna",
"(",
"x",
")",
")",
"invN",
"=... | Root Mean Square"
Arguments:
x (seq of float): A sequence of numerical values
Returns:
The square root of the average of the squares of the values
math.sqrt(sum(x_i**2 for x_i in x) / len(x))
or
return (np.array(x) ** 2).mean() ** 0.5
>>> rms([0, 2, 4, 4])
3.0 | [
"Root",
"Mean",
"Square"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L34-L57 |
242,891 | hobson/pug-invest | pug/invest/util.py | rmse | def rmse(target, prediction, relative=False, percent=False):
"""Root Mean Square Error
This seems like a simple formula that you'd never need to create a function for.
But my mistakes on coding challenges have convinced me that I do need it,
as a reminder of important tweaks, if nothing else.
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1])
3.0
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1], relative=True) # doctest: +ELLIPSIS
1.2247...
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1], percent=True) # doctest: +ELLIPSIS
122.47...
"""
relative = relative or percent
prediction = pd.np.array(prediction)
target = np.array(target)
err = prediction - target
if relative:
denom = target
# Avoid ZeroDivisionError: divide by prediction rather than target where target==0
denom[denom == 0] = prediction[denom == 0]
# If the prediction and target are both 0, then the error is 0 and should be included in the RMSE
# Otherwise, the np.isinf() below would remove all these zero-error predictions from the array.
denom[(denom == 0) & (target == 0)] = 1
err = (err / denom)
err = err[(~ np.isnan(err)) & (~ np.isinf(err))]
return 100 * rms(err) if percent else rms(err) | python | def rmse(target, prediction, relative=False, percent=False):
"""Root Mean Square Error
This seems like a simple formula that you'd never need to create a function for.
But my mistakes on coding challenges have convinced me that I do need it,
as a reminder of important tweaks, if nothing else.
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1])
3.0
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1], relative=True) # doctest: +ELLIPSIS
1.2247...
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1], percent=True) # doctest: +ELLIPSIS
122.47...
"""
relative = relative or percent
prediction = pd.np.array(prediction)
target = np.array(target)
err = prediction - target
if relative:
denom = target
# Avoid ZeroDivisionError: divide by prediction rather than target where target==0
denom[denom == 0] = prediction[denom == 0]
# If the prediction and target are both 0, then the error is 0 and should be included in the RMSE
# Otherwise, the np.isinf() below would remove all these zero-error predictions from the array.
denom[(denom == 0) & (target == 0)] = 1
err = (err / denom)
err = err[(~ np.isnan(err)) & (~ np.isinf(err))]
return 100 * rms(err) if percent else rms(err) | [
"def",
"rmse",
"(",
"target",
",",
"prediction",
",",
"relative",
"=",
"False",
",",
"percent",
"=",
"False",
")",
":",
"relative",
"=",
"relative",
"or",
"percent",
"prediction",
"=",
"pd",
".",
"np",
".",
"array",
"(",
"prediction",
")",
"target",
"=... | Root Mean Square Error
This seems like a simple formula that you'd never need to create a function for.
But my mistakes on coding challenges have convinced me that I do need it,
as a reminder of important tweaks, if nothing else.
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1])
3.0
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1], relative=True) # doctest: +ELLIPSIS
1.2247...
>>> rmse([0, 1, 4, 3], [2, 1, 0, -1], percent=True) # doctest: +ELLIPSIS
122.47... | [
"Root",
"Mean",
"Square",
"Error"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L60-L87 |
242,892 | hobson/pug-invest | pug/invest/util.py | pandas_mesh | def pandas_mesh(df):
"""Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame
Arguments:
df (DataFrame): Must have 3 or 4 columns of numerical data
Returns:
OrderedDict: column labels from the data frame are the keys, values are 2-D matrices
All matrices have shape NxM, where N = len(set(df.iloc[:,0])) and M = len(set(df.iloc[:,1]))
>>> pandas_mesh(pd.DataFrame(np.arange(18).reshape(3,6),
... columns=list('ABCDEF'))).values() # doctest: +NORMALIZE_WHITESPACE
[array([[ 0, 6, 12],
[ 0, 6, 12],
[ 0, 6, 12]]),
array([[ 1, 1, 1],
[ 7, 7, 7],
[13, 13, 13]]),
array([[ 2., nan, nan],
[ nan, 8., nan],
[ nan, nan, 14.]]),
array([[ 3., nan, nan],
[ nan, 9., nan],
[ nan, nan, 15.]]),
array([[ 4., nan, nan],
[ nan, 10., nan],
[ nan, nan, 16.]]),
array([[ 5., nan, nan],
[ nan, 11., nan],
[ nan, nan, 17.]])]
"""
xyz = [df[c].values for c in df.columns]
index = pd.MultiIndex.from_tuples(zip(xyz[0], xyz[1]), names=['x', 'y'])
# print(index)
series = [pd.Series(values, index=index) for values in xyz[2:]]
# print(series)
X, Y = np.meshgrid(sorted(list(set(xyz[0]))), sorted(list(set(xyz[1]))))
N, M = X.shape
Zs = []
# print(Zs)
for k, s in enumerate(series):
Z = np.empty(X.shape)
Z[:] = np.nan
for i, j in itertools.product(range(N), range(M)):
Z[i, j] = s.get((X[i, j], Y[i, j]), np.NAN)
Zs += [Z]
return OrderedDict((df.columns[i], m) for i, m in enumerate([X, Y] + Zs)) | python | def pandas_mesh(df):
"""Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame
Arguments:
df (DataFrame): Must have 3 or 4 columns of numerical data
Returns:
OrderedDict: column labels from the data frame are the keys, values are 2-D matrices
All matrices have shape NxM, where N = len(set(df.iloc[:,0])) and M = len(set(df.iloc[:,1]))
>>> pandas_mesh(pd.DataFrame(np.arange(18).reshape(3,6),
... columns=list('ABCDEF'))).values() # doctest: +NORMALIZE_WHITESPACE
[array([[ 0, 6, 12],
[ 0, 6, 12],
[ 0, 6, 12]]),
array([[ 1, 1, 1],
[ 7, 7, 7],
[13, 13, 13]]),
array([[ 2., nan, nan],
[ nan, 8., nan],
[ nan, nan, 14.]]),
array([[ 3., nan, nan],
[ nan, 9., nan],
[ nan, nan, 15.]]),
array([[ 4., nan, nan],
[ nan, 10., nan],
[ nan, nan, 16.]]),
array([[ 5., nan, nan],
[ nan, 11., nan],
[ nan, nan, 17.]])]
"""
xyz = [df[c].values for c in df.columns]
index = pd.MultiIndex.from_tuples(zip(xyz[0], xyz[1]), names=['x', 'y'])
# print(index)
series = [pd.Series(values, index=index) for values in xyz[2:]]
# print(series)
X, Y = np.meshgrid(sorted(list(set(xyz[0]))), sorted(list(set(xyz[1]))))
N, M = X.shape
Zs = []
# print(Zs)
for k, s in enumerate(series):
Z = np.empty(X.shape)
Z[:] = np.nan
for i, j in itertools.product(range(N), range(M)):
Z[i, j] = s.get((X[i, j], Y[i, j]), np.NAN)
Zs += [Z]
return OrderedDict((df.columns[i], m) for i, m in enumerate([X, Y] + Zs)) | [
"def",
"pandas_mesh",
"(",
"df",
")",
":",
"xyz",
"=",
"[",
"df",
"[",
"c",
"]",
".",
"values",
"for",
"c",
"in",
"df",
".",
"columns",
"]",
"index",
"=",
"pd",
".",
"MultiIndex",
".",
"from_tuples",
"(",
"zip",
"(",
"xyz",
"[",
"0",
"]",
",",
... | Create numpy 2-D "meshgrid" from 3+ columns in a Pandas DataFrame
Arguments:
df (DataFrame): Must have 3 or 4 columns of numerical data
Returns:
OrderedDict: column labels from the data frame are the keys, values are 2-D matrices
All matrices have shape NxM, where N = len(set(df.iloc[:,0])) and M = len(set(df.iloc[:,1]))
>>> pandas_mesh(pd.DataFrame(np.arange(18).reshape(3,6),
... columns=list('ABCDEF'))).values() # doctest: +NORMALIZE_WHITESPACE
[array([[ 0, 6, 12],
[ 0, 6, 12],
[ 0, 6, 12]]),
array([[ 1, 1, 1],
[ 7, 7, 7],
[13, 13, 13]]),
array([[ 2., nan, nan],
[ nan, 8., nan],
[ nan, nan, 14.]]),
array([[ 3., nan, nan],
[ nan, 9., nan],
[ nan, nan, 15.]]),
array([[ 4., nan, nan],
[ nan, 10., nan],
[ nan, nan, 16.]]),
array([[ 5., nan, nan],
[ nan, 11., nan],
[ nan, nan, 17.]])] | [
"Create",
"numpy",
"2",
"-",
"D",
"meshgrid",
"from",
"3",
"+",
"columns",
"in",
"a",
"Pandas",
"DataFrame"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L246-L292 |
242,893 | hobson/pug-invest | pug/invest/util.py | get_integrator | def get_integrator(integrator):
"""Return the scipy.integrator indicated by an index, name, or integrator_function
>> get_integrator(0)
"""
integrator_types = set(['trapz', 'cumtrapz', 'simps', 'romb'])
integrator_funcs = [integrate.trapz, integrate.cumtrapz, integrate.simps, integrate.romb]
if isinstance(integrator, int) and 0 <= integrator < len(integrator_types):
integrator = integrator_types[integrator]
if isinstance(integrator, basestring) and integrator in integrator_types:
return getattr(integrate, integrator)
elif integrator in integrator_funcs:
return integrator
else:
print('Unsupported integration rule: {0}'.format(integrator))
print('Expecting one of these sample-based integration rules: %s' % (str(list(integrator_types))))
raise AttributeError
return integrator | python | def get_integrator(integrator):
"""Return the scipy.integrator indicated by an index, name, or integrator_function
>> get_integrator(0)
"""
integrator_types = set(['trapz', 'cumtrapz', 'simps', 'romb'])
integrator_funcs = [integrate.trapz, integrate.cumtrapz, integrate.simps, integrate.romb]
if isinstance(integrator, int) and 0 <= integrator < len(integrator_types):
integrator = integrator_types[integrator]
if isinstance(integrator, basestring) and integrator in integrator_types:
return getattr(integrate, integrator)
elif integrator in integrator_funcs:
return integrator
else:
print('Unsupported integration rule: {0}'.format(integrator))
print('Expecting one of these sample-based integration rules: %s' % (str(list(integrator_types))))
raise AttributeError
return integrator | [
"def",
"get_integrator",
"(",
"integrator",
")",
":",
"integrator_types",
"=",
"set",
"(",
"[",
"'trapz'",
",",
"'cumtrapz'",
",",
"'simps'",
",",
"'romb'",
"]",
")",
"integrator_funcs",
"=",
"[",
"integrate",
".",
"trapz",
",",
"integrate",
".",
"cumtrapz",... | Return the scipy.integrator indicated by an index, name, or integrator_function
>> get_integrator(0) | [
"Return",
"the",
"scipy",
".",
"integrator",
"indicated",
"by",
"an",
"index",
"name",
"or",
"integrator_function"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L400-L418 |
242,894 | hobson/pug-invest | pug/invest/util.py | square_off | def square_off(series, time_delta=None, transition_seconds=1):
"""Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.
New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting
>>> square_off(pd.Series(range(3), index=pd.date_range('2014-01-01', periods=3, freq='15m')),
... time_delta=5.5) # doctest: +NORMALIZE_WHITESPACE
2014-01-31 00:00:00 0
2014-01-31 00:00:05.500000 0
2015-04-30 00:00:00 1
2015-04-30 00:00:05.500000 1
2016-07-31 00:00:00 2
2016-07-31 00:00:05.500000 2
dtype: int64
>>> square_off(pd.Series(range(2), index=pd.date_range('2014-01-01', periods=2, freq='15min')),
... transition_seconds=2.5) # doctest: +NORMALIZE_WHITESPACE
2014-01-01 00:00:00 0
2014-01-01 00:14:57.500000 0
2014-01-01 00:15:00 1
2014-01-01 00:29:57.500000 1
dtype: int64
"""
if time_delta:
# int, float means delta is in seconds (not years!)
if isinstance(time_delta, (int, float)):
time_delta = datetime.timedelta(0, time_delta)
new_times = series.index + time_delta
else:
diff = np.diff(series.index)
time_delta = np.append(diff, [diff[-1]])
new_times = series.index + time_delta
new_times = pd.DatetimeIndex(new_times) - datetime.timedelta(0, transition_seconds)
return pd.concat([series, pd.Series(series.values, index=new_times)]).sort_index() | python | def square_off(series, time_delta=None, transition_seconds=1):
"""Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.
New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting
>>> square_off(pd.Series(range(3), index=pd.date_range('2014-01-01', periods=3, freq='15m')),
... time_delta=5.5) # doctest: +NORMALIZE_WHITESPACE
2014-01-31 00:00:00 0
2014-01-31 00:00:05.500000 0
2015-04-30 00:00:00 1
2015-04-30 00:00:05.500000 1
2016-07-31 00:00:00 2
2016-07-31 00:00:05.500000 2
dtype: int64
>>> square_off(pd.Series(range(2), index=pd.date_range('2014-01-01', periods=2, freq='15min')),
... transition_seconds=2.5) # doctest: +NORMALIZE_WHITESPACE
2014-01-01 00:00:00 0
2014-01-01 00:14:57.500000 0
2014-01-01 00:15:00 1
2014-01-01 00:29:57.500000 1
dtype: int64
"""
if time_delta:
# int, float means delta is in seconds (not years!)
if isinstance(time_delta, (int, float)):
time_delta = datetime.timedelta(0, time_delta)
new_times = series.index + time_delta
else:
diff = np.diff(series.index)
time_delta = np.append(diff, [diff[-1]])
new_times = series.index + time_delta
new_times = pd.DatetimeIndex(new_times) - datetime.timedelta(0, transition_seconds)
return pd.concat([series, pd.Series(series.values, index=new_times)]).sort_index() | [
"def",
"square_off",
"(",
"series",
",",
"time_delta",
"=",
"None",
",",
"transition_seconds",
"=",
"1",
")",
":",
"if",
"time_delta",
":",
"# int, float means delta is in seconds (not years!)",
"if",
"isinstance",
"(",
"time_delta",
",",
"(",
"int",
",",
"float",... | Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.
New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting
>>> square_off(pd.Series(range(3), index=pd.date_range('2014-01-01', periods=3, freq='15m')),
... time_delta=5.5) # doctest: +NORMALIZE_WHITESPACE
2014-01-31 00:00:00 0
2014-01-31 00:00:05.500000 0
2015-04-30 00:00:00 1
2015-04-30 00:00:05.500000 1
2016-07-31 00:00:00 2
2016-07-31 00:00:05.500000 2
dtype: int64
>>> square_off(pd.Series(range(2), index=pd.date_range('2014-01-01', periods=2, freq='15min')),
... transition_seconds=2.5) # doctest: +NORMALIZE_WHITESPACE
2014-01-01 00:00:00 0
2014-01-01 00:14:57.500000 0
2014-01-01 00:15:00 1
2014-01-01 00:29:57.500000 1
dtype: int64 | [
"Insert",
"samples",
"in",
"regularly",
"sampled",
"data",
"to",
"produce",
"stairsteps",
"from",
"ramps",
"when",
"plotted",
"."
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L572-L604 |
242,895 | hobson/pug-invest | pug/invest/util.py | join_time_series | def join_time_series(serieses, ignore_year=False, T_s=None, aggregator='mean'):
"""Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling
FIXME:
For ignore_year and multi-year data, the index (in seconds) is computed assuming
366 days per year (leap year). So 3 out of 4 years will have a 1-day (86400 s) gap
Arguments:
series (dict of Series): dictionary of named timestamp-indexed Series objects
ignore_year (bool): ignore the calendar year, but not the season (day of year)
If True, the DataFrame index will be seconds since the beginning of the
year in each Series index, i.e. midnight Jan 1, 2014 will have index=0
as will Jan 1, 2010 if two Series start on those two dates.
T_s (float): sample period in seconds (for downsampling)
aggregator (str or func): e.g. 'mean', 'sum', np.std
"""
if ignore_year:
df = pd.DataFrame()
for name, ts in serieses.iteritems():
# FIXME: deal with leap years
sod = np.array(map(lambda x: (x.hour * 3600 + x.minute * 60 + x.second),
ts.index.time))
# Coerce soy to an integer so that merge/join operations identify same values
# (floats don't equal!?)
soy = (ts.index.dayofyear + 366 * (ts.index.year - ts.index.year[0])) * 3600 * 24 + sod
ts2 = pd.Series(ts.values, index=soy)
ts2 = ts2.dropna()
ts2 = ts2.sort_index()
df2 = pd.DataFrame({name: ts2.values}, index=soy)
df = df.join(df2, how='outer')
if T_s and aggregator:
df = df.groupby(lambda x: int(x /
float(T_s))).aggregate(dict((name, aggregator) for name in df.columns))
else:
df = pd.DataFrame(serieses)
if T_s and aggregator:
x0 = df.index[0]
df = df.groupby(lambda x: int((x - x0).total_seconds() /
float(T_s))).aggregate(dict((name, aggregator) for name in df.columns))
# FIXME: convert seconds since begninning of first year back into Timestamp instances
return df | python | def join_time_series(serieses, ignore_year=False, T_s=None, aggregator='mean'):
"""Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling
FIXME:
For ignore_year and multi-year data, the index (in seconds) is computed assuming
366 days per year (leap year). So 3 out of 4 years will have a 1-day (86400 s) gap
Arguments:
series (dict of Series): dictionary of named timestamp-indexed Series objects
ignore_year (bool): ignore the calendar year, but not the season (day of year)
If True, the DataFrame index will be seconds since the beginning of the
year in each Series index, i.e. midnight Jan 1, 2014 will have index=0
as will Jan 1, 2010 if two Series start on those two dates.
T_s (float): sample period in seconds (for downsampling)
aggregator (str or func): e.g. 'mean', 'sum', np.std
"""
if ignore_year:
df = pd.DataFrame()
for name, ts in serieses.iteritems():
# FIXME: deal with leap years
sod = np.array(map(lambda x: (x.hour * 3600 + x.minute * 60 + x.second),
ts.index.time))
# Coerce soy to an integer so that merge/join operations identify same values
# (floats don't equal!?)
soy = (ts.index.dayofyear + 366 * (ts.index.year - ts.index.year[0])) * 3600 * 24 + sod
ts2 = pd.Series(ts.values, index=soy)
ts2 = ts2.dropna()
ts2 = ts2.sort_index()
df2 = pd.DataFrame({name: ts2.values}, index=soy)
df = df.join(df2, how='outer')
if T_s and aggregator:
df = df.groupby(lambda x: int(x /
float(T_s))).aggregate(dict((name, aggregator) for name in df.columns))
else:
df = pd.DataFrame(serieses)
if T_s and aggregator:
x0 = df.index[0]
df = df.groupby(lambda x: int((x - x0).total_seconds() /
float(T_s))).aggregate(dict((name, aggregator) for name in df.columns))
# FIXME: convert seconds since begninning of first year back into Timestamp instances
return df | [
"def",
"join_time_series",
"(",
"serieses",
",",
"ignore_year",
"=",
"False",
",",
"T_s",
"=",
"None",
",",
"aggregator",
"=",
"'mean'",
")",
":",
"if",
"ignore_year",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"for",
"name",
",",
"ts",
"in",
... | Combine a dict of pd.Series objects into a single pd.DataFrame with optional downsampling
FIXME:
For ignore_year and multi-year data, the index (in seconds) is computed assuming
366 days per year (leap year). So 3 out of 4 years will have a 1-day (86400 s) gap
Arguments:
series (dict of Series): dictionary of named timestamp-indexed Series objects
ignore_year (bool): ignore the calendar year, but not the season (day of year)
If True, the DataFrame index will be seconds since the beginning of the
year in each Series index, i.e. midnight Jan 1, 2014 will have index=0
as will Jan 1, 2010 if two Series start on those two dates.
T_s (float): sample period in seconds (for downsampling)
aggregator (str or func): e.g. 'mean', 'sum', np.std | [
"Combine",
"a",
"dict",
"of",
"pd",
".",
"Series",
"objects",
"into",
"a",
"single",
"pd",
".",
"DataFrame",
"with",
"optional",
"downsampling"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L637-L677 |
242,896 | hobson/pug-invest | pug/invest/util.py | smooth | def smooth(x, window_len=11, window='hanning', fill='reflect'):
"""smooth the data using a window with requested size.
Convolve a normalized window with the signal.
input:
x: signal to be smoothed
window_len: the width of the smoothing window
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
fill: 'reflect' means that the signal is reflected onto both ends before filtering
output:
the smoothed signal
example:
t = linspace(-2, 2, 0.1)
x = sin(t) + 0.1 * randn(len(t))
y = smooth(x)
import seaborn
pd.DataFrame({'x': x, 'y': y}, index=t).plot()
SEE ALSO:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman
numpy.convolve
scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
NOTE: length(output) != length(input), to correct this: instead of just y.
References:
http://wiki.scipy.org/Cookbook/SignalSmooth
"""
# force window_len to be an odd integer so it can be symmetrically applied
window_len = int(window_len)
window_len += int(not (window_len % 2))
half_len = (window_len - 1) / 2
if x.ndim != 1:
raise ValueError("smooth only accepts 1 dimension arrays.")
if x.size < window_len:
raise ValueError("Input vector needs to be bigger than window size.")
if window_len < 3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise ValueError("The window arg ({}) should be 'flat', 'hanning', 'hamming', 'bartlett', or 'blackman'"
.format(window))
s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
window = window.strip().lower()
if window is None or window == 'flat':
w = np.ones(window_len, 'd')
else:
w = getattr(np, window)(window_len)
y = np.convolve(w / w.sum(), s, mode='valid')
return y[half_len + 1:-half_len] | python | def smooth(x, window_len=11, window='hanning', fill='reflect'):
"""smooth the data using a window with requested size.
Convolve a normalized window with the signal.
input:
x: signal to be smoothed
window_len: the width of the smoothing window
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
fill: 'reflect' means that the signal is reflected onto both ends before filtering
output:
the smoothed signal
example:
t = linspace(-2, 2, 0.1)
x = sin(t) + 0.1 * randn(len(t))
y = smooth(x)
import seaborn
pd.DataFrame({'x': x, 'y': y}, index=t).plot()
SEE ALSO:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman
numpy.convolve
scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
NOTE: length(output) != length(input), to correct this: instead of just y.
References:
http://wiki.scipy.org/Cookbook/SignalSmooth
"""
# force window_len to be an odd integer so it can be symmetrically applied
window_len = int(window_len)
window_len += int(not (window_len % 2))
half_len = (window_len - 1) / 2
if x.ndim != 1:
raise ValueError("smooth only accepts 1 dimension arrays.")
if x.size < window_len:
raise ValueError("Input vector needs to be bigger than window size.")
if window_len < 3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise ValueError("The window arg ({}) should be 'flat', 'hanning', 'hamming', 'bartlett', or 'blackman'"
.format(window))
s = np.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
window = window.strip().lower()
if window is None or window == 'flat':
w = np.ones(window_len, 'd')
else:
w = getattr(np, window)(window_len)
y = np.convolve(w / w.sum(), s, mode='valid')
return y[half_len + 1:-half_len] | [
"def",
"smooth",
"(",
"x",
",",
"window_len",
"=",
"11",
",",
"window",
"=",
"'hanning'",
",",
"fill",
"=",
"'reflect'",
")",
":",
"# force window_len to be an odd integer so it can be symmetrically applied",
"window_len",
"=",
"int",
"(",
"window_len",
")",
"window... | smooth the data using a window with requested size.
Convolve a normalized window with the signal.
input:
x: signal to be smoothed
window_len: the width of the smoothing window
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
fill: 'reflect' means that the signal is reflected onto both ends before filtering
output:
the smoothed signal
example:
t = linspace(-2, 2, 0.1)
x = sin(t) + 0.1 * randn(len(t))
y = smooth(x)
import seaborn
pd.DataFrame({'x': x, 'y': y}, index=t).plot()
SEE ALSO:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman
numpy.convolve
scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
NOTE: length(output) != length(input), to correct this: instead of just y.
References:
http://wiki.scipy.org/Cookbook/SignalSmooth | [
"smooth",
"the",
"data",
"using",
"a",
"window",
"with",
"requested",
"size",
"."
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L846-L907 |
242,897 | hobson/pug-invest | pug/invest/util.py | fuzzy_index_match | def fuzzy_index_match(possiblities, label, **kwargs):
"""Find the closest matching column label, key, or integer indexed value
Returns:
type(label): sequence of immutable objects corresponding to best matches to each object in label
if label is an int returns the object (value) in the list of possibilities at that index
if label is a str returns the closest str match in possibilities
>>> from collections import OrderedDict as odict
>>> fuzzy_index_match(pd.DataFrame(pd.np.random.randn(9,4), columns=list('ABCD'), index=range(9)), 'b')
'B'
>>> fuzzy_index_match(odict(zip('12345','ABCDE')), 'r2d2')
'2'
>>> fuzzy_index_match(odict(zip('12345','ABCDE')), 1)
'2'
>>> fuzzy_index_match(odict(zip('12345','ABCDE')), -1)
'5'
>>> fuzzy_index_match(odict(zip(range(4),'FOUR')), -4)
0
"""
possibilities = list(possiblities)
if isinstance(label, basestring):
return fuzzy_get(possibilities, label, **kwargs)
if isinstance(label, int):
return possibilities[label]
if isinstance(label, list):
return [fuzzy_get(possibilities, lbl) for lbl in label] | python | def fuzzy_index_match(possiblities, label, **kwargs):
"""Find the closest matching column label, key, or integer indexed value
Returns:
type(label): sequence of immutable objects corresponding to best matches to each object in label
if label is an int returns the object (value) in the list of possibilities at that index
if label is a str returns the closest str match in possibilities
>>> from collections import OrderedDict as odict
>>> fuzzy_index_match(pd.DataFrame(pd.np.random.randn(9,4), columns=list('ABCD'), index=range(9)), 'b')
'B'
>>> fuzzy_index_match(odict(zip('12345','ABCDE')), 'r2d2')
'2'
>>> fuzzy_index_match(odict(zip('12345','ABCDE')), 1)
'2'
>>> fuzzy_index_match(odict(zip('12345','ABCDE')), -1)
'5'
>>> fuzzy_index_match(odict(zip(range(4),'FOUR')), -4)
0
"""
possibilities = list(possiblities)
if isinstance(label, basestring):
return fuzzy_get(possibilities, label, **kwargs)
if isinstance(label, int):
return possibilities[label]
if isinstance(label, list):
return [fuzzy_get(possibilities, lbl) for lbl in label] | [
"def",
"fuzzy_index_match",
"(",
"possiblities",
",",
"label",
",",
"*",
"*",
"kwargs",
")",
":",
"possibilities",
"=",
"list",
"(",
"possiblities",
")",
"if",
"isinstance",
"(",
"label",
",",
"basestring",
")",
":",
"return",
"fuzzy_get",
"(",
"possibilitie... | Find the closest matching column label, key, or integer indexed value
Returns:
type(label): sequence of immutable objects corresponding to best matches to each object in label
if label is an int returns the object (value) in the list of possibilities at that index
if label is a str returns the closest str match in possibilities
>>> from collections import OrderedDict as odict
>>> fuzzy_index_match(pd.DataFrame(pd.np.random.randn(9,4), columns=list('ABCD'), index=range(9)), 'b')
'B'
>>> fuzzy_index_match(odict(zip('12345','ABCDE')), 'r2d2')
'2'
>>> fuzzy_index_match(odict(zip('12345','ABCDE')), 1)
'2'
>>> fuzzy_index_match(odict(zip('12345','ABCDE')), -1)
'5'
>>> fuzzy_index_match(odict(zip(range(4),'FOUR')), -4)
0 | [
"Find",
"the",
"closest",
"matching",
"column",
"label",
"key",
"or",
"integer",
"indexed",
"value"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L1008-L1034 |
242,898 | hobson/pug-invest | pug/invest/util.py | make_dataframe | def make_dataframe(obj, columns=None, exclude=None, limit=1e8):
"""Coerce an iterable, queryset, list or rows, dict of columns, etc into a Pandas DataFrame"""
try:
obj = obj.objects.all()[:limit]
except:
pass
if isinstance(obj, (pd.Series, list, tuple)):
return make_dataframe(pd.DataFrame(obj), columns, exclude, limit)
# if the obj is a named tuple, DataFrame, dict of columns, django QuerySet, sql alchemy query result
# retrieve the "include"d field/column names from its keys/fields/attributes
if columns is None:
columns = get_column_labels(obj)
if exclude is not None and columns is not None and columns and exclude:
columns = [i for i in columns if i not in exclude]
try:
return pd.DataFrame(list(obj.values(*columns)[:limit]))
except:
pass
try:
return pd.DataFrame(obj)[fuzzy_get(obj, columns)]
except:
pass
return pd.DataFrame(obj) | python | def make_dataframe(obj, columns=None, exclude=None, limit=1e8):
"""Coerce an iterable, queryset, list or rows, dict of columns, etc into a Pandas DataFrame"""
try:
obj = obj.objects.all()[:limit]
except:
pass
if isinstance(obj, (pd.Series, list, tuple)):
return make_dataframe(pd.DataFrame(obj), columns, exclude, limit)
# if the obj is a named tuple, DataFrame, dict of columns, django QuerySet, sql alchemy query result
# retrieve the "include"d field/column names from its keys/fields/attributes
if columns is None:
columns = get_column_labels(obj)
if exclude is not None and columns is not None and columns and exclude:
columns = [i for i in columns if i not in exclude]
try:
return pd.DataFrame(list(obj.values(*columns)[:limit]))
except:
pass
try:
return pd.DataFrame(obj)[fuzzy_get(obj, columns)]
except:
pass
return pd.DataFrame(obj) | [
"def",
"make_dataframe",
"(",
"obj",
",",
"columns",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"limit",
"=",
"1e8",
")",
":",
"try",
":",
"obj",
"=",
"obj",
".",
"objects",
".",
"all",
"(",
")",
"[",
":",
"limit",
"]",
"except",
":",
"pass",... | Coerce an iterable, queryset, list or rows, dict of columns, etc into a Pandas DataFrame | [
"Coerce",
"an",
"iterable",
"queryset",
"list",
"or",
"rows",
"dict",
"of",
"columns",
"etc",
"into",
"a",
"Pandas",
"DataFrame"
] | 836911258a0e920083a88c91beae88eefdebb20c | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/util.py#L1062-L1084 |
242,899 | armstrong/armstrong.apps.related_content | armstrong/apps/related_content/managers.py | RelatedContentQuerySet.filter | def filter(self, destination_object=None, source_object=None, **kwargs):
"""
See ``QuerySet.filter`` for full documentation
This adds support for ``destination_object`` and ``source_object``
as kwargs. This converts those objects into the values necessary
to handle the ``GenericForeignKey`` fields.
"""
if destination_object:
kwargs.update({
"destination_id": destination_object.pk,
"destination_type": get_for_model(destination_object),
})
if source_object:
kwargs.update({
"source_id": source_object.pk,
"source_type": get_for_model(source_object),
})
return super(RelatedContentQuerySet, self).filter(**kwargs) | python | def filter(self, destination_object=None, source_object=None, **kwargs):
"""
See ``QuerySet.filter`` for full documentation
This adds support for ``destination_object`` and ``source_object``
as kwargs. This converts those objects into the values necessary
to handle the ``GenericForeignKey`` fields.
"""
if destination_object:
kwargs.update({
"destination_id": destination_object.pk,
"destination_type": get_for_model(destination_object),
})
if source_object:
kwargs.update({
"source_id": source_object.pk,
"source_type": get_for_model(source_object),
})
return super(RelatedContentQuerySet, self).filter(**kwargs) | [
"def",
"filter",
"(",
"self",
",",
"destination_object",
"=",
"None",
",",
"source_object",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"destination_object",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"destination_id\"",
":",
"destination_object",
"... | See ``QuerySet.filter`` for full documentation
This adds support for ``destination_object`` and ``source_object``
as kwargs. This converts those objects into the values necessary
to handle the ``GenericForeignKey`` fields. | [
"See",
"QuerySet",
".",
"filter",
"for",
"full",
"documentation"
] | f57b6908d3c76c4a44b2241c676ab5d86391106c | https://github.com/armstrong/armstrong.apps.related_content/blob/f57b6908d3c76c4a44b2241c676ab5d86391106c/armstrong/apps/related_content/managers.py#L9-L27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.