_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q33100
UserManager__Views.change_password_view
train
def change_password_view(self): """ Prompt for old password and new password and change the user's password.""" # Initialize form form = self.ChangePasswordFormClass(request.form) # Process valid POST if request.method == 'POST' and form.validate(): # Hash password ...
python
{ "resource": "" }
q33101
UserManager__Views.change_username_view
train
def change_username_view(self): """ Prompt for new username and old password and change the user's username.""" # Initialize form form = self.ChangeUsernameFormClass(request.form) # Process valid POST if request.method == 'POST' and form.validate(): # Change userna...
python
{ "resource": "" }
q33102
UserManager__Views.confirm_email_view
train
def confirm_email_view(self, token): """ Verify email confirmation token and activate the user account.""" # Verify token data_items = self.token_manager.verify_token( token, self.USER_CONFIRM_EMAIL_EXPIRATION) # Retrieve user, user_email by ID user = Non...
python
{ "resource": "" }
q33103
UserManager__Views.email_action_view
train
def email_action_view(self, id, action): """ Perform action 'action' on UserEmail object 'id' """ # Retrieve UserEmail by id user_email = self.db_manager.get_user_email_by_id(id=id) # Users may only change their own UserEmails if not user_email or user_email.user_id != ...
python
{ "resource": "" }
q33104
UserManager__Views.forgot_password_view
train
def forgot_password_view(self): """Prompt for email and send reset password email.""" # Initialize form form = self.ForgotPasswordFormClass(request.form) # Process valid POST if request.method == 'POST' and form.validate(): # Get User and UserEmail by email ...
python
{ "resource": "" }
q33105
UserManager__Views.invite_user_view
train
def invite_user_view(self): """ Allows users to send invitations to register an account """ invite_user_form = self.InviteUserFormClass(request.form) if request.method == 'POST' and invite_user_form.validate(): # Find User and UserEmail by email email = invite_user_form...
python
{ "resource": "" }
q33106
UserManager__Views.login_view
train
def login_view(self): """Prepare and process the login form.""" # Authenticate username/email and login authenticated users. safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGIN_ENDPOINT) safe_reg_next = self._get_safe_next_url('reg_next', self.USER_AFTER_REGISTER_ENDP...
python
{ "resource": "" }
q33107
UserManager__Views.logout_view
train
def logout_view(self): """Process the logout link.""" """ Sign the user out.""" # Send user_logged_out signal signals.user_logged_out.send(current_app._get_current_object(), user=current_user) # Use Flask-Login to sign out user logout_user() # Flash a system me...
python
{ "resource": "" }
q33108
UserManager__Views.register_view
train
def register_view(self): """ Display registration form and create new User.""" safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGIN_ENDPOINT) safe_reg_next_url = self._get_safe_next_url('reg_next', self.USER_AFTER_REGISTER_ENDPOINT) # Initialize form login_form...
python
{ "resource": "" }
q33109
UserManager__Views.resend_email_confirmation_view
train
def resend_email_confirmation_view(self): """Prompt for email and re-send email conformation email.""" # Initialize form form = self.ResendEmailConfirmationFormClass(request.form) # Process valid POST if request.method == 'POST' and form.validate(): # Find user by ...
python
{ "resource": "" }
q33110
UserManager__Views.reset_password_view
train
def reset_password_view(self, token): """ Verify the password reset token, Prompt for new password, and set the user's password.""" # Verify token if self.call_or_get(current_user.is_authenticated): logout_user() data_items = self.token_manager.verify_token( tok...
python
{ "resource": "" }
q33111
UserManager__Views.unauthenticated_view
train
def unauthenticated_view(self): """ Prepare a Flash message and redirect to USER_UNAUTHENTICATED_ENDPOINT""" # Prepare Flash message url = request.url flash(_("You must be signed in to access '%(url)s'.", url=url), 'error') # Redirect to USER_UNAUTHENTICATED_ENDPOINT saf...
python
{ "resource": "" }
q33112
UserManager__Views.unauthorized_view
train
def unauthorized_view(self): """ Prepare a Flash message and redirect to USER_UNAUTHORIZED_ENDPOINT""" # Prepare Flash message url = request.script_root + request.path flash(_("You do not have permission to access '%(url)s'.", url=url), 'error') # Redirect to USER_UNAUTHORIZED_E...
python
{ "resource": "" }
q33113
_is_logged_in_with_confirmed_email
train
def _is_logged_in_with_confirmed_email(user_manager): """| Returns True if user is logged in and has a confirmed email address. | Returns False otherwise. """ # User must be logged in if user_manager.call_or_get(current_user.is_authenticated): # Is unconfirmed email allowed for this view by ...
python
{ "resource": "" }
q33114
login_required
train
def login_required(view_function): """ This decorator ensures that the current user is logged in. Example:: @route('/member_page') @login_required def member_page(): # User must be logged in ... If USER_ENABLE_EMAIL is True and USER_ENABLE_CONFIRM_EMAIL is True, t...
python
{ "resource": "" }
q33115
allow_unconfirmed_email
train
def allow_unconfirmed_email(view_function): """ This decorator ensures that the user is logged in, but allows users with or without a confirmed email addresses to access this particular view. It works in tandem with the ``USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL=True`` setting. .. caution:: ...
python
{ "resource": "" }
q33116
TokenManager.verify_token
train
def verify_token(self, token, expiration_in_seconds=None): """ Verify token signature, verify token expiration, and decrypt token. | Returns None if token is expired or invalid. | Returns a list of strings and integers on success. Implemented as:: concatenated_str = self.d...
python
{ "resource": "" }
q33117
TokenManager.encode_data_items
train
def encode_data_items(self, *args): """ Encodes a list of integers and strings into a concatenated string. - encode string items as-is. - encode integer items as base-64 with a ``'~'`` prefix. - concatenate encoded items with a ``'|'`` separator. Example: ``encode_d...
python
{ "resource": "" }
q33118
TokenManager.decode_data_items
train
def decode_data_items(self, concatenated_str): """Decodes a concatenated string into a list of integers and strings. Example: ``decode_data_items('abc|~B7|xyz')`` returns ``['abc', 123, 'xyz']`` """ data_items = [] str_list = concatenated_str.split(self.SEPARATOR) ...
python
{ "resource": "" }
q33119
TokenManager.encode_int
train
def encode_int(self, n): """ Encodes an integer into a short Base64 string. Example: ``encode_int(123)`` returns ``'B7'``. """ str = [] while True: n, r = divmod(n, self.BASE) str.append(self.ALPHABET[r]) if n == 0: break r...
python
{ "resource": "" }
q33120
TokenManager.decode_int
train
def decode_int(self, str): """ Decodes a short Base64 string into an integer. Example: ``decode_int('B7')`` returns ``123``. """ n = 0 for c in str: n = n * self.BASE + self.ALPHABET_REVERSE[c] return n
python
{ "resource": "" }
q33121
EmailManager.send_confirm_email_email
train
def send_confirm_email_email(self, user, user_email): """Send the 'email confirmation' email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_ENABLE_CONFIRM_EMAIL: return # The confirm_email email is sent to a...
python
{ "resource": "" }
q33122
EmailManager.send_password_changed_email
train
def send_password_changed_email(self, user): """Send the 'password has changed' notification email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_SEND_PASSWORD_CHANGED_EMAIL: return # Notification emails are sent to...
python
{ "resource": "" }
q33123
EmailManager.send_reset_password_email
train
def send_reset_password_email(self, user, user_email): """Send the 'reset password' email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return assert self.user_manager.USER_ENABLE_FORGOT_PASSWORD # The reset_password email is sent to a specific user_e...
python
{ "resource": "" }
q33124
EmailManager.send_invite_user_email
train
def send_invite_user_email(self, user, user_invitation): """Send the 'user invitation' email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_ENABLE_INVITE_USER: return # The user param points to the inviter #...
python
{ "resource": "" }
q33125
EmailManager.send_registered_email
train
def send_registered_email(self, user, user_email, request_email_confirmation): """Send the 'user has registered' notification email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_SEND_REGISTERED_EMAIL: return # The ...
python
{ "resource": "" }
q33126
EmailManager.send_username_changed_email
train
def send_username_changed_email(self, user): """Send the 'username has changed' notification email.""" # Verify config settings if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_SEND_USERNAME_CHANGED_EMAIL: return # Notification emails are sent to...
python
{ "resource": "" }
q33127
UserMixin.get_id
train
def get_id(self): """Converts a User ID and parts of a User password hash to a token.""" # This function is used by Flask-Login to store a User ID securely as a browser cookie. # The last part of the password is included to invalidate tokens when password change. # user_id and password_...
python
{ "resource": "" }
q33128
UserMixin.has_roles
train
def has_roles(self, *requirements): """ Return True if the user has all of the specified roles. Return False otherwise. has_roles() accepts a list of requirements: has_role(requirement1, requirement2, requirement3). Each requirement is either a role_name, or a tuple_of_...
python
{ "resource": "" }
q33129
UserManager__Utils.email_is_available
train
def email_is_available(self, new_email): """Check if ``new_email`` is available. | Returns True if ``new_email`` does not exist or belongs to the current user. | Return False otherwise. """ user, user_email = self.db_manager.get_user_and_user_email_by_email(new_email) r...
python
{ "resource": "" }
q33130
UserManager__Utils.make_safe_url
train
def make_safe_url(self, url): """Makes a URL safe by removing optional hostname and port. Example: | ``make_safe_url('https://hostname:80/path1/path2?q1=v1&q2=v2#fragment')`` | returns ``'/path1/path2?q1=v1&q2=v2#fragment'`` Override this method if you need to allow a ...
python
{ "resource": "" }
q33131
UserManager.password_validator
train
def password_validator(self, form, field): """Ensure that passwords have at least 6 characters with one lowercase letter, one uppercase letter and one number. Override this method to customize the password validator. """ # Convert string to list of characters password = list(fi...
python
{ "resource": "" }
q33132
UserManager.username_validator
train
def username_validator(self, form, field): """Ensure that Usernames contains at least 3 alphanumeric characters. Override this method to customize the username validator. """ username = field.data if len(username) < 3: raise ValidationError( _('Userna...
python
{ "resource": "" }
q33133
UserManager._check_settings
train
def _check_settings(self, app): """Verify required settings. Produce a helpful error messages for incorrect settings.""" # Check for invalid settings # -------------------------- # Check self.UserInvitationClass and USER_ENABLE_INVITE_USER if self.USER_ENABLE_INVITE_USER and no...
python
{ "resource": "" }
q33134
MongoDbAdapter.drop_all_tables
train
def drop_all_tables(self): """Drop all document collections of the database. .. warning:: ALL DATA WILL BE LOST. Use only for automated testing. """ # Retrieve database name from application config app = self.db.app mongo_settings = app.config['MONGODB_SETTINGS'] ...
python
{ "resource": "" }
q33135
DynamoDbAdapter.add_object
train
def add_object(self, object): """Add object to db session. Only for session-centric object-database mappers.""" if object.id is None: object.get_id() self.db.engine.save(object)
python
{ "resource": "" }
q33136
DynamoDbAdapter.delete_object
train
def delete_object(self, object): """ Delete object specified by ``object``. """ #pdb.set_trace() self.db.engine.delete_key(object)#, userid='abc123', id='1') print('dynamo.delete_object(%s)' % object)
python
{ "resource": "" }
q33137
unique_username_validator
train
def unique_username_validator(form, field): """ Ensure that Username is unique. This validator may NOT be customized.""" user_manager = current_app.user_manager if not user_manager.db_manager.username_is_available(field.data): raise ValidationError(_('This Username is already in use. Please try ano...
python
{ "resource": "" }
q33138
unique_email_validator
train
def unique_email_validator(form, field): """ Username must be unique. This validator may NOT be customized.""" user_manager = current_app.user_manager if not user_manager.email_is_available(field.data): raise ValidationError(_('This Email is already in use. Please try another one.'))
python
{ "resource": "" }
q33139
SMTPEmailAdapter.send_email_message
train
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name): """ Send email message via Flask-Mail. Args: recipient: Email address or tuple of (Name, Email-address). subject: Subject line. html_message: The message body in ...
python
{ "resource": "" }
q33140
PasswordManager.verify_password
train
def verify_password(self, password, password_hash): """Verify plaintext ``password`` against ``hashed password``. Args: password(str): Plaintext password that the user types in. password_hash(str): Password hash generated by a previous call to ``hash_password()``. Return...
python
{ "resource": "" }
q33141
SendgridEmailAdapter.send_email_message
train
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name): """ Send email message via sendgrid-python. Args: recipient: Email address or tuple of (Name, Email-address). subject: Subject line. html_message: The message bod...
python
{ "resource": "" }
q33142
PynamoDbAdapter.create_all_tables
train
def create_all_tables(self): """Create database tables for all known database data-models.""" for klass in self.__get_classes(): if not klass.exists(): klass.create_table(read_capacity_units=1, write_capacity_units=1, wait=True)
python
{ "resource": "" }
q33143
BasePlot.draw
train
def draw(self): """ Draws the Plot to screen. If there is a continuous datatype for the nodes, it will be reflected in self.sm being constructed (in `compute_node_colors`). It will then automatically add in a colorbar to the plot and scale the plot axes accordingly. ...
python
{ "resource": "" }
q33144
BasePlot.compute_node_colors
train
def compute_node_colors(self): """Compute the node colors. Also computes the colorbar.""" data = [self.graph.node[n][self.node_color] for n in self.nodes] if self.group_order == "alphabetically": data_reduced = sorted(list(set(data))) elif self.group_order == "default": ...
python
{ "resource": "" }
q33145
BasePlot.compute_group_colors
train
def compute_group_colors(self): """Computes the group colors according to node colors""" seen = set() self.group_label_color = [ x for x in self.node_colors if not (x in seen or seen.add(x)) ]
python
{ "resource": "" }
q33146
BasePlot.compute_edge_colors
train
def compute_edge_colors(self): """Compute the edge colors.""" data = [self.graph.edges[n][self.edge_color] for n in self.edges] data_reduced = sorted(list(set(data))) dtype = infer_data_type(data) n_grps = num_discrete_groups(data) if dtype == "categorical" or dtype == "...
python
{ "resource": "" }
q33147
BasePlot.compute_node_sizes
train
def compute_node_sizes(self): """Compute the node sizes.""" if type(self.node_size) is str: nodes = self.graph.nodes self.node_sizes = [nodes[n][self.node_size] for n in self.nodes] else: self.node_sizes = self.node_size
python
{ "resource": "" }
q33148
BasePlot.compute_edge_widths
train
def compute_edge_widths(self): """Compute the edge widths.""" if type(self.edge_width) is str: edges = self.graph.edges self.edge_widths = [edges[n][self.edge_width] for n in self.edges] else: self.edge_widths = self.edge_width
python
{ "resource": "" }
q33149
BasePlot.group_and_sort_nodes
train
def group_and_sort_nodes(self): """ Groups and then sorts the nodes according to the criteria passed into the Plot constructor. """ if self.node_grouping and not self.node_order: if self.group_order == "alphabetically": self.nodes = [ ...
python
{ "resource": "" }
q33150
CircosPlot.compute_group_label_positions
train
def compute_group_label_positions(self): """ Computes the x,y positions of the group labels. """ assert self.group_label_position in ["beginning", "middle", "end"] data = [self.graph.node[n][self.node_grouping] for n in self.nodes] node_length = len(data) groups =...
python
{ "resource": "" }
q33151
CircosPlot.compute_node_positions
train
def compute_node_positions(self): """ Uses the get_cartesian function to compute the positions of each node in the Circos plot. """ xs = [] ys = [] node_r = self.nodeprops["radius"] radius = circos_radius(n_nodes=len(self.graph.nodes()), node_r=node_r) ...
python
{ "resource": "" }
q33152
CircosPlot.compute_node_label_positions
train
def compute_node_label_positions(self): """ Uses the get_cartesian function to compute the positions of each node label in the Circos plot. This method is always called after the compute_node_positions method, so that the plot_radius is pre-computed. This will also add a...
python
{ "resource": "" }
q33153
CircosPlot.store_node_label_meta
train
def store_node_label_meta(self, x, y, tx, ty, rot): """ This function stored coordinates-related metadate for a node This function should not be called by the user :param x: x location of node label or number :type x: np.float64 :param y: y location of node label or num...
python
{ "resource": "" }
q33154
CircosPlot.draw_nodes
train
def draw_nodes(self): """ Renders nodes to the figure. """ node_r = self.nodeprops["radius"] lw = self.nodeprops["linewidth"] for i, node in enumerate(self.nodes): x = self.node_coords["x"][i] y = self.node_coords["y"][i] color = self.n...
python
{ "resource": "" }
q33155
CircosPlot.draw_group_labels
train
def draw_group_labels(self): """ Renders group labels to the figure. """ for i, label in enumerate(self.groups): label_x = self.group_label_coords["x"][i] label_y = self.group_label_coords["y"][i] label_ha = self.group_label_aligns["has"][i] ...
python
{ "resource": "" }
q33156
MatrixPlot.draw
train
def draw(self): """ Draws the plot to screen. Note to self: Do NOT call super(MatrixPlot, self).draw(); the underlying logic for drawing here is completely different from other plots, and as such necessitates a different implementation. """ matrix = nx.to_numpy_m...
python
{ "resource": "" }
q33157
ArcPlot.compute_node_positions
train
def compute_node_positions(self): """ Computes nodes positions. Arranges nodes in a line starting at (x,y) = (0,0). Node radius is assumed to be equal to 0.5 units. Nodes are placed at integer locations. """ xs = [0] * len(self.nodes) ys = [0] * len(self....
python
{ "resource": "" }
q33158
ArcPlot.draw_nodes
train
def draw_nodes(self): """ Draw nodes to screen. """ node_r = self.node_sizes for i, node in enumerate(self.nodes): x = self.node_coords["x"][i] y = self.node_coords["y"][i] color = self.node_colors[i] node_patch = patches.Ellipse( ...
python
{ "resource": "" }
q33159
GeoPlot.compute_node_positions
train
def compute_node_positions(self): """ Extracts the node positions based on the specified longitude and latitude keyword arguments. """ xs = [] ys = [] self.locs = dict() for node in self.nodes: x = self.graph.node[node][self.node_lon] ...
python
{ "resource": "" }
q33160
GeoPlot.draw_nodes
train
def draw_nodes(self): """ Draws nodes to the screen. GeoPlot is the first plot kind to support an Altair backend in addition to the usual matplotlib backend. """ if self.backend == "matplotlib": node_r = 0.005 # temporarily hardcoded. for i, node...
python
{ "resource": "" }
q33161
GeoPlot.draw_edges
train
def draw_edges(self): """ Draws edges to screen. """ if self.backend == "matplotlib": for i, (n1, n2) in enumerate(self.edges): x1, y1 = self.locs[n1] x2, y2 = self.locs[n2] color = self.edge_colors[i] line = Lin...
python
{ "resource": "" }
q33162
update_travis_deploy_password
train
def update_travis_deploy_password(encrypted_password): """Update the deploy section of the .travis.yml file to use the given encrypted password. """ config = load_yaml_config(TRAVIS_CONFIG_FILE) config["deploy"]["password"] = dict(secure=encrypted_password) save_yaml_config(TRAVIS_CONFIG_FILE,...
python
{ "resource": "" }
q33163
graph_from_dataframe
train
def graph_from_dataframe( dataframe, threshold_by_percent_unique=0.1, threshold_by_count_unique=None, node_id_columns=[], node_property_columns=[], edge_property_columns=[], node_type_key="type", edge_type_key="type", collapse_edges=True, edge_agg_key="weight", ): """ Bui...
python
{ "resource": "" }
q33164
is_data_homogenous
train
def is_data_homogenous(data_container): """ Checks that all of the data in the container are of the same Python data type. This function is called in every other function below, and as such need not necessarily be called. :param data_container: A generic container of data points. :type data_con...
python
{ "resource": "" }
q33165
infer_data_type
train
def infer_data_type(data_container): """ For a given container of data, infer the type of data as one of continuous, categorical, or ordinal. For now, it is a one-to-one mapping as such: - str: categorical - int: ordinal - float: continuous There may be better ways that are not cu...
python
{ "resource": "" }
q33166
is_data_diverging
train
def is_data_diverging(data_container): """ We want to use this to check whether the data are diverging or not. This is a simple check, can be made much more sophisticated. :param data_container: A generic container of data points. :type data_container: `iterable` """ assert infer_data_type...
python
{ "resource": "" }
q33167
to_pandas_nodes
train
def to_pandas_nodes(G): # noqa: N803 """ Convert nodes in the graph into a pandas DataFrame. """ data = [] for n, meta in G.nodes(data=True): d = dict() d["node"] = n d.update(meta) data.append(d) return pd.DataFrame(data)
python
{ "resource": "" }
q33168
to_pandas_edges
train
def to_pandas_edges(G, x_kw, y_kw, **kwargs): # noqa: N803 """ Convert Graph edges to pandas DataFrame that's readable to Altair. """ # Get all attributes in nodes attributes = ["source", "target", "x", "y", "edge", "pair"] for e in G.edges(): attributes += list(G.edges[e].keys()) a...
python
{ "resource": "" }
q33169
node_theta
train
def node_theta(nodelist, node): """ Maps node to Angle. :param nodelist: Nodelist from the graph. :type nodelist: list. :param node: The node of interest. Must be in the nodelist. :returns: theta -- the angle of the node in radians. """ assert len(nodelist) > 0, "nodelist must be a list...
python
{ "resource": "" }
q33170
group_theta
train
def group_theta(node_length, node_idx): """ Returns an angle corresponding to a node of interest. Intended to be used for placing node group labels at the correct spot. :param float node_length: total number of nodes in the graph. :param int node_idx: the index of the node of interest. :return...
python
{ "resource": "" }
q33171
text_alignment
train
def text_alignment(x, y): """ Align text labels based on the x- and y-axis coordinate values. This function is used for computing the appropriate alignment of the text label. For example, if the text is on the "right" side of the plot, we want it to be left-aligned. If the text is on the "top"...
python
{ "resource": "" }
q33172
circos_radius
train
def circos_radius(n_nodes, node_r): """ Automatically computes the origin-to-node centre radius of the Circos plot using the triangle equality sine rule. a / sin(A) = b / sin(B) = c / sin(C) :param n_nodes: the number of nodes in the plot. :type n_nodes: int :param node_r: the radius of ea...
python
{ "resource": "" }
q33173
to_polar
train
def to_polar(x, y, theta_units="radians"): """ Converts cartesian x, y to polar r, theta. """ assert theta_units in [ "radians", "degrees", ], "kwarg theta_units must specified in radians or degrees" theta = atan2(y, x) r = sqrt(x ** 2 + y ** 2) if theta_units == "degre...
python
{ "resource": "" }
q33174
download_track
train
def download_track(track, album_name=u'', keep_previews=False, folders=False, filenames=[], custom_path=''): """ Given a track, force scrape it. """ hard_track_url = get_hard_track_url(track['id']) # We have no info on this track whatsoever. if not 'title' in track: return None if...
python
{ "resource": "" }
q33175
get_soundcloud_data
train
def get_soundcloud_data(url): """ Scrapes a SoundCloud page for a track's important information. Returns: dict: of audio data """ data = {} request = requests.get(url) title_tag = request.text.split('<title>')[1].split('</title')[0] data['title'] = title_tag.split(' by ')[0]...
python
{ "resource": "" }
q33176
get_hard_track_url
train
def get_hard_track_url(item_id): """ Hard-scrapes a track. """ streams_url = "https://api.soundcloud.com/i1/tracks/%s/streams/?client_id=%s&app_version=%s" % ( item_id, AGGRESSIVE_CLIENT_ID, APP_VERSION) response = requests.get(streams_url) json_response = response.json() if response.s...
python
{ "resource": "" }
q33177
process_bandcamp
train
def process_bandcamp(vargs): """ Main BandCamp path. """ artist_url = vargs['artist_url'] if 'bandcamp.com' in artist_url or ('://' in artist_url and vargs['bandcamp']): bc_url = artist_url else: bc_url = 'https://' + artist_url + '.bandcamp.com/music' filenames = scrape_b...
python
{ "resource": "" }
q33178
scrape_bandcamp_url
train
def scrape_bandcamp_url(url, num_tracks=sys.maxsize, folders=False, custom_path=''): """ Pull out artist and track info from a Bandcamp URL. Returns: list: filenames to open """ filenames = [] album_data = get_bandcamp_metadata(url) # If it's a list, we're dealing with a list of A...
python
{ "resource": "" }
q33179
process_mixcloud
train
def process_mixcloud(vargs): """ Main MixCloud path. """ artist_url = vargs['artist_url'] if 'mixcloud.com' in artist_url: mc_url = artist_url else: mc_url = 'https://mixcloud.com/' + artist_url filenames = scrape_mixcloud_url(mc_url, num_tracks=vargs['num_tracks'], folder...
python
{ "resource": "" }
q33180
process_audiomack
train
def process_audiomack(vargs): """ Main Audiomack path. """ artist_url = vargs['artist_url'] if 'audiomack.com' in artist_url: mc_url = artist_url else: mc_url = 'https://audiomack.com/' + artist_url filenames = scrape_audiomack_url(mc_url, num_tracks=vargs['num_tracks'], f...
python
{ "resource": "" }
q33181
process_hive
train
def process_hive(vargs): """ Main Hive.co path. """ artist_url = vargs['artist_url'] if 'hive.co' in artist_url: mc_url = artist_url else: mc_url = 'https://www.hive.co/downloads/download/' + artist_url filenames = scrape_hive_url(mc_url, num_tracks=vargs['num_tracks'], fo...
python
{ "resource": "" }
q33182
scrape_hive_url
train
def scrape_hive_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''): """ Scrape a Hive.co download page. Returns: list: filenames to open """ try: data = get_hive_data(mc_url) except Exception as e: puts_safe(colored.red("Problem downloading ") + mc_url)...
python
{ "resource": "" }
q33183
process_musicbed
train
def process_musicbed(vargs): """ Main MusicBed path. """ # let's validate given MusicBed url validated = False if vargs['artist_url'].startswith( 'https://www.musicbed.com/' ): splitted = vargs['artist_url'][len('https://www.musicbed.com/'):].split( '/' ) if len( splitted ) == 3...
python
{ "resource": "" }
q33184
download_file
train
def download_file(url, path, session=None, params=None): """ Download an individual file. """ if url[0:2] == '//': url = 'https://' + url[2:] # Use a temporary file so that we don't import incomplete files. tmp_path = path + '.tmp' if session and params: r = session.get( u...
python
{ "resource": "" }
q33185
tag_file
train
def tag_file(filename, artist, title, year=None, genre=None, artwork_url=None, album=None, track_number=None, url=None): """ Attempt to put ID3 tags on a file. Args: artist (str): title (str): year (int): genre (str): artwork_url (str): album (str): t...
python
{ "resource": "" }
q33186
open_files
train
def open_files(filenames): """ Call the system 'open' command on a file. """ command = ['open'] + filenames process = Popen(command, stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate()
python
{ "resource": "" }
q33187
sanitize_filename
train
def sanitize_filename(filename): """ Make sure filenames are valid paths. Returns: str: """ sanitized_filename = re.sub(r'[/\\:*?"<>|]', '-', filename) sanitized_filename = sanitized_filename.replace('&', 'and') sanitized_filename = sanitized_filename.replace('"', '') sanitized_...
python
{ "resource": "" }
q33188
Crc.update
train
def update(self, byte_arr): """Read bytes and update the CRC computed.""" if byte_arr: self.value = self.calculate(byte_arr, self.value)
python
{ "resource": "" }
q33189
Crc.calculate
train
def calculate(cls, byte_arr, crc=0): """Compute CRC for input bytes.""" for byte in byte_iter(byte_arr): # Taken verbatim from FIT SDK docs tmp = cls.CRC_TABLE[crc & 0xF] crc = (crc >> 4) & 0x0FFF crc = crc ^ tmp ^ cls.CRC_TABLE[byte & 0xF] tm...
python
{ "resource": "" }
q33190
FitFileDataProcessor._scrub_method_name
train
def _scrub_method_name(self, method_name): """Scrubs a method name, returning result from local cache if available. This method wraps fitparse.utils.scrub_method_name and memoizes results, as scrubbing a method name is expensive. Args: method_name: Method name to scrub. ...
python
{ "resource": "" }
q33191
notify
train
def notify(title, message, prio='ALERT', facility='LOCAL5', fmt='[{title}] {message}', retcode=None): """ Uses the ``syslog`` core Python module, which is not available on Windows platforms. Optional parameters: * ``prio`` - Syslog prority ...
python
{ "resource": "" }
q33192
notify
train
def notify(title, message, **kwargs): """ This backend automatically selects the correct desktop notification backend for your operating system. """ for os in ['linux', 'win32', 'darwin']: if platform.startswith(os): module = import_module('ntfy.backends.{}'.format(os)) ...
python
{ "resource": "" }
q33193
notify
train
def notify(title, message, retcode=None): """Sends message over Telegram using telegram-send, title is ignored.""" if not path.exists(config_file): if not path.exists(config_dir): makedirs(config_dir) print("Follow the instructions to configure the Telegram backend.\n") confi...
python
{ "resource": "" }
q33194
minute_change
train
def minute_change(device): '''When we reach a minute change, animate it.''' hours = datetime.now().strftime('%H') minutes = datetime.now().strftime('%M') def helper(current_y): with canvas(device) as draw: text(draw, (0, 1), hours, fill="white", font=proportional(CP437_FONT)) ...
python
{ "resource": "" }
q33195
clock
train
def clock(seg, seconds): """ Display current time on device. """ interval = 0.5 for i in range(int(seconds / interval)): now = datetime.now() seg.text = now.strftime("%H-%M-%S") # calculate blinking dot if i % 2 == 0: seg.text = now.strftime("%H-%M-%S") ...
python
{ "resource": "" }
q33196
ws2812.hide
train
def hide(self): """ Simulates switching the display mode OFF; this is achieved by setting the contrast level to zero. """ if self._prev_contrast is None: self._prev_contrast = self._contrast self.contrast(0x00)
python
{ "resource": "" }
q33197
ws2812.cleanup
train
def cleanup(self): """ Attempt to reset the device & switching it off prior to exiting the python process. """ self.hide() self.clear() if self._leds is not None: self._ws.ws2811_fini(self._leds) self._ws.delete_ws2811_t(self._leds) ...
python
{ "resource": "" }
q33198
rotate_image_180
train
def rotate_image_180(): ''' Rotate the image ''' # Create the media service mycam = ONVIFCamera('192.168.0.112', 80, 'admin', '12345') media_service = mycam.create_media_service() profiles = media_service.GetProfiles() # Use the first profile and Profiles have at least one token = profile...
python
{ "resource": "" }
q33199
ONVIFService.set_wsse
train
def set_wsse(self, user=None, passwd=None): ''' Basic ws-security auth ''' if user: self.user = user if passwd: self.passwd = passwd security = Security() if self.encrypt: token = UsernameDigestTokenDtDiff(self.user, self.passwd, dt_diff=self...
python
{ "resource": "" }