code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def filter_keys(cls, data):
keys = list(data.keys())
for pattern in cls.EXCLUDE_PATTERNS:
for key in keys:
if re.match(pattern, key):
keys.remove(key)
return dict(filter(lambda x: x[0] in keys, data.items())) | Filter GELF record keys using exclude_patterns
:param dict data: Log record has dict
:return: the filtered log record
:rtype: dict |
def write_config(self):
json.dump(
self.config,
open(CONFIG_FILE, 'w'),
indent=4,
separators=(',', ': ')
)
return True | Write the configuration to a local file.
:return: Boolean if successful |
def load_config(self, **kwargs):
virgin_config = False
if not os.path.exists(CONFIG_PATH):
virgin_config = True
os.makedirs(CONFIG_PATH)
if not os.path.exists(CONFIG_FILE):
virgin_config = True
if not virgin_config:
self.config = j... | Load the configuration for the user or seed it with defaults.
:return: Boolean if successful |
def create_table_rate_rule(cls, table_rate_rule, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_table_rate_rule_with_http_info(table_rate_rule, **kwargs)
else:
(data) = cls._create_table_rate_rule_with_http_info(tabl... | Create TableRateRule
Create a new TableRateRule
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_table_rate_rule(table_rate_rule, async=True)
>>> result = thread.get()
:param as... |
def delete_table_rate_rule_by_id(cls, table_rate_rule_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_table_rate_rule_by_id_with_http_info(table_rate_rule_id, **kwargs)
else:
(data) = cls._delete_table_rate_rule_b... | Delete TableRateRule
Delete an instance of TableRateRule by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_table_rate_rule_by_id(table_rate_rule_id, async=True)
>>> result = th... |
def get_table_rate_rule_by_id(cls, table_rate_rule_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_table_rate_rule_by_id_with_http_info(table_rate_rule_id, **kwargs)
else:
(data) = cls._get_table_rate_rule_by_id_with... | Find TableRateRule
Return single instance of TableRateRule by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_table_rate_rule_by_id(table_rate_rule_id, async=True)
>>> result = thr... |
def list_all_table_rate_rules(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_table_rate_rules_with_http_info(**kwargs)
else:
(data) = cls._list_all_table_rate_rules_with_http_info(**kwargs)
return ... | List TableRateRules
Return a list of TableRateRules
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_table_rate_rules(async=True)
>>> result = thread.get()
:param async bool
... |
def replace_table_rate_rule_by_id(cls, table_rate_rule_id, table_rate_rule, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_table_rate_rule_by_id_with_http_info(table_rate_rule_id, table_rate_rule, **kwargs)
else:
(d... | Replace TableRateRule
Replace all attributes of TableRateRule
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_table_rate_rule_by_id(table_rate_rule_id, table_rate_rule, async=True)
>>>... |
def update_table_rate_rule_by_id(cls, table_rate_rule_id, table_rate_rule, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_table_rate_rule_by_id_with_http_info(table_rate_rule_id, table_rate_rule, **kwargs)
else:
(dat... | Update TableRateRule
Update attributes of TableRateRule
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_table_rate_rule_by_id(table_rate_rule_id, table_rate_rule, async=True)
>>> result... |
def _update_fobj(self):
# print("PPPPPPPPPPPPPPPPPPPRINTANDO O STACK")
# traceback.print_stack()
emsg, flag_error = "", False
fieldname = None
try:
self._before_update_fobj()
for item in self._map:
self... | Updates fobj from GUI. Opposite of _update_gui(). |
def colname_gen(df,col_name = 'unnamed_col'):
if col_name not in df.keys():
yield col_name
id_number = 0
while True:
col_name = col_name + str(id_number)
if col_name in df.keys():
id_number+=1
else:
return col_name | Returns a column name that isn't in the specified DataFrame
Parameters:
df - DataFrame
DataFrame to analyze
col_name - string, default 'unnamed_col'
Column name to use as the base value for the generated column name |
def clean_colnames(df):
col_list = []
for index in range(_dutils.cols(df)):
col_list.append(df.columns[index].strip().lower().replace(' ','_'))
df.columns = col_list | Cleans the column names on a DataFrame
Parameters:
df - DataFrame
The DataFrame to clean |
def col_strip(df,col_name,dest = False):
if dest:
df[col_name] = df[col_name].str.strip()
else:
return df[col_name].str.strip() | Performs str.strip() a column of a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to strip
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def col_scrubf(df,col_name,which,count = 1,dest = False):
if dest:
df.loc[which,col_name] = df.loc[which,col_name].str[count:]
else:
new_col = df[col_name].copy()
new_col[which] = df.loc[which,col_name].str[count:]
return new_col | Removes characters from the front of the entries in DataFrame for a column
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to scrub
which - boolean array
Boolean array that determines which elements to scrub, where True means scrub
count - ... |
def col_to_numeric(df,col_name, dest = False):
new_col = _pd.to_numeric(df[col_name], errors = 'coerce')
if dest:
set_col(df,col_name,new_col)
else:
return new_col | Coerces a column in a DataFrame to numeric
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def col_to_dt(df,col_name,set_format = None,infer_format = True, dest = False):
new_col = _pd.to_datetime(df[col_name],errors = 'coerce',
format = set_format,infer_datetime_format = infer_format)
if dest:
set_col(df,col_name,new_col)
else:
return new_... | Coerces a column in a DataFrame to datetime
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def col_to_cat(df,col_name, dest = False):
new_col = df[col_name].astype('category')
if dest:
set_col(df,col_name,new_col)
else:
return new_col | Coerces a column in a DataFrame to categorical
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def col_rename(df,col_name,new_col_name):
col_list = list(df.columns)
for index,value in enumerate(col_list):
if value == col_name:
col_list[index] = new_col_name
break
df.columns = col_list | Changes a column name in a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to change
new_col_name - string
New name of column |
def col_mod(df,col_name,func,*args,**kwargs):
backup = df[col_name].copy()
try:
return_val = func(df,col_name,*args,**kwargs)
if return_val is not None:
set_col(df,col_name,return_val)
except:
df[col_name] = backup | Changes a column of a DataFrame according to a given function
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to modify
func - function
The function to use to modify the column |
def cols_strip(df,col_list, dest = False):
if not dest:
return _pd.DataFrame({col_name:col_strip(df,col_name) for col_name in col_list})
for col_name in col_list:
col_strip(df,col_name,dest) | Performs str.strip() a column of a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to strip
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def cols_to_numeric(df, col_list,dest = False):
if not dest:
return _pd.DataFrame({col_name:col_to_numeric(df,col_name) for col_name in col_list})
for col_name in col_list:
col_to_numeric(df,col_name,dest) | Coerces a list of columns to numeric
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def cols_to_dt(df, col_list,set_format = None,infer_format = True,dest = False):
if not dest:
return _pd.DataFrame({col_name:col_to_dt(df,col_name,set_format,infer_format) for col_name in col_list})
for col_name in col_list:
col_to_dt(df,col_name,set_format,infer_format,dest) | Coerces a list of columns to datetime
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def cols_to_cat(df, col_list,dest = False):
# Convert a list of columns to categorical
if not dest:
return _pd.DataFrame({col_name:col_to_cat(df,col_name) for col_name in col_list})
for col_name in col_list:
col_to_cat(df,col_name,dest) | Coerces a list of columns to categorical
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def cols_(df,col_list,func,*args,**kwargs):
return _pd.DataFrame({col_name:func(df,col_name,*args,**kwargs) for col_name in col_list}) | Do a function over a list of columns and return the result
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to coerce
func - function
function to use |
def cols_rename(df,col_names, new_col_names):
assert len(col_names) == len(new_col_names)
for old_name,new_name in zip(col_names,new_col_names):
col_rename(df,old_name,new_name) | Rename a set of columns in a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_names - list of strings
names of columns to change
new_col_names - list of strings
new names for old columns (order should be same as col_names) |
def col_dtypes(df): # Does some work to reduce possibility of errors and stuff
test_list = [col_isobj,col_isnum,col_isbool,col_isdt,col_iscat,col_istdelt,col_isdtz]
deque_list = [(deque(col_method(df)),name) \
for col_method,name in zip(test_list,_globals.__dtype_names) if len(col_method(... | Returns dictionary of datatypes in a DataFrame (uses string representation)
Parameters:
df - DataFrame
The DataFrame to return the object types of
Pandas datatypes are as follows:
object,number,bool,datetime,category,timedelta,datetimetz
This method uses queues and iterates over the col... |
def col_isobj(df, col_name = None):
col_list = df.select_dtypes(include = 'object').columns
if col_name is None:
return col_list
else:
return col_name in col_list | Returns a list of columns that are of type object. If col_name is specified, returns
whether the column in the DataFrame is of type 'object' instead.
Parameters:
df - DataFrame
DataFrame to check
col_name - string, default None
If specified, this function will True if df[col_name] is of... |
def col_isnum(df,col_name = None):
col_list = df.select_dtypes(include = 'number').columns
if col_name is None:
return col_list
else:
return col_name in col_list | Returns a list of columns that are of type 'number'. If col_name is specified, returns
whether the column in the DataFrame is of type 'number' instead.
Parameters:
df - DataFrame
DataFrame to check
col_name - string, default None
If specified, this function will True if df[col_name] is ... |
def col_isbool(df,col_name = None):
col_list = df.select_dtypes(include = 'bool').columns
if col_name is None:
return col_list
else:
return col_name in col_list | Returns a list of columns that are of type 'bool'. If col_name is specified, returns
whether the column in the DataFrame is of type 'bool' instead.
Parameters:
df - DataFrame
DataFrame to check
col_name - string, default None
If specified, this function will True if df[col_name] is of t... |
def col_isdt(df,col_name = None):
col_list = df.select_dtypes(include = 'datetime').columns
if col_name is None:
return col_list
else:
return col_name in col_list | Returns a list of columns that are of type 'datetime'. If col_name is specified, returns
whether the column in the DataFrame is of type 'datetime' instead.
Parameters:
df - DataFrame
DataFrame to check
col_name - string, default None
If specified, this function will True if df[col_name]... |
def col_iscat(df,col_name = None):
col_list = df.select_dtypes(include = 'category').columns
if col_name is None:
return col_list
else:
return col_name in col_list | Returns a list of columns that are of type 'category'. If col_name is specified, returns
whether the column in the DataFrame is of type 'category' instead.
Parameters:
df - DataFrame
DataFrame to check
col_name - string, default None
If specified, this function will True if df[col_name]... |
def col_istdelt(df,col_name = None):
col_list = df.select_dtypes(include = 'timedelta').columns
if col_name is None:
return col_list
else:
return col_name in col_list | Returns a list of columns that are of type 'timedelta'. If col_name is specified, returns
whether the column in the DataFrame is of type 'timedelta' instead.
Parameters:
df - DataFrame
DataFrame to check
col_name - string, default None
If specified, this function will True if df[col_nam... |
def col_isdtz(df,col_name = None):
col_list = df.select_dtypes(include = 'datetimetz').columns
if col_name is None:
return col_list
else:
return col_name in col_list | Returns a list of columns that are of type 'datetimetz'. If col_name is specified, returns
whether the column in the DataFrame is of type 'datetimetz' instead.
Parameters:
df - DataFrame
DataFrame to check
col_name - string, default None
If specified, this function will True if df[col_n... |
def set_query_on_table_metaclass(model: object, session: Session):
if not hasattr(model, "query"):
model.query = session.query(model) | Ensures that the given database model (`DeclarativeMeta`) has a `query` property through
which the user can easily query the corresponding database table.
Database object models derived from Flask-SQLAlchemy's `database.Model` have this property
set up by default, but when using SQLAlchemy,... |
def get_feature_model():
try:
return apps.get_model(flipper_settings.FEATURE_FLIPPER_MODEL)
except ValueError:
raise ImproperlyConfigured(
"FEATURE_FLIPPER_MODEL must be of the form 'app_label.model_name'")
except LookupError:
raise ImproperlyConfigured(
... | Return the FeatureFlipper model defined in settings.py |
def show_feature(self, user, feature):
user_filter = {
self.model.USER_FEATURE_FIELD: user,
}
return self.get_feature(feature).filter(
models.Q(**user_filter) | models.Q(everyone=True)).exists() | Return True or False for the given feature. |
def solve_loop(slsp, u_span, j_coup):
zet, lam, eps, hlog, mean_f = [], [], [], [], [None]
for u in u_span:
print(u, j_coup)
hlog.append(slsp.selfconsistency(u, j_coup, mean_f[-1]))
mean_f.append(slsp.mean_field())
zet.append(slsp.quasiparticle_weight())
lam.append... | Calculates the quasiparticle for the input loop of:
@param slsp: Slave spin Object
@param Uspan: local Couloumb interation
@param J_coup: Fraction of Uspan of Hund coupling strength |
def calc_z(bands, filling, interaction, hund_cu, name):
while True:
try:
data = np.load(name+'.npz')
break
except IOError:
dopout = []
for dop in filling:
slsp = Spinon(slaves=2*bands, orbitals=bands, \
... | Calculates the quasiparticle weight of degenerate system of N-bands
at a given filling within an interaction range and saves the file |
def label_saves(name):
plt.legend(loc=0)
plt.ylim([0, 1.025])
plt.xlabel('$U/D$', fontsize=20)
plt.ylabel('$Z$', fontsize=20)
plt.savefig(name, dpi=300, format='png',
transparent=False, bbox_inches='tight', pad_inches=0.05) | Labels plots and saves file |
def plot_curves_z(data, name, title=None):
plt.figure()
for zet, c in zip(data['zeta'], data['doping']):
plt.plot(data['u_int'], zet[:, 0], label='$n={}$'.format(str(c)))
if title != None:
plt.title(title)
label_saves(name+'.png') | Generates a simple plot of the quasiparticle weight decay curves given
data object with doping setup |
def pick_flat_z(data):
zmes = []
for i in data['zeta']:
zmes.append(i[:, 0])
return np.asarray(zmes) | Generate a 2D array of the quasiparticle weight by only selecting the
first particle data |
def imshow_z(data, name):
zmes = pick_flat_z(data)
plt.figure()
plt.imshow(zmes.T, origin='lower', \
extent=[data['doping'].min(), data['doping'].max(), \
0, data['u_int'].max()], aspect=.16)
plt.colorbar()
plt.xlabel('$n$', fontsize=20)
plt.ylabel('$U/D$', fontsiz... | 2D color plot of the quasiparticle weight as a function of interaction
and doping |
def surf_z(data, name):
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
fig = plt.figure()
ax = fig.gca(projection='3d')
dop, u_int = np.meshgrid(data['doping'], data['u_int'])
zmes = pick_flat_z(data)
... | Surface plot of the quasiparticle weight as fuction of U/D and dop |
def plot_mean_field_conv(N=1, n=0.5, Uspan=np.arange(0, 3.6, 0.5)):
sl = Spinon(slaves=2*N, orbitals=N, avg_particles=2*n,
hopping=[0.5]*2*N, orbital_e=[0]*2*N)
hlog = solve_loop(sl, Uspan, [0.])[1]
f, (ax1, ax2) = plt.subplots(2, sharex=True)
for field in hlog:
fie... | Generates the plot on the convergenge of the mean field in single
site spin hamiltonian under with N degenerate half-filled orbitals |
def assign(self, value, termenc):
if self._termenc != termenc:
self._decoder = codecs.getincrementaldecoder(termenc)(errors='replace')
self._termenc = termenc
self._data = self._decoder.decode(value) | >>> scanner = DefaultScanner()
>>> scanner.assign("01234", "ascii")
>>> scanner._data
u'01234' |
def dtypes_summary(df):
output_df = pd.DataFrame([])
row_count = df.shape[0]
row_indexes = ['rows_numerical','rows_string','rows_date_time','category_count','largest_category','rows_na','rows_total']
for colname in df:
data = df[colname] # data is the pandas series associated with this colu... | Takes in a dataframe and returns a dataframe with
information on the data-types present in each column.
Parameters:
df - DataFrame
Dataframe to summarize |
def df_outliers(df,sensitivity = 1.5):
outlier_df = df.copy()
dtypes = _basics.col_dtypes(df)
for col_name in df.columns:
outlier_df.loc[~outliers(df[col_name],'bool',dtypes[col_name],sensitivity),col_name] = np.nan
outlier_df = outlier_df.dropna(how = 'all')
return outlier_df | Finds outliers in the dataframe.
Parameters:
df - DataFrame
The DataFrame to analyze.
sensitivity - number, default 1.5
The value to multipy by the iter-quartile range when determining outliers. This number is used
for categorical data as well. |
def outliers(df,output_type = 'values',dtype = 'number',sensitivity = 1.5):# can output boolean array or values
if dtype in ('number','datetime','timedelt','datetimetz'):
if not dtype == 'number':
df = pd.to_numeric(df,errors = 'coerce')
quart25, quart75 = percentiles(df,q = [.25,.7... | Returns potential outliers as either a boolean array or a subset of the original.
Parameters:
df - array_like
Series or dataframe to check
output_type - string, default 'values'
if 'values' is specified, then will output the values in the series that are suspected
outliers. Else, a b... |
def cum_percentile(series,q):
total = series.sum()
cum_sum = series.cumsum()
return sum(cum_sum < total*q) | Takes a series of ordered frequencies and returns the value at a specified quantile
Parameters:
series - Series
The series to analyze
q - number
Quantile to get the value of |
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
... | Returns the model properties as a dict |
def list_all_payments(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_payments_with_http_info(**kwargs)
else:
(data) = cls._list_all_payments_with_http_info(**kwargs)
return data | List Payments
Return a list of Payments
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_payments(async=True)
>>> result = thread.get()
:param async bool
:param int pa... |
def from_config(cls):
config = Config()
client = cls(
email=config.get('email'),
api_key=config.get('api_key'),
server=config.get('api_server'),
http_proxy=config.get('http_proxy'),
https_proxy=config.get('https_proxy'),
)
... | Method to return back a loaded instance. |
def set_debug(self, status):
if status:
self.logger.setLevel('DEBUG')
else:
self.logger.setLevel('INFO') | Control the logging state. |
def _endpoint(self, endpoint, action, *url_args):
args = (self.api_base, endpoint, action)
if action == '':
args = (self.api_base, endpoint)
api_url = "/".join(args)
if url_args:
if len(url_args) == 1:
api_url += "/" + url_args[0]
... | Return the URL for the action.
:param str endpoint: The controller
:param str action: The action provided by the controller
:param url_args: Additional endpoints(for endpoints that take part of
the url as option)
:return: Full URL for the requested action |
def _json(self, response):
if response.status_code == 204:
return None
try:
return response.json()
except ValueError as e:
raise ValueError(
'Exception: %s\n'
'request: %s, response code: %s, response: %s' % (
... | JSON response from server.
:param response: Response from the server
:throws ValueError: from requests' response.json() error
:return: response deserialized from JSON |
def _get(self, endpoint, action, *url_args, **url_params):
api_url = self._endpoint(endpoint, action, *url_args)
kwargs = {'headers': self.headers, 'params': url_params,
'timeout': Client.TIMEOUT, 'verify': self.verify}
if self.proxies:
kwargs['proxies'] = ... | Request API Endpoint - for GET methods.
:param str endpoint: Endpoint
:param str action: Endpoint Action
:param url_args: Additional endpoints(for endpoints that take part of
the url as option)
:param url_params: Parameters to pass to url, typically query string... |
def _send_data(self, method, endpoint, action,
data, *url_args, **url_params):
api_url = self._endpoint(endpoint, action, *url_args)
data.update({'email': self.email, 'api_key': self.api_key})
data = json.dumps(data)
kwargs = {'headers': self.headers, 'params'... | Submit to API Endpoint - for DELETE, PUT, POST methods.
:param str method: Method to use for the request
:param str endpoint: Endpoint
:param str action: Endpoint Action
:param url_args: Additional endpoints(for endpoints that take part of
the url as option)
... |
def create_free_item_coupon(cls, free_item_coupon, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_free_item_coupon_with_http_info(free_item_coupon, **kwargs)
else:
(data) = cls._create_free_item_coupon_with_http_info... | Create FreeItemCoupon
Create a new FreeItemCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_free_item_coupon(free_item_coupon, async=True)
>>> result = thread.get()
:para... |
def delete_free_item_coupon_by_id(cls, free_item_coupon_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_free_item_coupon_by_id_with_http_info(free_item_coupon_id, **kwargs)
else:
(data) = cls._delete_free_item_cou... | Delete FreeItemCoupon
Delete an instance of FreeItemCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_free_item_coupon_by_id(free_item_coupon_id, async=True)
>>> result ... |
def get_free_item_coupon_by_id(cls, free_item_coupon_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_free_item_coupon_by_id_with_http_info(free_item_coupon_id, **kwargs)
else:
(data) = cls._get_free_item_coupon_by_id... | Find FreeItemCoupon
Return single instance of FreeItemCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_free_item_coupon_by_id(free_item_coupon_id, async=True)
>>> result =... |
def list_all_free_item_coupons(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_free_item_coupons_with_http_info(**kwargs)
else:
(data) = cls._list_all_free_item_coupons_with_http_info(**kwargs)
retu... | List FreeItemCoupons
Return a list of FreeItemCoupons
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_free_item_coupons(async=True)
>>> result = thread.get()
:param async boo... |
def replace_free_item_coupon_by_id(cls, free_item_coupon_id, free_item_coupon, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_free_item_coupon_by_id_with_http_info(free_item_coupon_id, free_item_coupon, **kwargs)
else:
... | Replace FreeItemCoupon
Replace all attributes of FreeItemCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_free_item_coupon_by_id(free_item_coupon_id, free_item_coupon, async=True)
... |
def update_free_item_coupon_by_id(cls, free_item_coupon_id, free_item_coupon, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_free_item_coupon_by_id_with_http_info(free_item_coupon_id, free_item_coupon, **kwargs)
else:
... | Update FreeItemCoupon
Update attributes of FreeItemCoupon
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_free_item_coupon_by_id(free_item_coupon_id, free_item_coupon, async=True)
>>> r... |
def process_events(events, source_ip):
s3 = boto3.resource('s3')
table = boto3.resource("dynamodb").Table(os.environ['database'])
with table.batch_writer() as batch:
for idx, event in enumerate(events):
event = convert_keys_to_string(event)
event['sourceIp'] = source_ip
... | Process all the events for logging and S3. |
def lambda_handler(event, context):
body = event.get('body', dict())
events = body.get('events', list())
source_ip = str(event.get('source_ip', ''))
if len(events) == 0:
return {'success': False, 'message': "No events sent in"}
status = process_events(events, source_ip)
msg = "Wrote... | Run the script. |
def cost_type(self, cost_type):
allowed_values = ["orderSubtotal", "weight"]
if cost_type is not None and cost_type not in allowed_values:
raise ValueError(
"Invalid value for `cost_type` ({0}), must be one of {1}"
.format(cost_type, allowed_values)
... | Sets the cost_type of this TableRateShipping.
:param cost_type: The cost_type of this TableRateShipping.
:type: str |
def create_table_rate_shipping(cls, table_rate_shipping, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_table_rate_shipping_with_http_info(table_rate_shipping, **kwargs)
else:
(data) = cls._create_table_rate_shipping... | Create TableRateShipping
Create a new TableRateShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_table_rate_shipping(table_rate_shipping, async=True)
>>> result = thread.get()
... |
def delete_table_rate_shipping_by_id(cls, table_rate_shipping_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, **kwargs)
else:
(data) = cls._delete_t... | Delete TableRateShipping
Delete an instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_table_rate_shipping_by_id(table_rate_shipping_id, async=True)
... |
def get_table_rate_shipping_by_id(cls, table_rate_shipping_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, **kwargs)
else:
(data) = cls._get_table_rate... | Find TableRateShipping
Return single instance of TableRateShipping by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_table_rate_shipping_by_id(table_rate_shipping_id, async=True)
... |
def list_all_table_rate_shippings(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_table_rate_shippings_with_http_info(**kwargs)
else:
(data) = cls._list_all_table_rate_shippings_with_http_info(**kwargs)
... | List TableRateShippings
Return a list of TableRateShippings
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_table_rate_shippings(async=True)
>>> result = thread.get()
:param ... |
def replace_table_rate_shipping_by_id(cls, table_rate_shipping_id, table_rate_shipping, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, table_rate_shipping, **kwargs)
... | Replace TableRateShipping
Replace all attributes of TableRateShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_table_rate_shipping_by_id(table_rate_shipping_id, table_rate_shipping, asy... |
def update_table_rate_shipping_by_id(cls, table_rate_shipping_id, table_rate_shipping, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_table_rate_shipping_by_id_with_http_info(table_rate_shipping_id, table_rate_shipping, **kwargs)
... | Update TableRateShipping
Update attributes of TableRateShipping
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_table_rate_shipping_by_id(table_rate_shipping_id, table_rate_shipping, async=True... |
def next_formatted_pair(self):
key = self.key_gen.next()
token = self.token_gen.create_token(key)
fkey = self.formatter.format_key(key)
ftoken = self.formatter.format_token(token)
return FormattedPair(key, token, fkey, ftoken) | \
Returns a :class:`FormattedPair <shorten.store.FormattedPair>` containing
attributes `key`, `token`, `formatted_key` and `formatted_token`.
Calling this method will always consume a key and token. |
def get_source(path):
''' yields all non-empty lines in a file '''
for line in read(path):
if 'import' in line or len(line.strip()) == 0 or line.startswith('#'):
continue
if '__name__' in line and '__main__' in line:
break
else:
yield linf get_source(p... | yields all non-empty lines in a file |
def create_option_value(cls, option_value, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._create_option_value_with_http_info(option_value, **kwargs)
else:
(data) = cls._create_option_value_with_http_info(option_value, **kwa... | Create OptionValue
Create a new OptionValue
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_option_value(option_value, async=True)
>>> result = thread.get()
:param async bool
... |
def delete_option_value_by_id(cls, option_value_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._delete_option_value_by_id_with_http_info(option_value_id, **kwargs)
else:
(data) = cls._delete_option_value_by_id_with_http_... | Delete OptionValue
Delete an instance of OptionValue by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_option_value_by_id(option_value_id, async=True)
>>> result = thread.get()... |
def get_option_value_by_id(cls, option_value_id, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._get_option_value_by_id_with_http_info(option_value_id, **kwargs)
else:
(data) = cls._get_option_value_by_id_with_http_info(opti... | Find OptionValue
Return single instance of OptionValue by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_option_value_by_id(option_value_id, async=True)
>>> result = thread.get()
... |
def list_all_option_values(cls, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._list_all_option_values_with_http_info(**kwargs)
else:
(data) = cls._list_all_option_values_with_http_info(**kwargs)
return data | List OptionValues
Return a list of OptionValues
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_option_values(async=True)
>>> result = thread.get()
:param async bool
... |
def replace_option_value_by_id(cls, option_value_id, option_value, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_option_value_by_id_with_http_info(option_value_id, option_value, **kwargs)
else:
(data) = cls._replac... | Replace OptionValue
Replace all attributes of OptionValue
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_option_value_by_id(option_value_id, option_value, async=True)
>>> result = thr... |
def update_option_value_by_id(cls, option_value_id, option_value, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._update_option_value_by_id_with_http_info(option_value_id, option_value, **kwargs)
else:
(data) = cls._update_o... | Update OptionValue
Update attributes of OptionValue
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_option_value_by_id(option_value_id, option_value, async=True)
>>> result = thread.get... |
def bool_set(operation,*sets):
'''combine ``sets`` with ``operation``
:and: combine sets with AND
:or: combine sets with OR
:not: NOT sets versus the last given set'''
if len(sets)<=1:
return sets
if operation=='and':
return and_sets(*sets)
if operatio... | combine ``sets`` with ``operation``
:and: combine sets with AND
:or: combine sets with OR
:not: NOT sets versus the last given set |
def datetime_to_ns(then):
if then == datetime(1970, 1, 1, 0, 0):
return 'Antiquity'
now = datetime.utcnow()
delta = now - then
seconds = delta.total_seconds()
# There's gotta be a better way to do this...
years, seconds = divmod(seconds, 60*60*24*365)
days, seconds = divm... | Transform a :any:`datetime.datetime` into a NationStates-style
string.
For example "6 days ago", "105 minutes ago", etc. |
def authenticate(self, request):
# todo: can we trust that request.user variable is even defined?
if request.user and request.user.is_authenticated():
return request.user
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()... | Authenticate request using HTTP Basic authentication protocl.
If the user is successfully identified, the corresponding user
object is stored in `request.user`. If the request has already
been authenticated (i.e. `request.user` has authenticated user
object), this function does nothing.... |
def clean():
os.chdir(os.path.join(project_root, 'docs'))
sh("make clean")
os.chdir(project_root)
sh("rm -rf pyoauth2.egg-info") | Clean up previous garbage |
def _is_unit(rule):
# type: (Type[Rule]) -> bool
return len(rule.left) == 1 and len(rule.right) == 1 and \
isclass(rule.fromSymbol) and isclass(rule.toSymbol) and \
issubclass(rule.fromSymbol, Nonterminal) and issubclass(rule.toSymbol, Nonterminal) | Check if parameter is unit rule.
:param rule: Object to check.
:return: True if is parameter unit rule, false otherwise. |
def _create_rule(rule, index, backtrack):
# type: (Rule, int, Dict[Type[Nonterminal], Type[Rule]]) -> Type[EpsilonRemovedRule]
# remove old rules from the dictionary
old_dict = rule.__dict__.copy()
if 'rules' in old_dict: del old_dict['rules']
if 'rule' in old_dict: del old_dict['rule']
if ... | Create EpsilonRemovedRule. This rule will skip symbol at the `index`.
:param rule: Original rule.
:param index: Index of symbol that is rewritable to epsilon.
:param backtrack: Dictionary where key is nonterminal and value is rule which is next to generate epsilon.
:return: EpsilonRemovedRule class with... |
def remove_rules_with_epsilon(grammar, inplace=False):
# type: (Grammar, bool) -> Grammar
# copy if required
if inplace is False:
grammar = copy(grammar)
# find nonterminals rewritable to epsilon
rewritable = find_nonterminals_rewritable_to_epsilon(grammar) # type: Dict[Type[Nontermina... | Remove epsilon rules.
:param grammar: Grammar where rules remove
:param inplace: True if transformation should be performed in place, false otherwise.
False by default.
:return: Grammar without epsilon rules. |
def average():
count = 0
total = total()
i=0
while 1:
i = yield ((total.send(i)*1.0)/count if count else 0)
count += 1 | generator that holds a rolling average |
def args(self):
if self._args is None:
parser = self._build_parser()
self._args = parser.parse_args()
return self._args | Parsed command-line arguments. |
def build_pypackage_basename(self, pytree, base):
dirname = os.path.dirname(pytree)
parsed_package_name = base.replace(dirname, '').strip('/')
return parsed_package_name | Build the string representing the parsed package basename.
:param str pytree: The pytree absolute path.
:param str pytree: The absolute path of the pytree sub-package of which determine the
parsed name.
:rtype: str |
def _build_parser(self):
parser = argparse.ArgumentParser()
parser.add_argument('--pytree',
required=True,
type=self._valid_directory,
help='This is the path, absolute or relative, of the Python package '
... | Build the needed command-line parser. |
def build_pyfile_path_from_docname(self, docfile):
name, ext = os.path.splitext(docfile)
expected_py_name = name.replace('.', '/') + '.py'
return expected_py_name | Build the expected Python file name based on the given documentation file name.
:param str docfile: The documentation file name from which to build the Python file name.
:rtype: str |
def calculate_tree_differences(self, pytree, doctree):
pykeys = set(pytree.keys())
dockeys = set(doctree.keys())
# Calculate the missing documentation files, if any.
missing_doc_keys = pykeys - dockeys
missing_docs = {pytree[pyfile] for pyfile in missing_doc_keys}
... | Calculate the differences between the given trees.
:param dict pytree: The dictionary of the parsed Python tree.
:param dict doctree: The dictionary of the parsed documentation tree.
:rtype: tuple
:returns: A two-tuple of sets, where the first is the missing Python files, and the second... |
def compare_trees(self, parsed_pytree, parsed_doctree):
if parsed_pytree == parsed_doctree:
return 0
missing_pys, missing_docs = self.calculate_tree_differences(pytree=parsed_pytree,
doctree=parsed_doctree)
... | Compare the given parsed trees.
:param dict parsed_pytree: A dictionary representing the parsed Python tree where each
key is a parsed Python file and its key is its expected rst file name. |
def parse_doc_tree(self, doctree, pypackages):
parsed_doctree = {}
for filename in os.listdir(doctree):
if self._ignore_docfile(filename):
continue
expected_pyfile = self.build_pyfile_path_from_docname(filename)
parsed_doctree[expected_pyfile... | Parse the given documentation tree.
:param str doctree: The absolute path to the documentation tree which is to be parsed.
:param set pypackages: A set of all Python packages found in the pytree.
:rtype: dict
:returns: A dict where each key is the path of an expected Python module and i... |
def parse_py_tree(self, pytree):
parsed_pytree = {}
pypackages = set()
for base, dirs, files in os.walk(pytree):
if self._ignore_pydir(os.path.basename(base)):
continue
# TODO(Anthony): If this is being run against a Python 3 package, this needs ... | Parse the given Python package tree.
:param str pytree: The absolute path to the Python tree which is to be parsed.
:rtype: dict
:returns: A two-tuple. The first element is a dict where each key is the path of a parsed
Python module (relative to the Python tree) and its value is the... |
def pprint_tree_differences(self, missing_pys, missing_docs):
if missing_pys:
print('The following Python files appear to be missing:')
for pyfile in missing_pys:
print(pyfile)
print('\n')
if missing_docs:
print('The following doc... | Pprint the missing files of each given set.
:param set missing_pys: The set of missing Python files.
:param set missing_docs: The set of missing documentation files.
:rtype: None |
def _valid_directory(self, path):
abspath = os.path.abspath(path)
if not os.path.isdir(abspath):
raise argparse.ArgumentTypeError('Not a valid directory: {}'.format(abspath))
return abspath | Ensure that the given path is valid.
:param str path: A valid directory path.
:raises: :py:class:`argparse.ArgumentTypeError`
:returns: An absolute directory path. |
def main(self):
args = self.args
parsed_pytree, pypackages = self.parse_py_tree(pytree=args.pytree)
parsed_doctree = self.parse_doc_tree(doctree=args.doctree, pypackages=pypackages)
return self.compare_trees(parsed_pytree=parsed_pytree, parsed_doctree=parsed_doctree) | Parse package trees and report on any discrepancies. |
def initialize(self, grid, num_of_paths, seed):
for p in self.producers:
p.initialize(grid, num_of_paths, seed)
self.grid = grid
self.num_of_paths = num_of_paths
self.seed = seed | inits producer for a simulation run |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.