_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q23900
Context._pop_buffer_and_writer
train
def _pop_buffer_and_writer(self): """pop the most recent capturing buffer from this Context
python
{ "resource": "" }
q23901
LoopContext.cycle
train
def cycle(self, *values): """Cycle through values as the loop progresses. """ if not values:
python
{ "resource": "" }
q23902
Namespace.include_file
train
def include_file(self, uri, **kwargs): """Include a file at the given ``uri``."""
python
{ "resource": "" }
q23903
find_path
train
def find_path(dirs, path_to_find): """ Go through a bunch of dirs and see if dir+path_to_find exists there. Returns the first dir that matches. Otherwise, return None. """ for
python
{ "resource": "" }
q23904
to_bool
train
def to_bool(s): """ Convert string `s` into a boolean. `s` can be 'true', 'True', 1, 'false', 'False', 0. Examples: >>> to_bool("true") True >>> to_bool("0") False >>> to_bool(True) True """ if isinstance(s, bool):
python
{ "resource": "" }
q23905
Template.render
train
def render(self, *args, **data): """Render the output of this template as a string. If the template specifies an output encoding, the string will be encoded accordingly, else the output is raw (raw output uses `cStringIO` and can't handle multibyte characters). A :class:`.Contex...
python
{ "resource": "" }
q23906
Template.render_unicode
train
def render_unicode(self, *args, **data): """Render the output of this template as a unicode object.""" return runtime._render(self, self.callable_,
python
{ "resource": "" }
q23907
strip_exts
train
def strip_exts(s, exts): """ Given a string and an interable of extensions, strip the extenion off the string if the string ends with one of the extensions. """
python
{ "resource": "" }
q23908
Ansible._parse_hosts_inventory
train
def _parse_hosts_inventory(self, inventory_path): """ Read all the available hosts inventory information into one big list and parse it. """ hosts_contents = [] if os.path.isdir(inventory_path): self.log.debug("Inventory path {} is a dir. Looking for inventory...
python
{ "resource": "" }
q23909
Ansible._parse_hostvar_dir
train
def _parse_hostvar_dir(self, inventory_path): """ Parse host_vars dir, if it exists. """ # inventory_path could point to a `hosts` file, or to a dir. So we # construct the location to the `host_vars` differently. if os.path.isdir(inventory_path): path = os.pat...
python
{ "resource": "" }
q23910
Ansible._parse_hostvar_file
train
def _parse_hostvar_file(self, hostname, path): """ Parse a host var file and apply it to host `hostname`. """ # Check for ansible-vault files, because they're valid yaml for # some reason... (psst, the reason is that yaml sucks) first_line = open(path, 'r').readline() ...
python
{ "resource": "" }
q23911
Ansible._parse_groupvar_dir
train
def _parse_groupvar_dir(self, inventory_path): """ Parse group_vars dir, if it exists. Encrypted vault files are skipped. """ # inventory_path could point to a `hosts` file, or to a dir. So we # construct the location to the `group_vars` differently. if os.path.isdir(inve...
python
{ "resource": "" }
q23912
Ansible._parse_dyn_inventory
train
def _parse_dyn_inventory(self, script): """ Execute a dynamic inventory script and parse the results. """ self.log.debug("Reading dynamic inventory {0}".format(script)) try: proc = subprocess.Popen([script, '--list'], stdout=subproc...
python
{ "resource": "" }
q23913
Ansible.update_host
train
def update_host(self, hostname, key_values, overwrite=True): """ Update a hosts information. This is called by various collectors such as the ansible setup module output and the hosts parser to add informatio to a host. It does some deep
python
{ "resource": "" }
q23914
Ansible.hosts_in_group
train
def hosts_in_group(self, groupname): """ Return a list of hostnames that are in a group. """ result = [] for hostname, hostinfo in self.hosts.items():
python
{ "resource": "" }
q23915
Ansible.get_hosts
train
def get_hosts(self): """ Return a list of parsed hosts info, with the limit applied if required. """ limited_hosts = {} if self.limit is not None: # Find hosts and groups of hosts to include for include in self.limit['include']: # Include w...
python
{ "resource": "" }
q23916
get_logger
train
def get_logger(): """ Instantiate a logger. """ root = logging.getLogger() root.setLevel(logging.WARNING)
python
{ "resource": "" }
q23917
get_data_dir
train
def get_data_dir(): """ Find out our installation prefix and data directory. These can be in different places depending on how ansible-cmdb was installed. """ data_dir_paths = [ os.path.join(os.path.dirname(ansiblecmdb.__file__), 'data'), os.path.join(os.path.dirname(sys.argv[0]), '....
python
{ "resource": "" }
q23918
get_hosts_files
train
def get_hosts_files(option): """ Find out the location of the `hosts` file. This looks in multiple places such as the `-i` option, current dir and ansible configuration files. The first match is returned as a list. """ if option is not None: return option.split(',') # Use hosts file...
python
{ "resource": "" }
q23919
get_cust_cols
train
def get_cust_cols(path): """ Load custom column definitions. """ required_keys = ["title", "id", "sType", "visible"] with open(path, 'r') as f: try: cust_cols = ast.literal_eval(f.read()) except Exception as err: sys.stderr.write("Invalid custom columns file:...
python
{ "resource": "" }
q23920
Render._tpl_possibilities
train
def _tpl_possibilities(self): """ Construct a list of possible paths to templates. """ tpl_possibilities = [ os.path.realpath(self.tpl) ] for tpl_dir in self.tpl_dirs:
python
{ "resource": "" }
q23921
Render._find_tpl
train
def _find_tpl(self): """ Find a template in the list of possible paths. """ for tpl_possibility in self.tpl_possibilities:
python
{ "resource": "" }
q23922
Render.render
train
def render(self, hosts, vars={}): """ Render a mako or .py file. """ if self.tpl_file.endswith(".tpl"): return self._render_mako(hosts, vars) elif self.tpl_file.endswith(".py"):
python
{ "resource": "" }
q23923
shlex.sourcehook
train
def sourcehook(self, newfile, encoding='utf-8'): "Hook called on a filename to be sourced." from codecs import open if newfile[0] == '"': newfile = newfile[1:-1] # This implements cpp-like semantics for relative-path inclusion.
python
{ "resource": "" }
q23924
TGPlugin.load_template
train
def load_template(self, templatename, template_string=None): """Loads a template from a file or a string""" if template_string is not None: return Template(template_string, **self.tmpl_options) # Translate TG dot notation to normal / template path if '/' not in templatename: ...
python
{ "resource": "" }
q23925
FunctionDecl.get_argument_expressions
train
def get_argument_expressions(self, as_call=False): """Return the argument declarations of this FunctionDecl as a printable list. By default the return value is appropriate for writing in a ``def``; set `as_call` to true to build arguments to be passed to the function instead (as...
python
{ "resource": "" }
q23926
legacy_html_escape
train
def legacy_html_escape(s): """legacy HTML escape for non-unicode mode.""" s = s.replace("&", "&amp;") s = s.replace(">", "&gt;") s = s.replace("<", "&lt;")
python
{ "resource": "" }
q23927
htmlentityreplace_errors
train
def htmlentityreplace_errors(ex): """An encoding error handler. This python `codecs`_ error handler replaces unencodable characters with HTML entities, or, if no HTML entity exists for the character, XML character references. >>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace') ...
python
{ "resource": "" }
q23928
XMLEntityEscaper.escape
train
def escape(self, text): """Replace characters with their character references. Replace characters by their named entity references. Non-ASCII characters, if they do not have a named entity reference, are replaced by numerical character references. The return value is guaranteed...
python
{ "resource": "" }
q23929
MessageExtractor._split_comment
train
def _split_comment(lineno, comment): """Return the multiline comment at lineno split into a list of comment line numbers and the accompanying comment line"""
python
{ "resource": "" }
q23930
adjust_whitespace
train
def adjust_whitespace(text): """remove the left-whitespace margin of a block of Python code.""" state = [False, False] (backslashed, triplequoted) = (0, 1) def in_multi_line(line): start_state = (state[backslashed] or state[triplequoted]) if re.search(r"\\$", line): state[...
python
{ "resource": "" }
q23931
PythonPrinter.write_indented_block
train
def write_indented_block(self, block): """print a line or lines of python which already contain indentation. The indentation of the total block of lines
python
{ "resource": "" }
q23932
PythonPrinter.writeline
train
def writeline(self, line): """print a line of python, indenting it according to the current indent level. this also adjusts the indentation counter according to the content of the line. """ if not self.in_indent_lines: self._flush_adjusted_lines() ...
python
{ "resource": "" }
q23933
PythonPrinter._is_unindentor
train
def _is_unindentor(self, line): """return true if the given line is an 'unindentor', relative to the last 'indent' event received. """ # no indentation detail has been pushed on; return False if len(self.indent_detail) == 0: return False indentor = self.ind...
python
{ "resource": "" }
q23934
PythonPrinter._indent_line
train
def _indent_line(self, line, stripspace=''): """indent the given line according to the current indent level. stripspace is a string of space that will be truncated from the
python
{ "resource": "" }
q23935
PythonPrinter._in_multi_line
train
def _in_multi_line(self, line): """return true if the given line is part of a multi-line block, via backslash or triple-quote.""" # we are only looking for explicitly joined lines here, not # implicit ones (i.e. brackets, braces etc.). this is just to # guard against the possib...
python
{ "resource": "" }
q23936
html_error_template
train
def html_error_template(): """Provides a template that renders a stack trace in an HTML format, providing an excerpt of code as well as substituting source template filenames, line numbers and code for that of the originating source template, as applicable. The template's default ``encoding_errors`...
python
{ "resource": "" }
q23937
RichTraceback._init_message
train
def _init_message(self): """Find a unicode representation of self.error""" try: self.message = compat.text_type(self.error) except UnicodeError: try: self.message = str(self.error)
python
{ "resource": "" }
q23938
TemplateLookup.adjust_uri
train
def adjust_uri(self, uri, relativeto): """Adjust the given ``uri`` based on the given relative URI.""" key = (uri, relativeto) if key in self._uri_cache: return self._uri_cache[key] if uri[0] != '/': if relativeto is not None: v = self._uri_cache...
python
{ "resource": "" }
q23939
TemplateLookup._relativeize
train
def _relativeize(self, filename): """Return the portion of a filename that is 'relative' to the directories in this lookup. """ filename = posixpath.normpath(filename) for dir in self.directories:
python
{ "resource": "" }
q23940
GitHubAssetManager._get_style_urls
train
def _get_style_urls(self, asset_url_path): """ Gets the specified resource and parses all style URLs and their assets in the form of the specified patterns. """ # Check cache if self.cache_path: cached = self._get_cached_style_urls(asset_url_path) ...
python
{ "resource": "" }
q23941
GitHubAssetManager._get_cached_style_urls
train
def _get_cached_style_urls(self, asset_url_path): """ Gets the URLs of the cached styles. """ try: cached_styles = os.listdir(self.cache_path) except IOError as ex:
python
{ "resource": "" }
q23942
GitHubAssetManager._cache_contents
train
def _cache_contents(self, style_urls, asset_url_path): """ Fetches the given URLs and caches their contents and their assets in the given directory. """ files = {} asset_urls = [] for style_url in style_urls: if not self.quiet: print('...
python
{ "resource": "" }
q23943
GitHubAssetManager.retrieve_styles
train
def retrieve_styles(self, asset_url_path): """ Get style URLs from the source HTML page and specified cached asset base URL. """ if not asset_url_path.endswith('/'):
python
{ "resource": "" }
q23944
is_server_running
train
def is_server_running(host, port): """ Checks whether a server is currently listening on the specified host and port. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
python
{ "resource": "" }
q23945
wait_for_server
train
def wait_for_server(host, port, cancel_event=None): """ Blocks until a local server is listening on the specified host and port. Set cancel_event to cancel the wait. This is intended to be used in conjunction with running the Flask server. """ while not is_server_running(host, port):
python
{ "resource": "" }
q23946
wait_and_start_browser
train
def wait_and_start_browser(host, port=None, cancel_event=None): """ Waits for the server to run and then opens the specified address in the browser. Set cancel_event to cancel the wait. """ if host == '0.0.0.0': host = 'localhost' if port is
python
{ "resource": "" }
q23947
start_browser_when_ready
train
def start_browser_when_ready(host, port=None, cancel_event=None): """ Starts a thread that waits for the server then opens the specified address in the browser. Set cancel_event to cancel
python
{ "resource": "" }
q23948
Grip._render_asset
train
def _render_asset(self, subpath): """ Renders the specified cache file. """ return
python
{ "resource": "" }
q23949
Grip._render_rate_limit_page
train
def _render_rate_limit_page(self, exception=None): """ Renders the rate limit page. """ auth = request.args.get('auth') is_auth =
python
{ "resource": "" }
q23950
Grip._get_styles
train
def _get_styles(self, style_urls, asset_url_path): """ Gets the content of the given list of style URLs and inlines assets. """ styles = [] for style_url in style_urls: urls_inline = STYLE_ASSET_URLS_INLINE_FORMAT.format( asset_url_path.rstrip(...
python
{ "resource": "" }
q23951
Grip._inline_styles
train
def _inline_styles(self): """ Downloads the assets from the style URL list, clears it, and adds each style with its embedded asset to the literal style list. """
python
{ "resource": "" }
q23952
Grip._retrieve_styles
train
def _retrieve_styles(self): """ Retrieves the style URLs from the source and caches them. This is called before the first request is dispatched. """ if self._styles_retrieved: return self._styles_retrieved = True
python
{ "resource": "" }
q23953
Grip.default_asset_manager
train
def default_asset_manager(self): """ Returns the default asset manager using the current config. This is only used if asset_manager is set to None in the constructor. """ cache_path = None cache_directory = self.config['CACHE_DIRECTORY'] if cache_directory: ...
python
{ "resource": "" }
q23954
Grip.render
train
def render(self, route=None): """ Renders the application and returns the HTML unicode that would normally appear when visiting in the browser. """ if route is None: route = '/'
python
{ "resource": "" }
q23955
Grip.run
train
def run(self, host=None, port=None, debug=None, use_reloader=None, open_browser=False): """ Starts a server to render the README. """ if host is None: host = self.config['HOST'] if port is None: port = self.config['PORT'] if debug is No...
python
{ "resource": "" }
q23956
create_app
train
def create_app(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=False, api_url=None, title=None, text=None, autorefresh=None, quiet=None, grip_class=None): """ Creates a Grip application...
python
{ "resource": "" }
q23957
render_page
train
def render_page(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=False, api_url=None, title=None, text=None, quiet=None, grip_class=None): """ Renders the specified ma...
python
{ "resource": "" }
q23958
render_content
train
def render_content(text, user_content=False, context=None, username=None, password=None, render_offline=False, api_url=None): """ Renders the specified markup and returns the result. """ renderer = (GitHubRenderer(user_content, context, api_url) if not render_offline e...
python
{ "resource": "" }
q23959
export
train
def export(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=True, out_filename=None, api_url=None, title=None, quiet=False, grip_class=None): """ Exports the rendered HTML to a file. """ exp...
python
{ "resource": "" }
q23960
patch
train
def patch(html, user_content=False): """ Processes the HTML rendered by the GitHub API, patching any inconsistencies from the main site. """ # FUTURE: Remove this once GitHub API renders task lists # https://github.com/isaacs/github/issues/309
python
{ "resource": "" }
q23961
DirectoryReader._find_file
train
def _find_file(self, path, silent=False): """ Gets the full path and extension, or None if a README file could not be found at the specified path. """ for filename in DEFAULT_FILENAMES: full_path = os.path.join(path, filename) if path else filename if os.p...
python
{ "resource": "" }
q23962
DirectoryReader._resolve_readme
train
def _resolve_readme(self, path=None, silent=False): """ Returns the path if it's a file; otherwise, looks for a compatible README file in the directory specified by path. If path is None, the current working directory is used. If silent is set, the default relative filename wil...
python
{ "resource": "" }
q23963
DirectoryReader._read_text
train
def _read_text(self, filename): """ Helper that reads the UTF-8 content of the specified file, or None if the file doesn't exist. This returns a unicode string.
python
{ "resource": "" }
q23964
DirectoryReader.normalize_subpath
train
def normalize_subpath(self, subpath): """ Normalizes the specified subpath, or None if subpath is None. This allows Readme files to be inferred from directories while still allowing relative paths to work properly. Raises werkzeug.exceptions.NotFound if the resulting path ...
python
{ "resource": "" }
q23965
DirectoryReader.readme_for
train
def readme_for(self, subpath): """ Returns the full path for the README file for the specified subpath, or the root filename if subpath is None. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the r...
python
{ "resource": "" }
q23966
DirectoryReader.filename_for
train
def filename_for(self, subpath): """ Returns the relative filename for the specified subpath, or the root filename if subpath is None. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the root directory. """
python
{ "resource": "" }
q23967
DirectoryReader.is_binary
train
def is_binary(self, subpath=None): """ Gets whether the specified subpath is a supported binary file. """
python
{ "resource": "" }
q23968
DirectoryReader.last_updated
train
def last_updated(self, subpath=None): """ Returns the time of the last modification of the Readme or specified subpath, or None if the file does not exist. The return value is a number giving the number of seconds since the epoch (see the time module). Raises werkzeug.e...
python
{ "resource": "" }
q23969
DirectoryReader.read
train
def read(self, subpath=None): """ Returns the UTF-8 content of the specified subpath. subpath is expected to already have been normalized. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the result...
python
{ "resource": "" }
q23970
StdinReader.read
train
def read(self, subpath=None): """ Returns the UTF-8 Readme content. Raises ReadmeNotFoundError if subpath is specified since subpaths are not supported for text readers. """ # Lazily read STDIN
python
{ "resource": "" }
q23971
StdinReader.read_stdin
train
def read_stdin(self): """ Reads STDIN until the end of input and returns a unicode string. """ text = sys.stdin.read() # Decode the bytes returned from earlier Python STDIN
python
{ "resource": "" }
q23972
ParetoNBDFitter._fit
train
def _fit( self, minimizing_function_args, iterative_fitting, initial_params, params_size, disp, tol=1e-6, fit_method="Nelder-Mead", maxiter=2000, **kwargs ): """Fit function for fitters.""" ll = [] sols = [] ...
python
{ "resource": "" }
q23973
BaseFitter.save_model
train
def save_model(self, path, save_data=True, save_generate_data_method=True, values_to_save=None): """ Save model with dill package. Parameters ---------- path: str Path where to save model. save_data: bool, optional Whether to save data from fitter...
python
{ "resource": "" }
q23974
BaseFitter.load_model
train
def load_model(self, path): """ Load model with dill package. Parameters ---------- path: str From what path load model.
python
{ "resource": "" }
q23975
ModifiedBetaGeoFitter.conditional_expected_number_of_purchases_up_to_time
train
def conditional_expected_number_of_purchases_up_to_time(self, t, frequency, recency, T): """ Conditional expected number of repeat purchases up to time t. Calculate the expected number of repeat purchases up to time t for a randomly choose individual from the population, given they have...
python
{ "resource": "" }
q23976
BetaGeoFitter.conditional_probability_alive
train
def conditional_probability_alive(self, frequency, recency, T): """ Compute conditional probability alive. Compute the probability that a customer with history (frequency, recency, T) is currently alive. From http://www.brucehardie.com/notes/021/palive_for_BGNBD.pdf Pa...
python
{ "resource": "" }
q23977
BetaGeoFitter.probability_of_n_purchases_up_to_time
train
def probability_of_n_purchases_up_to_time(self, t, n): r""" Compute the probability of n purchases. .. math:: P( N(t) = n | \text{model} ) where N(t) is the number of repeat purchases a customer makes in t units of time. Parameters ---------- t: float...
python
{ "resource": "" }
q23978
calibration_and_holdout_data
train
def calibration_and_holdout_data( transactions, customer_id_col, datetime_col, calibration_period_end, observation_period_end=None, freq="D", datetime_format=None, monetary_value_col=None, ): """ Create a summary of each customer over a calibration and holdout period. This f...
python
{ "resource": "" }
q23979
_find_first_transactions
train
def _find_first_transactions( transactions, customer_id_col, datetime_col, monetary_value_col=None, datetime_format=None, observation_period_end=None, freq="D", ): """ Return dataframe with first transactions. This takes a DataFrame of transaction data of the form: custo...
python
{ "resource": "" }
q23980
summary_data_from_transaction_data
train
def summary_data_from_transaction_data( transactions, customer_id_col, datetime_col, monetary_value_col=None, datetime_format=None, observation_period_end=None, freq="D", freq_multiplier=1, ): """ Return summary data from transactions. This transforms a DataFrame of transact...
python
{ "resource": "" }
q23981
calculate_alive_path
train
def calculate_alive_path(model, transactions, datetime_col, t, freq="D"): """ Calculate alive path for plotting alive history of user. Parameters ---------- model: A fitted lifetimes model transactions: DataFrame a Pandas DataFrame containing the transactions history of the cust...
python
{ "resource": "" }
q23982
_check_inputs
train
def _check_inputs(frequency, recency=None, T=None, monetary_value=None): """ Check validity of inputs. Raises ValueError when checks failed. Parameters ---------- frequency: array_like the frequency vector of customers' purchases (denoted x in literature). recency: array_like, opti...
python
{ "resource": "" }
q23983
_customer_lifetime_value
train
def _customer_lifetime_value( transaction_prediction_model, frequency, recency, T, monetary_value, time=12, discount_rate=0.01, freq="D" ): """ Compute the average lifetime value for a group of one or more customers. This method computes the average lifetime value for a group of one or more customers. ...
python
{ "resource": "" }
q23984
expected_cumulative_transactions
train
def expected_cumulative_transactions( model, transactions, datetime_col, customer_id_col, t, datetime_format=None, freq="D", set_index_date=False, freq_multiplier=1, ): """ Get expected and actual repeated cumulative transactions. Parameters ---------- model: ...
python
{ "resource": "" }
q23985
_save_obj_without_attr
train
def _save_obj_without_attr(obj, attr_list, path, values_to_save=None): """ Save object with attributes from attr_list. Parameters ---------- obj: obj Object of class with __dict__ attribute. attr_list: list List with attributes to exclude from saving to dill object. If empty ...
python
{ "resource": "" }
q23986
BetaGeoBetaBinomFitter._loglikelihood
train
def _loglikelihood(params, x, tx, T): warnings.simplefilter(action="ignore", category=FutureWarning) """Log likelihood for optimizer.""" alpha, beta, gamma, delta = params betaln_ab = betaln(alpha, beta) betaln_gd = betaln(gamma, delta)
python
{ "resource": "" }
q23987
BetaGeoBetaBinomFitter.conditional_expected_number_of_purchases_up_to_time
train
def conditional_expected_number_of_purchases_up_to_time(self, m_periods_in_future, frequency, recency, n_periods): r""" Conditional expected purchases in future time period. The expected number of future transactions across the next m_periods_in_future transaction opportunities by ...
python
{ "resource": "" }
q23988
BetaGeoBetaBinomFitter.expected_number_of_transactions_in_first_n_periods
train
def expected_number_of_transactions_in_first_n_periods(self, n): r""" Return expected number of transactions in first n n_periods. Expected number of transactions occurring across first n transaction opportunities. Used by Fader and Hardie to assess in-sample fit. .. ma...
python
{ "resource": "" }
q23989
plot_period_transactions
train
def plot_period_transactions( model, max_frequency=7, title="Frequency of Repeat Transactions", xlabel="Number of Calibration Period Transactions", ylabel="Customers", **kwargs ): """ Plot a figure with period actual and predicted transactions. Parameters ---------- model: l...
python
{ "resource": "" }
q23990
plot_calibration_purchases_vs_holdout_purchases
train
def plot_calibration_purchases_vs_holdout_purchases( model, calibration_holdout_matrix, kind="frequency_cal", n=7, **kwargs ): """ Plot calibration purchases vs holdout. This currently relies too much on the lifetimes.util calibration_and_holdout_data function. Parameters ---------- model:...
python
{ "resource": "" }
q23991
plot_frequency_recency_matrix
train
def plot_frequency_recency_matrix( model, T=1, max_frequency=None, max_recency=None, title=None, xlabel="Customer's Historical Frequency", ylabel="Customer's Recency", **kwargs ): """ Plot recency frequecy matrix as heatmap. Plot a figure of expected transactions in T next u...
python
{ "resource": "" }
q23992
plot_probability_alive_matrix
train
def plot_probability_alive_matrix( model, max_frequency=None, max_recency=None, title="Probability Customer is Alive,\nby Frequency and Recency of a Customer", xlabel="Customer's Historical Frequency", ylabel="Customer's Recency", **kwargs ): """ Plot probability alive matrix as heat...
python
{ "resource": "" }
q23993
plot_expected_repeat_purchases
train
def plot_expected_repeat_purchases( model, title="Expected Number of Repeat Purchases per Customer", xlabel="Time Since First Purchase", ax=None, label=None, **kwargs ): """ Plot expected repeat purchases on calibration period . Parameters ---------- model: lifetimes model ...
python
{ "resource": "" }
q23994
plot_history_alive
train
def plot_history_alive(model, t, transactions, datetime_col, freq="D", start_date=None, ax=None, **kwargs): """ Draw a graph showing the probability of being alive for a customer in time. Parameters ---------- model: lifetimes model A fitted lifetimes model. t: int the number of...
python
{ "resource": "" }
q23995
plot_incremental_transactions
train
def plot_incremental_transactions( model, transactions, datetime_col, customer_id_col, t, t_cal, datetime_format=None, freq="D", set_index_date=False, title="Tracking Daily Transactions", xlabel="day", ylabel="Transactions", ax=None, **kwargs ): """ Plot a...
python
{ "resource": "" }
q23996
plot_dropout_rate_heterogeneity
train
def plot_dropout_rate_heterogeneity( model, suptitle="Heterogeneity in Dropout Probability", xlabel="Dropout Probability p", ylabel="Density", suptitle_fontsize=14, **kwargs ): """ Plot the estimated gamma distribution of p. p - (customers' probability of dropping out immediately af...
python
{ "resource": "" }
q23997
load_cdnow_summary_data_with_monetary_value
train
def load_cdnow_summary_data_with_monetary_value(**kwargs): """Load cdnow customers summary with monetary value as pandas DataFrame.""" df = load_dataset("cdnow_customers_summary_with_transactions.csv", **kwargs)
python
{ "resource": "" }
q23998
GammaGammaFitter.conditional_expected_average_profit
train
def conditional_expected_average_profit(self, frequency=None, monetary_value=None): """ Conditional expectation of the average profit. This method computes the conditional expectation of the average profit per transaction for a group of one or more customers. Parameters ...
python
{ "resource": "" }
q23999
GammaGammaFitter.customer_lifetime_value
train
def customer_lifetime_value( self, transaction_prediction_model, frequency, recency, T, monetary_value, time=12, discount_rate=0.01, freq="D" ): """ Return customer lifetime value. This method computes the average lifetime value for a group of one or more customers. ...
python
{ "resource": "" }