INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns a new class with named fields. | def recordtype(typename, field_names, verbose=False, **default_kwds):
'''Returns a new class with named fields.
@keyword field_defaults: A mapping from (a subset of) field names to default
values.
@keyword default: If provided, the default value for all fields without an
explicit default i... |
one - dimensional arrays having shape [ N ] row and column matrices having shape [ 1 N ] and [ N 1 ] correspondingly and their generalizations having shape [ 1 1... N... 1 1 1 ]. Scalars have shape [ 1 1... 1 ]. Empty arrays dont count | def isvector_or_scalar(a):
"""
one-dimensional arrays having shape [N],
row and column matrices having shape [1 N] and
[N 1] correspondingly, and their generalizations
having shape [1 1 ... N ... 1 1 1].
Scalars have shape [1 1 ... 1].
Empty arrays dont count
"""
try:
return ... |
>>> a = arange ( 1 10 ) # 1: 10 >>> size ( a ) matlabarray ( [[ 1 10 ]] ) | def arange(start,stop,step=1,**kwargs):
"""
>>> a=arange(1,10) # 1:10
>>> size(a)
matlabarray([[ 1, 10]])
"""
expand_value = 1 if step > 0 else -1
return matlabarray(np.arange(start,
stop+expand_value,
step,
... |
>>> concat ( [ 1 2 3 4 5 ] [ 1 2 3 4 5 ]] ) [ 1 2 3 4 5 1 2 3 4 5 ] | def concat(args):
"""
>>> concat([1,2,3,4,5] , [1,2,3,4,5]])
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
"""
import pdb
pdb.set_trace()
t = [matlabarray(a) for a in args]
return np.concatenate(t) |
>>> size ( zeros ( 3 3 )) + 1 matlabarray ( [[ 4 4 ]] ) | def size(a, b=0, nargout=1):
"""
>>> size(zeros(3,3)) + 1
matlabarray([[4, 4]])
"""
s = np.asarray(a).shape
if s is ():
return 1 if b else (1,)*nargout
# a is not a scalar
try:
if b:
return s[b-1]
else:
return matlabarray(s) if nargout <= 1... |
top: | top stmt | def p_top(p):
"""
top :
| top stmt
"""
if len(p) == 1:
p[0] = node.stmt_list()
else:
p[0] = p[1]
p[0].append(p[2]) |
top: top END_FUNCTION | def p_end_function(p):
"""
top : top END_FUNCTION
"""
p[0] = p[1]
p[0].append(node.return_stmt(ret=ret_expr))
p[0].append(node.comment_stmt("\nif __name__ == '__main__':\n pass")) |
arg1: STRING | NUMBER | IDENT | GLOBAL | def p_arg1(p):
"""
arg1 : STRING
| NUMBER
| IDENT
| GLOBAL
"""
# a hack to support "clear global"
p[0] = node.string(value=str(p[1]), lineno=p.lineno(1), lexpos=p.lexpos(1)) |
arg_list: ident_init_opt | arg_list COMMA ident_init_opt | def p_arg_list(p):
"""
arg_list : ident_init_opt
| arg_list COMMA ident_init_opt
"""
if len(p) == 2:
p[0] = node.expr_list([p[1]])
elif len(p) == 4:
p[0] = p[1]
p[0].append(p[3])
else:
assert 0
assert isinstance(p[0], node.expr_list) |
args: arg1 | args arg1 | def p_args(p):
"""
args : arg1
| args arg1
"""
if len(p) == 2:
p[0] = node.expr_list([p[1]])
else:
p[0] = p[1]
p[0].append(p[2]) |
case_list: | CASE expr sep stmt_list_opt case_list | CASE expr error stmt_list_opt case_list | OTHERWISE stmt_list | def p_case_list(p):
"""
case_list :
| CASE expr sep stmt_list_opt case_list
| CASE expr error stmt_list_opt case_list
| OTHERWISE stmt_list
"""
if len(p) == 1:
p[0] = node.stmt_list()
elif len(p) == 3:
assert isinstance(p[2], node.stmt_list)
... |
cellarray: LBRACE RBRACE | LBRACE expr_list RBRACE | LBRACE concat_list RBRACE | LBRACE concat_list SEMI RBRACE | def p_cellarray(p):
"""
cellarray : LBRACE RBRACE
| LBRACE expr_list RBRACE
| LBRACE concat_list RBRACE
| LBRACE concat_list SEMI RBRACE
"""
if len(p) == 3:
p[0] = node.cellarray(op="{}", args=node.expr_list())
else:
p[0] = node.cellarray(op=... |
expr: expr LBRACE expr_list RBRACE | expr LBRACE RBRACE | def p_cellarrayref(p):
"""expr : expr LBRACE expr_list RBRACE
| expr LBRACE RBRACE
"""
args = node.expr_list() if len(p) == 4 else p[3]
assert isinstance(args, node.expr_list)
p[0] = node.cellarrayref(func_expr=p[1], args=args) |
concat_list: expr_list SEMI expr_list | concat_list SEMI expr_list | def p_concat_list(p):
"""
concat_list : expr_list SEMI expr_list
| concat_list SEMI expr_list
"""
if p[1].__class__ == node.expr_list:
p[0] = node.concat_list([p[1], p[3]])
else:
p[0] = p[1]
p[0].append(p[3]) |
elseif_stmt: | ELSE stmt_list_opt | ELSEIF expr sep stmt_list_opt elseif_stmt | ELSEIF LPAREN expr RPAREN stmt_list_opt elseif_stmt | def p_elseif_stmt(p):
"""
elseif_stmt :
| ELSE stmt_list_opt
| ELSEIF expr sep stmt_list_opt elseif_stmt
| ELSEIF LPAREN expr RPAREN stmt_list_opt elseif_stmt
"""
if len(p) == 1:
p[0] = node.stmt_list()
elif len(p) == 3:
p[0] = p[2]
... |
expr1: MINUS expr %prec UMINUS | PLUS expr %prec UMINUS | NEG expr | HANDLE ident | PLUSPLUS ident | MINUSMINUS ident | def p_expr1(p):
"""expr1 : MINUS expr %prec UMINUS
| PLUS expr %prec UMINUS
| NEG expr
| HANDLE ident
| PLUSPLUS ident
| MINUSMINUS ident
"""
p[0] = node.expr(op=p[1], args=node.expr_list([p[2]])) |
expr2: expr AND expr | expr ANDAND expr | expr BACKSLASH expr | expr COLON expr | expr DIV expr | expr DOT expr | expr DOTDIV expr | expr DOTDIVEQ expr | expr DOTEXP expr | expr DOTMUL expr | expr DOTMULEQ expr | expr EQEQ expr | expr POW expr | expr EXP expr | expr EXPEQ expr | expr GE expr | expr GT expr | expr LE ex... | def p_expr2(p):
"""expr2 : expr AND expr
| expr ANDAND expr
| expr BACKSLASH expr
| expr COLON expr
| expr DIV expr
| expr DOT expr
| expr DOTDIV expr
| expr DOTDIVEQ expr
| expr DOTEXP expr
| expr D... |
end: END_EXPR | def p_expr_end(p):
"end : END_EXPR"
p[0] = node.expr(
op="end", args=node.expr_list([node.number(0), node.number(0)])) |
ident: IDENT | def p_expr_ident(p):
"ident : IDENT"
global use_nargin, use_varargin
if p[1] == "varargin":
use_varargin = 1
if p[1] == "nargin":
use_nargin = 1
# import pdb; pdb.set_trace()
p[0] = node.ident(
name=p[1],
lineno=p.lineno(1),
column=p.lexpos(1) - p.lexer.le... |
ident_init_opt: NEG | ident | ident EQ expr | def p_ident_init_opt(p):
"""
ident_init_opt : NEG
| ident
| ident EQ expr
"""
if p[1] == '~':
p[0] = node.ident("__")
else:
p[0] = p[1]
if len(p) == 2:
p[0].init = node.ident(name="None")
else:
p[0].init = p[3] |
number: NUMBER | def p_expr_number(p):
"number : NUMBER"
p[0] = node.number(p[1], lineno=p.lineno(1), lexpos=p.lexpos(1)) |
expr_stmt: expr_list SEMI | def p_expr_stmt(p):
"""
expr_stmt : expr_list SEMI
"""
assert isinstance(p[1], node.expr_list)
p[0] = node.expr_stmt(expr=p[1]) |
string: STRING | def p_expr_string(p):
"string : STRING"
p[0] = node.string(p[1], lineno=p.lineno(1), lexpos=p.lexpos(1)) |
exprs: expr | exprs COMMA expr | def p_exprs(p):
"""
exprs : expr
| exprs COMMA expr
"""
if len(p) == 2:
p[0] = node.expr_list([p[1]])
elif len(p) == 4:
p[0] = p[1]
p[0].append(p[3])
else:
assert (0)
assert isinstance(p[0], node.expr_list) |
expr: expr FIELD | def p_field_expr(p):
"""
expr : expr FIELD
"""
p[0] = node.expr(
op=".",
args=node.expr_list([
p[1], node.ident(
name=p[2], lineno=p.lineno(2), lexpos=p.lexpos(2))
])) |
foo_stmt: expr OROR expr SEMI | def p_foo_stmt(p):
"foo_stmt : expr OROR expr SEMI"
expr1 = p[1][1][0]
expr2 = p[3][1][0]
ident = expr1.ret
args1 = expr1.args
args2 = expr2.args
p[0] = node.let(ret=ident,
args=node.expr("or", node.expr_list([args1, args2]))) |
for_stmt: FOR ident EQ expr SEMI stmt_list END_STMT | FOR LPAREN ident EQ expr RPAREN SEMI stmt_list END_STMT | FOR matrix EQ expr SEMI stmt_list END_STMT | def p_for_stmt(p):
"""
for_stmt : FOR ident EQ expr SEMI stmt_list END_STMT
| FOR LPAREN ident EQ expr RPAREN SEMI stmt_list END_STMT
| FOR matrix EQ expr SEMI stmt_list END_STMT
"""
if len(p) == 8:
if not isinstance(p[2], node.ident):
raise_exception(Syntax... |
func_stmt: FUNCTION ident lambda_args SEMI | FUNCTION ret EQ ident lambda_args SEMI | def p_func_stmt(p):
"""func_stmt : FUNCTION ident lambda_args SEMI
| FUNCTION ret EQ ident lambda_args SEMI
"""
# stmt_list of func_stmt is set below
# marked with XYZZY
global ret_expr, use_nargin, use_varargin
ret_expr = node.expr_list()
use_varargin = use_nargin = 0
... |
expr: expr LPAREN expr_list RPAREN | expr LPAREN RPAREN | def p_funcall_expr(p):
"""expr : expr LPAREN expr_list RPAREN
| expr LPAREN RPAREN
"""
if (len(p) == 5 and len(p[3]) == 1 and p[3][0].__class__ is node.expr and
p[3][0].op == ":" and not p[3][0].args):
# foo(:) => ravel(foo)
p[0] = node.funcall(
func_expr=... |
global_list: ident | global_list ident | def p_global_list(p):
"""global_list : ident
| global_list ident
"""
if len(p) == 2:
p[0] = node.global_list([p[1]])
elif len(p) == 3:
p[0] = p[1]
p[0].append(p[2]) |
global_stmt: GLOBAL global_list SEMI | GLOBAL ident EQ expr SEMI | def p_global_stmt(p):
"""
global_stmt : GLOBAL global_list SEMI
| GLOBAL ident EQ expr SEMI
"""
p[0] = node.global_stmt(p[2])
for ident in p[0]:
ident.props = "G" |
if_stmt: IF expr sep stmt_list_opt elseif_stmt END_STMT | IF LPAREN expr RPAREN stmt_list_opt elseif_stmt END_STMT | def p_if_stmt(p):
"""
if_stmt : IF expr sep stmt_list_opt elseif_stmt END_STMT
| IF LPAREN expr RPAREN stmt_list_opt elseif_stmt END_STMT
"""
if len(p) == 7:
p[0] = node.if_stmt(cond_expr=p[2], then_stmt=p[4], else_stmt=p[5])
elif len(p) == 8:
p[0] = node.if_stmt(cond_exp... |
matrix: LBRACKET RBRACKET | LBRACKET concat_list RBRACKET | LBRACKET concat_list SEMI RBRACKET | LBRACKET expr_list RBRACKET | LBRACKET expr_list SEMI RBRACKET | def p_matrix(p):
"""matrix : LBRACKET RBRACKET
| LBRACKET concat_list RBRACKET
| LBRACKET concat_list SEMI RBRACKET
| LBRACKET expr_list RBRACKET
| LBRACKET expr_list SEMI RBRACKET
"""
if len(p) == 3:
p[0] = node.matrix()
else:
p[0]... |
expr: LPAREN expr RPAREN | def p_parens_expr(p):
"""
expr : LPAREN expr RPAREN
"""
p[0] = node.expr(op="parens", args=node.expr_list([p[2]])) |
ret: ident | LBRACKET RBRACKET | LBRACKET expr_list RBRACKET | def p_ret(p):
"""
ret : ident
| LBRACKET RBRACKET
| LBRACKET expr_list RBRACKET
"""
if len(p) == 2:
p[0] = node.expr_list([p[1]])
elif len(p) == 3:
p[0] = node.expr_list([])
elif len(p) == 4:
assert isinstance(p[2], node.expr_list)
p[0] = p[2]
... |
stmt_list: stmt | stmt_list stmt | def p_stmt_list(p):
"""
stmt_list : stmt
| stmt_list stmt
"""
if len(p) == 2:
p[0] = node.stmt_list([p[1]] if p[1] else [])
elif len(p) == 3:
p[0] = p[1]
if p[2]:
p[0].append(p[2])
else:
assert 0 |
switch_stmt: SWITCH expr semi_opt case_list END_STMT | def p_switch_stmt(p):
"""
switch_stmt : SWITCH expr semi_opt case_list END_STMT
"""
def backpatch(expr, stmt):
if isinstance(stmt, node.if_stmt):
stmt.cond_expr.args[1] = expr
backpatch(expr, stmt.else_stmt)
backpatch(p[2], p[4])
p[0] = p[4] |
try_catch: TRY stmt_list CATCH stmt_list END_STMT | def p_try_catch(p):
"""
try_catch : TRY stmt_list CATCH stmt_list END_STMT
"""
## | TRY stmt_list END_STMT
assert isinstance(p[2], node.stmt_list)
# assert isinstance(p[4],node.stmt_list)
p[0] = node.try_catch(
try_stmt=p[2],
catch_stmt=p[4],
finally_stmt=node.stmt_li... |
unwind: UNWIND_PROTECT stmt_list UNWIND_PROTECT_CLEANUP stmt_list END_UNWIND_PROTECT | def p_unwind(p):
"""
unwind : UNWIND_PROTECT stmt_list UNWIND_PROTECT_CLEANUP stmt_list END_UNWIND_PROTECT
"""
p[0] = node.try_catch(
try_stmt=p[2], catch_stmt=node.expr_list(), finally_stmt=p[4]) |
while_stmt: WHILE expr SEMI stmt_list END_STMT | def p_while_stmt(p):
"""
while_stmt : WHILE expr SEMI stmt_list END_STMT
"""
assert isinstance(p[4], node.stmt_list)
p[0] = node.while_stmt(cond_expr=p[2], stmt_list=p[4]) |
To the parser funcall is indistinguishable from rhs array reference. But LHS references can be converted to arrayref nodes. | def to_arrayref(u):
"""
To the parser, funcall is indistinguishable
from rhs array reference. But LHS references
can be converted to arrayref nodes.
"""
if u.__class__ is node.funcall:
try:
if u.func_expr.props in "UR": # upd,ref
u.__class__ = node.arrayref
... |
Array colon subscripts foo ( 1: 10 ) and colon expressions 1: 10 look too similar to each other. Now is the time to find out who is who. | def colon_subscripts(u):
"""
Array colon subscripts foo(1:10) and colon expressions 1:10 look
too similar to each other. Now is the time to find out who is who.
"""
if u.__class__ in (node.arrayref,node.cellarrayref):
for w in u.args:
if w.__class__ is node.expr and w.op == ":":... |
If LHS is a plain variable and RHS is a matrix enclosed in square brackets replace the matrix expr with a funcall. | def let_statement(u):
"""
If LHS is a plain variable, and RHS is a matrix
enclosed in square brackets, replace the matrix
expr with a funcall.
"""
if u.__class__ is node.let:
if (u.ret.__class__ is node.ident and
u.args.__class__ is node.matrix):
u.args = node.fun... |
Convert +++/ --- formatted win/ loss streak column into a +/ - integer column | def process_win_streak(data):
"""
Convert "+++"/"---" formatted win/loss streak column into a +/- integer column
"""
#only do this if there are non-NANs in the column
if data['Streak'].count()>0:
data['Streak2'] = data['Streak'].str.len()
data.loc[data['Streak'].str[0]=='-','Streak2'... |
Splits Statcast queries to avoid request timeouts | def split_request(start_dt, end_dt, player_id, url):
"""
Splits Statcast queries to avoid request timeouts
"""
current_dt = datetime.datetime.strptime(start_dt, '%Y-%m-%d')
end_dt = datetime.datetime.strptime(end_dt, '%Y-%m-%d')
results = [] # list to hold data as it is returned
player_id =... |
Get zip file from provided URL | def get_zip_file(url):
"""
Get zip file from provided URL
"""
with requests.get(url, stream=True) as f:
z = zipfile.ZipFile(io.BytesIO(f.content))
return z |
Pulls statcast pitch - level data from Baseball Savant for a given pitcher. | def statcast_pitcher(start_dt=None, end_dt=None, player_id=None):
"""
Pulls statcast pitch-level data from Baseball Savant for a given pitcher.
ARGUMENTS
start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data
end_dt : YYYY-MM-DD : the final date for which you want data
... |
Get all batting stats for a set time range. This can be the past week the month of August anything. Just supply the start and end date in YYYY - MM - DD format. | def batting_stats_range(start_dt=None, end_dt=None):
"""
Get all batting stats for a set time range. This can be the past week, the
month of August, anything. Just supply the start and end date in YYYY-MM-DD
format.
"""
# make sure date inputs are valid
start_dt, end_dt = sanitize_input(star... |
Get all batting stats for a set season. If no argument is supplied gives stats for current season to date. | def batting_stats_bref(season=None):
"""
Get all batting stats for a set season. If no argument is supplied, gives
stats for current season to date.
"""
if season is None:
season = datetime.datetime.today().strftime("%Y")
season = str(season)
start_dt = season + '-03-01' #opening day... |
Pull Retrosheet game logs for a given season | def season_game_logs(season):
"""
Pull Retrosheet game logs for a given season
"""
# validate input
max_year = int(datetime.now().year) - 1
if season > max_year or season < 1871:
raise ValueError('Season must be between 1871 and {}'.format(max_year))
file_name = 'GL{}.TXT'.format(sea... |
Pull Retrosheet World Series Game Logs | def world_series_logs():
"""
Pull Retrosheet World Series Game Logs
"""
file_name = 'GLWS.TXT'
z = get_zip_file(world_series_url)
data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"')
data.columns = gamelog_columns
return data |
Pull Retrosheet All Star Game Logs | def all_star_game_logs():
"""
Pull Retrosheet All Star Game Logs
"""
file_name = 'GLAS.TXT'
z = get_zip_file(all_star_url)
data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"')
data.columns = gamelog_columns
return data |
Pull Retrosheet Wild Card Game Logs | def wild_card_logs():
"""
Pull Retrosheet Wild Card Game Logs
"""
file_name = 'GLWC.TXT'
z = get_zip_file(wild_card_url)
data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"')
data.columns = gamelog_columns
return data |
Pull Retrosheet Division Series Game Logs | def division_series_logs():
"""
Pull Retrosheet Division Series Game Logs
"""
file_name = 'GLDV.TXT'
z = get_zip_file(division_series_url)
data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"')
data.columns = gamelog_columns
return data |
Pull Retrosheet LCS Game Logs | def lcs_logs():
"""
Pull Retrosheet LCS Game Logs
"""
file_name = 'GLLC.TXT'
z = get_zip_file(lcs_url)
data = pd.read_csv(z.open(file_name), header=None, sep=',', quotechar='"')
data.columns = gamelog_columns
return data |
Get season - level pitching data aggregated by team. | def team_pitching(start_season, end_season=None, league='all', ind=1):
"""
Get season-level pitching data aggregated by team.
ARGUMENTS:
start_season : int : first season you want data for (or the only season if you do not specify an end_season)
end_season : int : final season you want data for
... |
Get season - level Pitching Statistics for Specific Team ( from Baseball - Reference ) | def team_pitching_bref(team, start_season, end_season=None):
"""
Get season-level Pitching Statistics for Specific Team (from Baseball-Reference)
ARGUMENTS:
team : str : The Team Abbreviation (i.e. 'NYY' for Yankees) of the Team you want data for
start_season : int : first season you want data for ... |
Pulls statcast pitch - level data from Baseball Savant for a given batter. | def statcast_batter(start_dt=None, end_dt=None, player_id=None):
"""
Pulls statcast pitch-level data from Baseball Savant for a given batter.
ARGUMENTS
start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data
end_dt : YYYY-MM-DD : the final date for which you want data
... |
Retrieve a table of player information given a list of player ids | def playerid_reverse_lookup(player_ids, key_type=None):
"""Retrieve a table of player information given a list of player ids
:param player_ids: list of player ids
:type player_ids: list
:param key_type: name of the key type being looked up (one of "mlbam", "retro", "bbref", or "fangraphs")
:type ke... |
Get season - level pitching data from FanGraphs. | def pitching_stats(start_season, end_season=None, league='all', qual=1, ind=1):
"""
Get season-level pitching data from FanGraphs.
ARGUMENTS:
start_season : int : first season you want data for (or the only season if you do not specify an end_season)
end_season : int : final season you want data f... |
break start and end date into smaller increments collecting all data in small chunks and appending all results to a common dataframe end_dt is the date strings for the final day of the query d1 and d2 are datetime objects for first and last day of query for doing date math a third datetime object ( d ) will be used to ... | def large_request(start_dt,end_dt,d1,d2,step,verbose):
"""
break start and end date into smaller increments, collecting all data in small chunks and appending all results to a common dataframe
end_dt is the date strings for the final day of the query
d1 and d2 are datetime objects for first and last day... |
Pulls statcast play - level data from Baseball Savant for a given date range. | def statcast(start_dt=None, end_dt=None, team=None, verbose=True):
"""
Pulls statcast play-level data from Baseball Savant for a given date range.
INPUTS:
start_dt: YYYY-MM-DD : the first date for which you want statcast data
end_dt: YYYY-MM-DD : the last date for which you want statcast data
t... |
Pulls statcast play - level data from Baseball Savant for a single game identified by its MLB game ID ( game_pk in statcast data ) | def statcast_single_game(game_pk, team=None):
"""
Pulls statcast play-level data from Baseball Savant for a single game,
identified by its MLB game ID (game_pk in statcast data)
INPUTS:
game_pk : 6-digit integer MLB game ID to retrieve
"""
data = single_game_request(game_pk)
data = post... |
Get all pitching stats for a set time range. This can be the past week the month of August anything. Just supply the start and end date in YYYY - MM - DD format. | def pitching_stats_range(start_dt=None, end_dt=None):
"""
Get all pitching stats for a set time range. This can be the past week, the
month of August, anything. Just supply the start and end date in YYYY-MM-DD
format.
"""
# ensure valid date strings, perform necessary processing for query
... |
Get all pitching stats for a set season. If no argument is supplied gives stats for current season to date. | def pitching_stats_bref(season=None):
"""
Get all pitching stats for a set season. If no argument is supplied, gives stats for
current season to date.
"""
if season is None:
season = datetime.datetime.today().strftime("%Y")
season = str(season)
start_dt = season + '-03-01' #opening... |
Get data from war_daily_pitch table. Returns WAR its components and a few other useful stats. To get all fields from this table supply argument return_all = True. | def bwar_pitch(return_all=False):
"""
Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats.
To get all fields from this table, supply argument return_all=True.
"""
url = "http://www.baseball-reference.com/data/war_daily_pitch.txt"
s = requests.get(url... |
Decorator to mark a specified function as deprecated | def deprecated(version, *replacement):
""" Decorator to mark a specified function as deprecated
:param version: version in which it is deprecated
:param replacement: replacement functions to use
"""
def deprecated_wrapper(func):
replacement_message = 'Use {} instead'.format(', '.join(
... |
Returns a dictionary in cloud format | def to_api_data(self, restrict_keys=None):
""" Returns a dictionary in cloud format
:param restrict_keys: a set of keys to restrict the returned data to.
"""
cc = self._cc # alias
data = {
cc('displayName'): self.__display_name,
cc('givenName'): self.__... |
Deletes this contact | def delete(self):
""" Deletes this contact
:return: Success or Failure
:rtype: bool
:raises RuntimeError: if contact is not yet saved to cloud
"""
if not self.object_id:
raise RuntimeError('Attempting to delete an unsaved Contact')
url = self.build_u... |
Saves this contact to the cloud ( create or update existing one based on what values have changed ) | def save(self):
""" Saves this contact to the cloud (create or update existing one
based on what values have changed)
:return: Saved or Not
:rtype: bool
"""
if self.object_id:
# Update Contact
if not self._track_changes:
return Tru... |
This method returns a new draft Message instance with contacts first email as a recipient | def new_message(self, recipient=None, *, recipient_type=RecipientType.TO):
""" This method returns a new draft Message instance with
contacts first email as a recipient
:param Recipient recipient: a Recipient instance where to send this
message. If None first email of this contact will... |
Gets a list of contacts from this address book | def get_contacts(self, limit=100, *, query=None, order_by=None, batch=None):
""" Gets a list of contacts from this address book
When querying the Global Address List the Users endpoint will be used.
Only a limited set of information will be available unless you have
access to scope 'Use... |
Returns a Contact by it s email | def get_contact_by_email(self, email):
""" Returns a Contact by it's email
:param email: email to get contact for
:return: Contact for specified email
:rtype: Contact
"""
if not email:
return None
email = email.strip()
query = self.q().any(co... |
Returns a list of child folders | def get_folders(self, limit=None, *, query=None, order_by=None):
""" Returns a list of child folders
:param int limit: max no. of folders to get. Over 999 uses batch.
:param query: applies a OData filter to the request
:type query: Query or str
:param order_by: orders the result... |
Creates a new child folder | def create_child_folder(self, folder_name):
""" Creates a new child folder
:param str folder_name: name of the new folder to create
:return: newly created folder
:rtype: ContactFolder or None
"""
if not folder_name:
return None
if self.root:
... |
Change this folder name | def update_folder_name(self, name):
""" Change this folder name
:param str name: new name to change to
:return: Updated or Not
:rtype: bool
"""
if self.root:
return False
if not name:
return False
url = self.build_url(
... |
Change this folder name | def move_folder(self, to_folder):
""" Change this folder name
:param to_folder: folder_id/ContactFolder to move into
:type to_folder: str or ContactFolder
:return: Moved or Not
:rtype: bool
"""
if self.root:
return False
if not to_folder:
... |
Creates a new contact to be saved into it s parent folder | def new_contact(self):
""" Creates a new contact to be saved into it's parent folder
:return: newly created contact
:rtype: Contact
"""
contact = self.contact_constructor(parent=self)
if not self.root:
contact.__folder_id = self.folder_id
return conta... |
This method returns a new draft Message instance with all the contacts first email as a recipient | def new_message(self, recipient_type=RecipientType.TO, *, query=None):
""" This method returns a new draft Message instance with all the
contacts first email as a recipient
:param RecipientType recipient_type: section to add recipient into
:param query: applies a OData filter to the req... |
Returns a Contact by it s email | def get_contact_by_email(self, email):
""" Returns a Contact by it's email
:param email: email to get contact for
:return: Contact for specified email
:rtype: Contact
"""
if not email:
return None
email = email.strip()
url = self.build_url('... |
Sets this message as flagged: param start_date: the start datetime of the followUp: param due_date: the due datetime of the followUp | def set_flagged(self, *, start_date=None, due_date=None):
""" Sets this message as flagged
:param start_date: the start datetime of the followUp
:param due_date: the due datetime of the followUp
"""
self.__status = Flag.Flagged
start_date = start_date or dt.datetime.now()... |
Sets this message flag as completed: param completition_date: the datetime this followUp was completed | def set_completed(self, *, completition_date=None):
""" Sets this message flag as completed
:param completition_date: the datetime this followUp was completed
"""
self.__status = Flag.Complete
completition_date = completition_date or dt.datetime.now()
if completition_date... |
Sets this message as un flagged | def delete_flag(self):
""" Sets this message as un flagged """
self.__status = Flag.NotFlagged
self.__start = None
self.__due_date = None
self.__completed = None
self._track_changes() |
Returns this data as a dict to be sent to the server | def to_api_data(self):
""" Returns this data as a dict to be sent to the server """
data = {
self._cc('flagStatus'): self._cc(self.__status.value)
}
if self.__status is Flag.Flagged:
data[self._cc('startDateTime')] = self._build_date_time_time_zone(self.__start)
... |
sender is a property to force to be always a Recipient class | def sender(self, value):
""" sender is a property to force to be always a Recipient class """
if isinstance(value, Recipient):
if value._parent is None:
value._parent = self
value._field = 'from'
self.__sender = value
elif isinstance(value,... |
Returns a dict representation of this message prepared to be send to the cloud | def to_api_data(self, restrict_keys=None):
""" Returns a dict representation of this message prepared to be send
to the cloud
:param restrict_keys: a set of keys to restrict the returned
data to
:type restrict_keys: dict or set
:return: converted to cloud based keys
... |
Sends this message | def send(self, save_to_sent_folder=True):
""" Sends this message
:param bool save_to_sent_folder: whether or not to save it to
sent folder
:return: Success / Failure
:rtype: bool
"""
if self.object_id and not self.__is_draft:
return RuntimeError('No... |
Creates a new message that is a reply to this message | def reply(self, to_all=True):
""" Creates a new message that is a reply to this message
:param bool to_all: whether or not to replies to all the recipients
instead to just the sender
:return: new message
:rtype: Message
"""
if not self.object_id or self.__is_dr... |
Creates a new message that is a forward this message | def forward(self):
""" Creates a new message that is a forward this message
:return: new message
:rtype: Message
"""
if not self.object_id or self.__is_draft:
raise RuntimeError("Can't forward this message")
url = self.build_url(
self._endpoints... |
Marks this message as read in the cloud | def mark_as_read(self):
""" Marks this message as read in the cloud
:return: Success / Failure
:rtype: bool
"""
if self.object_id is None or self.__is_draft:
raise RuntimeError('Attempting to mark as read an unsaved Message')
data = {self._cc('isRead'): True... |
Move the message to a given folder | def move(self, folder):
""" Move the message to a given folder
:param folder: Folder object or Folder id or Well-known name to
move this message to
:type folder: str or mailbox.Folder
:return: Success / Failure
:rtype: bool
"""
if self.object_id is None:... |
Copy the message to a given folder | def copy(self, folder):
""" Copy the message to a given folder
:param folder: Folder object or Folder id or Well-known name to
copy this message to
:type folder: str or mailbox.Folder
:returns: the copied message
:rtype: Message
"""
if self.object_id is ... |
Saves changes to a message. If the message is a new or saved draft it will call save_draft otherwise this will save only properties of a message that are draft - independent such as: - is_read - category - flag: return: Success/ Failure: rtype: bool | def save_message(self):
""" Saves changes to a message.
If the message is a new or saved draft it will call 'save_draft' otherwise
this will save only properties of a message that are draft-independent such as:
- is_read
- category
- flag
:return: Succ... |
Save this message as a draft on the cloud | def save_draft(self, target_folder=OutlookWellKnowFolderNames.DRAFTS):
""" Save this message as a draft on the cloud
:param target_folder: name of the drafts folder
:return: Success / Failure
:rtype: bool
"""
if self.object_id:
# update message. Attachments ... |
If this is a EventMessage it should return the related Event | def get_event(self):
""" If this is a EventMessage it should return the related Event"""
if not self.is_event_message:
return None
# select a dummy field (eg. subject) to avoid pull unneccesary data
query = self.q().select('subject').expand('event')
url = self.buil... |
Builds the distribution files: wheels and source. | def build(force):
""" Builds the distribution files: wheels and source. """
dist_path = Path(DIST_PATH)
if dist_path.exists() and list(dist_path.glob('*')):
if force or click.confirm('{} is not empty - delete contents?'.format(dist_path)):
dist_path.rename(DIST_PATH_DELETE)
s... |
Uploads distribuition files to pypi or pypitest. | def upload(ctx, release, rebuild):
""" Uploads distribuition files to pypi or pypitest. """
dist_path = Path(DIST_PATH)
if rebuild is False:
if not dist_path.exists() or not list(dist_path.glob('*')):
print("No distribution files found. Please run 'build' command first")
retu... |
Checks the long description. | def check():
""" Checks the long description. """
dist_path = Path(DIST_PATH)
if not dist_path.exists() or not list(dist_path.glob('*')):
print("No distribution files found. Please run 'build' command first")
return
subprocess.check_call(['twine', 'check', 'dist/*']) |
Lists all releases published on pypi. | def list_releases():
""" Lists all releases published on pypi. """
response = requests.get(PYPI_URL.format(package=PYPI_PACKAGE_NAME))
if response:
data = response.json()
releases_dict = data.get('releases', {})
if releases_dict:
for version, release in releases_dict.it... |
Displays a table of the contributors and to what extent we have them to thank. | def contribution_breakdown():
""" Displays a table of the contributors and to what extent we have them to thank."""
args = ['git', 'blame']
counts = {}
line_format = '{0:30}\t{1:>10}\t{2:>10}%'
files = subprocess.check_output(['git', 'ls-files']).decode("utf-8").split('\n')
for f in files[:-1]:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.