Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def serve(content):
temp_folder = tempfile.gettempdir()
temp_file_name = tempfile.gettempprefix() + str(uuid.uuid4()) + ".html"
# Generate a file path with a random name in temporary dir
temp_file_path = os.path.join(temp_folder, temp_file_name)
# s... | [
"Write content to a temp file and serve it in browser"
] |
Please provide a description of the function:def render_template(table_headers, table_items, **options):
caption = options.get("caption") or "Table"
display_length = options.get("display_length") or -1
height = options.get("height") or "70vh"
default_length_menu = [-1, 10, 25, 50]
pagination = ... | [
"\n Render Jinja2 template\n "
] |
Please provide a description of the function:def freeze_js(html):
matches = js_src_pattern.finditer(html)
if not matches:
return html
# Reverse regex matches to replace match string with respective JS content
for match in reversed(tuple(matches)):
# JS file name
file_name ... | [
"\n Freeze all JS assets to the rendered html itself.\n "
] |
Please provide a description of the function:def cli(*args, **kwargs):
# Convert CSV file
content = convert.convert(kwargs["input_file"], **kwargs)
# Serve the temporary file in browser.
if kwargs["serve"]:
convert.serve(content)
# Write to output file
elif kwargs["output_file"]:
... | [
"\n CSVtoTable commandline utility.\n "
] |
Please provide a description of the function:def activate(request, activation_key,
template_name='userena/activate_fail.html',
retry_template_name='userena/activate_retry.html',
success_url=None, extra_context=None):
try:
if (not UserenaSignup.objects.check_expire... | [
"\n Activate a user with an activation key.\n\n The key is a SHA1 string. When the SHA1 is found with an\n :class:`UserenaSignup`, the :class:`User` of that account will be\n activated. After a successful activation the view will redirect to\n ``success_url``. If the SHA1 is not found, the user wil... |
Please provide a description of the function:def activate_retry(request, activation_key,
template_name='userena/activate_retry_success.html',
extra_context=None):
if not userena_settings.USERENA_ACTIVATION_RETRY:
return redirect(reverse('userena_activate', args=(ac... | [
"\n Reissue a new ``activation_key`` for the user with the expired\n ``activation_key``.\n\n If ``activation_key`` does not exists, or ``USERENA_ACTIVATION_RETRY`` is\n set to False and for any other error condition user is redirected to\n :func:`activate` for error message display.\n\n :param act... |
Please provide a description of the function:def email_confirm(request, confirmation_key,
template_name='userena/email_confirm_fail.html',
success_url=None, extra_context=None):
user = UserenaSignup.objects.confirm_email(confirmation_key)
if user:
if userena_sett... | [
"\n Confirms an email address with a confirmation key.\n\n Confirms a new email address by running :func:`User.objects.confirm_email`\n method. If the method returns an :class:`User` the user will have his new\n e-mail address set and redirected to ``success_url``. If no ``User`` is\n returned the us... |
Please provide a description of the function:def disabled_account(request, username, template_name, extra_context=None):
user = get_object_or_404(get_user_model(), username__iexact=username)
if user.is_active:
raise Http404
if not extra_context: extra_context = dict()
extra_context['viewe... | [
"\n Checks if the account is disabled, if so, returns the disabled account template.\n\n :param username:\n String defining the username of the user that made the action.\n\n :param template_name:\n String defining the name of the template to use. Defaults to\n ``userena/signup_complet... |
Please provide a description of the function:def signin(request, auth_form=AuthenticationForm,
template_name='userena/signin_form.html',
redirect_field_name=REDIRECT_FIELD_NAME,
redirect_signin_function=signin_redirect, extra_context=None):
form = auth_form()
if request.me... | [
"\n Signin using email or username with password.\n\n Signs a user in by combining email/username with password. If the\n combination is correct and the user :func:`is_active` the\n :func:`redirect_signin_function` is called with the arguments\n ``REDIRECT_FIELD_NAME`` and an instance of the :class:`... |
Please provide a description of the function:def email_change(request, username, email_form=ChangeEmailForm,
template_name='userena/email_form.html', success_url=None,
extra_context=None):
user = get_object_or_404(get_user_model(), username__iexact=username)
prev_email = u... | [
"\n Change email address\n\n :param username:\n String of the username which specifies the current account.\n\n :param email_form:\n Form that will be used to change the email address. Defaults to\n :class:`ChangeEmailForm` supplied by userena.\n\n :param template_name:\n Str... |
Please provide a description of the function:def profile_edit(request, username, edit_profile_form=EditProfileForm,
template_name='userena/profile_form.html', success_url=None,
extra_context=None, **kwargs):
user = get_object_or_404(get_user_model(), username__iexact=username)... | [
"\n Edit profile.\n\n Edits a profile selected by the supplied username. First checks\n permissions if the user is allowed to edit this profile, if denied will\n show a 404. When the profile is successfully edited will redirect to\n ``success_url``.\n\n :param username:\n Username of the us... |
Please provide a description of the function:def profile_detail(request, username,
template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
extra_context=None, **kwargs):
user = get_object_or_404(get_user_model(), username__iexact=username)
profile = get_user_profile(user=user)
if not pr... | [
"\n Detailed view of an user.\n\n :param username:\n String of the username of which the profile should be viewed.\n\n :param template_name:\n String representing the template name that should be used to display\n the profile.\n\n :param extra_context:\n Dictionary of variabl... |
Please provide a description of the function:def profile_list(request, page=1, template_name='userena/profile_list.html',
paginate_by=50, extra_context=None, **kwargs): # pragma: no cover
warnings.warn("views.profile_list is deprecated. Use ProfileListView instead", DeprecationWarning, stackle... | [
"\n Returns a list of all profiles that are public.\n\n It's possible to disable this by changing ``USERENA_DISABLE_PROFILE_LIST``\n to ``True`` in your settings.\n\n :param page:\n Integer of the active page used for pagination. Defaults to the first\n page.\n\n :param template_name:\n... |
Please provide a description of the function:def send_mail(subject, message_plain, message_html, email_from, email_to,
custom_headers={}, attachments=()):
if not message_plain and not message_html:
raise ValueError(_("Either message_plain or message_html should be not None"))
if not ... | [
"\n Build the email as a multipart message containing\n a multipart alternative for text (plain, HTML) plus\n all the attached files.\n "
] |
Please provide a description of the function:def get_or_create(self, um_from_user, um_to_user, message):
created = False
try:
contact = self.get(Q(um_from_user=um_from_user, um_to_user=um_to_user) |
Q(um_from_user=um_to_user, um_to_user=um_from_user))
... | [
"\n Get or create a Contact\n\n We override Django's :func:`get_or_create` because we want contact to\n be unique in a bi-directional manner.\n\n "
] |
Please provide a description of the function:def update_contact(self, um_from_user, um_to_user, message):
contact, created = self.get_or_create(um_from_user,
um_to_user,
message)
# If the contact alread... | [
" Get or update a contacts information "
] |
Please provide a description of the function:def get_contacts_for(self, user):
contacts = self.filter(Q(um_from_user=user) | Q(um_to_user=user))
return contacts | [
"\n Returns the contacts for this user.\n\n Contacts are other users that this user has received messages\n from or send messages to.\n\n :param user:\n The :class:`User` which to get the contacts for.\n\n "
] |
Please provide a description of the function:def send_message(self, sender, um_to_user_list, body):
msg = self.model(sender=sender,
body=body)
msg.save()
# Save the recipients
msg.save_recipients(um_to_user_list)
msg.update_contacts(um_to_user_l... | [
"\n Send a message from a user, to a user.\n\n :param sender:\n The :class:`User` which sends the message.\n\n :param um_to_user_list:\n A list which elements are :class:`User` to whom the message is for.\n\n :param message:\n String containing the messag... |
Please provide a description of the function:def get_conversation_between(self, um_from_user, um_to_user):
messages = self.filter(Q(sender=um_from_user, recipients=um_to_user,
sender_deleted_at__isnull=True) |
Q(sender=um_to_user, recipien... | [
" Returns a conversation between two users "
] |
Please provide a description of the function:def count_unread_messages_for(self, user):
unread_total = self.filter(user=user,
read_at__isnull=True,
deleted_at__isnull=True).count()
return unread_total | [
"\n Returns the amount of unread messages for this user\n\n :param user:\n A Django :class:`User`\n\n :return:\n An integer with the amount of unread messages.\n\n "
] |
Please provide a description of the function:def count_unread_messages_between(self, um_to_user, um_from_user):
unread_total = self.filter(message__sender=um_from_user,
user=um_to_user,
read_at__isnull=True,
... | [
"\n Returns the amount of unread messages between two users\n\n :param um_to_user:\n A Django :class:`User` for who the messages are for.\n\n :param um_from_user:\n A Django :class:`User` from whom the messages originate from.\n\n :return:\n An integer wi... |
Please provide a description of the function:def create_user(self, username, email, password, active=False,
send_email=True):
new_user = get_user_model().objects.create_user(
username, email, password)
new_user.is_active = active
new_user.save()
... | [
"\n A simple wrapper that creates a new :class:`User`.\n\n :param username:\n String containing the username of the new user.\n\n :param email:\n String containing the email address of the new user.\n\n :param password:\n String containing the password fo... |
Please provide a description of the function:def create_userena_profile(self, user):
if isinstance(user.username, text_type):
user.username = smart_text(user.username)
salt, activation_key = generate_sha1(user.username)
try:
profile = self.get(user=user)
... | [
"\n Creates an :class:`UserenaSignup` instance for this user.\n\n :param user:\n Django :class:`User` instance.\n\n :return: The newly created :class:`UserenaSignup` instance.\n\n "
] |
Please provide a description of the function:def reissue_activation(self, activation_key):
try:
userena = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return False
try:
salt, new_activation_key = generate_sha1(userena.user.u... | [
"\n Creates a new ``activation_key`` resetting activation timeframe when\n users let the previous key expire.\n\n :param activation_key:\n String containing the secret SHA1 activation key.\n\n "
] |
Please provide a description of the function:def activate_user(self, activation_key):
if SHA1_RE.search(activation_key):
try:
userena = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return False
if not userena... | [
"\n Activate an :class:`User` by supplying a valid ``activation_key``.\n\n If the key is valid and an user is found, activates the user and\n return it. Also sends the ``activation_complete`` signal.\n\n :param activation_key:\n String containing the secret SHA1 for a valid ac... |
Please provide a description of the function:def check_expired_activation(self, activation_key):
if SHA1_RE.search(activation_key):
userena = self.get(activation_key=activation_key)
return userena.activation_key_expired()
raise self.model.DoesNotExist | [
"\n Check if ``activation_key`` is still valid.\n\n Raises a ``self.model.DoesNotExist`` exception if key is not present or\n ``activation_key`` is not a valid string\n\n :param activation_key:\n String containing the secret SHA1 for a valid activation.\n\n :return:\n ... |
Please provide a description of the function:def confirm_email(self, confirmation_key):
if SHA1_RE.search(confirmation_key):
try:
userena = self.get(email_confirmation_key=confirmation_key,
email_unconfirmed__isnull=False)
excep... | [
"\n Confirm an email address by checking a ``confirmation_key``.\n\n A valid ``confirmation_key`` will set the newly wanted e-mail\n address as the current e-mail address. Returns the user after\n success or ``False`` when the confirmation key is\n invalid. Also sends the ``confir... |
Please provide a description of the function:def delete_expired_users(self):
deleted_users = []
for user in get_user_model().objects.filter(is_staff=False,
is_active=False):
if user.userena_signup.activation_key_expired():
... | [
"\n Checks for expired users and delete's the ``User`` associated with\n it. Skips if the user ``is_staff``.\n\n :return: A list containing the deleted users.\n\n "
] |
Please provide a description of the function:def check_permissions(self):
# Variable to supply some feedback
changed_permissions = []
changed_users = []
warnings = []
# Check that all the permissions are available.
for model, perms in ASSIGNED_PERMISSIONS.items(... | [
"\n Checks that all permissions are set correctly for the users.\n\n :return: A set of users whose permissions was wrong.\n\n "
] |
Please provide a description of the function:def get_visible_profiles(self, user=None):
profiles = self.all()
filter_kwargs = {'user__is_active': True}
profiles = profiles.filter(**filter_kwargs)
if user and isinstance(user, AnonymousUser):
profiles = profiles.excl... | [
"\n Returns all the visible profiles available to this user.\n\n For now keeps it simple by just applying the cases when a user is not\n active, a user has it's profile closed to everyone or a user only\n allows registered users to view their profile.\n\n :param user:\n ... |
Please provide a description of the function:def authenticate(self, request, identification, password=None, check_password=True):
User = get_user_model()
try:
django.core.validators.validate_email(identification)
try: user = User.objects.get(email__iexact=identification)... | [
"\n Authenticates a user through the combination email/username with\n password.\n\n :param request:\n The authenticate() method of authentication backends requires\n request as the first positional argument from Django 2.1.\n\n :param identification:\n A... |
Please provide a description of the function:def get_unread_message_count_for(parser, token):
try:
tag_name, arg = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError("%s tag requires arguments" % token.contents.split()[0])
m = re.search(r'(.*?) as (\w+)'... | [
"\n Returns the unread message count for a user.\n\n Syntax::\n\n {% get_unread_message_count_for [user] as [var_name] %}\n\n Example usage::\n\n {% get_unread_message_count_for pero as message_count %}\n\n "
] |
Please provide a description of the function:def get_unread_message_count_between(parser, token):
try:
tag_name, arg = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError("%s tag requires arguments" % token.contents.split()[0])
m = re.search(r'(.*?) and (... | [
"\n Returns the unread message count between two users.\n\n Syntax::\n\n {% get_unread_message_count_between [user] and [user] as [var_name] %}\n\n Example usage::\n\n {% get_unread_message_count_between funky and wunki as message_count %}\n\n "
] |
Please provide a description of the function:def upload_to_mugshot(instance, filename):
extension = filename.split('.')[-1].lower()
salt, hash = generate_sha1(instance.pk)
path = userena_settings.USERENA_MUGSHOT_PATH % {'username': instance.user.username,
... | [
"\n Uploads a mugshot for a user to the ``USERENA_MUGSHOT_PATH`` and saving it\n under unique hash for the image. This is for privacy reasons so others\n can't just browse through the mugshot directory.\n\n "
] |
Please provide a description of the function:def message_compose(request, recipients=None, compose_form=ComposeForm,
success_url=None, template_name="umessages/message_form.html",
recipient_filter=None, extra_context=None):
initial_data = dict()
if recipients:
... | [
"\n Compose a new message\n\n :recipients:\n String containing the usernames to whom the message is send to. Can be\n multiple username by seperating them with a ``+`` sign.\n\n :param compose_form:\n The form that is used for getting neccesary information. Defaults to\n :class:... |
Please provide a description of the function:def message_remove(request, undo=False):
message_pks = request.POST.getlist('message_pks')
redirect_to = request.GET.get(REDIRECT_FIELD_NAME,
request.POST.get(REDIRECT_FIELD_NAME, False))
if message_pks:
# Check tha... | [
"\n A ``POST`` to remove messages.\n\n :param undo:\n A Boolean that if ``True`` unremoves messages.\n\n POST can have the following keys:\n\n ``message_pks``\n List of message id's that should be deleted.\n\n ``next``\n String containing the URI which to redirect... |
Please provide a description of the function:def secure_required(view_func):
def _wrapped_view(request, *args, **kwargs):
if not request.is_secure():
if getattr(settings, 'USERENA_USE_HTTPS', userena_settings.DEFAULT_USERENA_USE_HTTPS):
request_url = request.build_absolute_u... | [
"\n Decorator to switch an url from http to https.\n\n If a view is accessed through http and this decorator is applied to that\n view, than it will return a permanent redirect to the secure (https)\n version of the same view.\n\n The decorator also must check that ``USERENA_USE_HTTPS`` is enabled. I... |
Please provide a description of the function:def save(self):
# First save the parent form and get the user.
new_user = super(SignupFormExtra, self).save()
new_user.first_name = self.cleaned_data['first_name']
new_user.last_name = self.cleaned_data['last_name']
new_user.... | [
" \n Override the save method to save the first and last name to the user\n field.\n\n "
] |
Please provide a description of the function:def get_gravatar(email, size=80, default='identicon'):
if userena_settings.USERENA_MUGSHOT_GRAVATAR_SECURE:
base_url = 'https://secure.gravatar.com/avatar/'
else: base_url = '//www.gravatar.com/avatar/'
gravatar_url = '%(base_url)s%(gravatar_id)s?' ... | [
" Get's a Gravatar for a email address.\n\n :param size:\n The size in pixels of one side of the Gravatar's square image.\n Optional, if not supplied will default to ``80``.\n\n :param default:\n Defines what should be displayed if no image is found for this user.\n Optional argume... |
Please provide a description of the function:def signin_redirect(redirect=None, user=None):
if redirect: return redirect
elif user is not None:
return userena_settings.USERENA_SIGNIN_REDIRECT_URL % \
{'username': user.username}
else: return settings.LOGIN_REDIRECT_URL | [
"\n Redirect user after successful sign in.\n\n First looks for a ``requested_redirect``. If not supplied will fall-back to\n the user specific account page. If all fails, will fall-back to the standard\n Django ``LOGIN_REDIRECT_URL`` setting. Returns a string defining the URI to\n go next.\n\n :p... |
Please provide a description of the function:def generate_sha1(string, salt=None):
if not isinstance(string, (str, text_type)):
string = str(string)
if not salt:
salt = sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
salted_bytes = (smart_bytes(salt) + smart_bytes(string))
... | [
"\n Generates a sha1 hash for supplied string. Doesn't need to be very secure\n because it's not used for password checking. We got Django for that.\n\n :param string:\n The string that needs to be encrypted.\n\n :param salt:\n Optionally define your own salt. If none is supplied, will use... |
Please provide a description of the function:def get_profile_model():
if (not hasattr(settings, 'AUTH_PROFILE_MODULE')) or \
(not settings.AUTH_PROFILE_MODULE):
raise SiteProfileNotAvailable
try:
profile_mod = apps.get_model(*settings.AUTH_PROFILE_MODULE.rsplit('.', 1))
exce... | [
"\n Return the model class for the currently-active user profile\n model, as defined by the ``AUTH_PROFILE_MODULE`` setting.\n\n :return: The model that is used as profile.\n\n "
] |
Please provide a description of the function:def save(self, sender):
um_to_user_list = self.cleaned_data['to']
body = self.cleaned_data['body']
msg = Message.objects.send_message(sender,
um_to_user_list,
... | [
"\n Save the message and send it out into the wide world.\n\n :param sender:\n The :class:`User` that sends the message.\n\n :param parent_msg:\n The :class:`Message` that preceded this message in the thread.\n\n :return: The saved :class:`Message`.\n\n "
] |
Please provide a description of the function:def identification_field_factory(label, error_required):
return forms.CharField(label=label,
widget=forms.TextInput(attrs=attrs_dict),
max_length=75,
error_messages={'required': error_r... | [
"\n A simple identification field factory which enable you to set the label.\n\n :param label:\n String containing the label for this field.\n\n :param error_required:\n String containing the error message if the field is left empty.\n\n "
] |
Please provide a description of the function:def clean_username(self):
try:
user = get_user_model().objects.get(username__iexact=self.cleaned_data['username'])
except get_user_model().DoesNotExist:
pass
else:
if userena_settings.USERENA_ACTIVATION_REQ... | [
"\n Validate that the username is alphanumeric and is not already in use.\n Also validates that the username is not listed in\n ``USERENA_FORBIDDEN_USERNAMES`` list.\n\n "
] |
Please provide a description of the function:def clean_email(self):
if get_user_model().objects.filter(email__iexact=self.cleaned_data['email']):
if userena_settings.USERENA_ACTIVATION_REQUIRED and UserenaSignup.objects.filter(user__email__iexact=self.cleaned_data['email']).exclude(activati... | [
" Validate that the e-mail address is unique. "
] |
Please provide a description of the function:def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_('The two password fields didn\'t match.'... | [
"\n Validates that the values entered into the two password fields match.\n Note that an error here will end up in ``non_field_errors()`` because\n it doesn't apply to a single field.\n\n "
] |
Please provide a description of the function:def save(self):
username, email, password = (self.cleaned_data['username'],
self.cleaned_data['email'],
self.cleaned_data['password1'])
new_user = UserenaSignup.objects.create... | [
" Creates a new user and account. Returns the newly created user. "
] |
Please provide a description of the function:def save(self):
while True:
username = sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
try:
get_user_model().objects.get(username__iexact=username)
except get_user_model().DoesNotExist: break
... | [
" Generate a random username before falling back to parent signup form "
] |
Please provide a description of the function:def clean(self):
identification = self.cleaned_data.get('identification')
password = self.cleaned_data.get('password')
if identification and password:
user = authenticate(identification=identification, password=password)
... | [
"\n Checks for the identification and password.\n\n If the combination can't be found will raise an invalid sign in error.\n\n "
] |
Please provide a description of the function:def parse_file(self, sourcepath):
# Open input file and read JSON array:
with open(sourcepath, 'r') as logfile:
jsonlist = logfile.readlines()
# Set our attributes for this entry and add it to data.entries:
data = {}
... | [
"Parse an object-per-line JSON file into a log data dict"
] |
Please provide a description of the function:def filter_data(self, data, value=None, args=None):
if args:
if not args.last:
return data
if not value: value = args.last
# Set the units and number from the option:
lastunit = value[-1]
lastnum = ... | [
"Morph log data by preceeding time period (single log)"
] |
Please provide a description of the function:def parse_file(self, sourcepath):
# Open input file and read JSON array:
with open(sourcepath, 'r') as logfile:
jsonstr = logfile.read()
# Set our attributes for this entry and add it to data.entries:
data = {}
d... | [
"Parse single JSON object into a LogData object"
] |
Please provide a description of the function:def filter_data(self, data, values=None, args=None):
if args:
if not args.rpattern:
return data
if not values: values = args.rpattern
newdata = {}
if 'parser' in data.keys():
newdata['parser'] =... | [
"Remove entries containing specified pattern (single log)"
] |
Please provide a description of the function:def run_job(self):
try:
self.load_parsers()
self.load_filters()
self.load_outputs()
self.config_args()
if self.args.list_parsers:
self.list_parsers()
if self.args.verbose... | [
"Execute a logdissect job"
] |
Please provide a description of the function:def run_parse(self):
# Data set already has source file names from load_inputs
parsedset = {}
parsedset['data_set'] = []
for log in self.input_files:
parsemodule = self.parse_modules[self.args.parser]
try:
... | [
"Parse one or more log files"
] |
Please provide a description of the function:def run_output(self):
for f in logdissect.output.__formats__:
ouroutput = self.output_modules[f]
ouroutput.write_output(self.data_set['finalized_data'],
args=self.args)
del(ouroutput)
# Output ... | [
"Output finalized data"
] |
Please provide a description of the function:def config_args(self):
# Module list options:
self.arg_parser.add_argument('--version', action='version',
version='%(prog)s ' + str(__version__))
self.arg_parser.add_argument('--verbose',
action='store_true', d... | [
"Set config options"
] |
Please provide a description of the function:def load_inputs(self):
for f in self.args.files:
if os.path.isfile(f):
fparts = str(f).split('.')
if fparts[-1] == 'gz':
if self.args.unzip:
fullpath = os.path.abspath(st... | [
"Load the specified inputs"
] |
Please provide a description of the function:def list_parsers(self, *args):
print('==== Available parsing modules: ====\n')
for parser in sorted(self.parse_modules):
print(self.parse_modules[parser].name.ljust(16) + \
': ' + self.parse_modules[parser].desc)
s... | [
"Return a list of available parsing modules"
] |
Please provide a description of the function:def load_parsers(self):
for parser in sorted(logdissect.parsers.__all__):
self.parse_modules[parser] = \
__import__('logdissect.parsers.' + parser, globals(), \
locals(), [logdissect]).ParseModule() | [
"Load parsing module(s)"
] |
Please provide a description of the function:def load_filters(self):
for f in sorted(logdissect.filters.__filters__):
self.filter_modules[f] = \
__import__('logdissect.filters.' + f, globals(), \
locals(), [logdissect]).FilterModule(args=self.filter_args) | [
"Load filter module(s)"
] |
Please provide a description of the function:def load_outputs(self):
for output in sorted(logdissect.output.__formats__):
self.output_modules[output] = \
__import__('logdissect.output.' + output, globals(), \
locals(), [logdissect]).OutputModule(args=self.out... | [
"Load output module(s)"
] |
Please provide a description of the function:def get_utc_date(entry):
if entry['numeric_date_stamp'] == '0':
entry['numeric_date_stamp_utc'] = '0'
return entry
else:
if '.' in entry['numeric_date_stamp']:
t = datetime.strptime(entry['numeric_date_stamp'],
... | [
"Return datestamp converted to UTC"
] |
Please provide a description of the function:def get_local_tzone():
if localtime().tm_isdst:
if altzone < 0:
tzone = '+' + \
str(int(float(altzone) / 60 // 60)).rjust(2,
'0') + \
str(int(float(
... | [
"Get the current time zone on the local host"
] |
Please provide a description of the function:def merge_logs(dataset, sort=True):
ourlog = {}
ourlog['entries'] = []
for d in dataset:
ourlog['entries'] = ourlog['entries'] + d['entries']
if sort:
ourlog['entries'].sort(key= lambda x: x['numeric_date_stamp_utc'])
return ourlog | [
"Merge log dictionaries together into one log dictionary"
] |
Please provide a description of the function:def filter_data(self, data, values=None, args=None):
if args:
if not args.pattern:
return data
if not values: values = args.pattern
newdata = {}
if 'parser' in data.keys():
newdata['parser'] = d... | [
"Return entries containing specified patterns (single log)"
] |
Please provide a description of the function:def write_output(self, data, args=None, filename=None, label=None):
if args:
if not args.outlog:
return 0
if not filename: filename=args.outlog
lastpath = ''
with open(str(filename), 'w') as output_file:
... | [
"Write log data to a log file"
] |
Please provide a description of the function:def write_output(self, data, args=None, filename=None, pretty=False):
if args:
if not args.sojson:
return 0
pretty = args.pretty
if not filename: filename = args.sojson
if pretty:
logstring ... | [
"Write log data to a single JSON object"
] |
Please provide a description of the function:def write_output(self, data, filename=None, args=None):
if args:
if not args.linejson:
return 0
if not filename: filename = args.linejson
entrylist = []
for entry in data['entries']:
entrystring... | [
"Write log data to a file with one JSON object per line"
] |
Please provide a description of the function:def parse_file(self, sourcepath):
# Get regex objects:
self.date_regex = re.compile(
r'{}'.format(self.format_regex))
if self.backup_format_regex:
self.backup_date_regex = re.compile(
r'{}'.form... | [
"Parse a file into a LogData object"
] |
Please provide a description of the function:def parse_line(self, line):
match = re.findall(self.date_regex, line)
if match:
fields = self.fields
elif self.backup_format_regex and not match:
match = re.findall(self.backup_date_regex, line)
fields = se... | [
"Parse a line into a dictionary"
] |
Please provide a description of the function:def post_parse_action(self, entry):
if 'source_host' in entry.keys():
host = self.ip_port_regex.findall(entry['source_host'])
if host:
hlist = host[0].split('.')
entry['source_host'] = '.'.join(hlist[:4... | [
"separate hosts and ports after entry is parsed"
] |
Please provide a description of the function:def filter_data(self, data, value=None, utc=False, args=None):
if args:
if not args.range:
return data
if not value:
value = args.range
utc = args.utc
ourlimits = value.split('-')
n... | [
"Morph log data by timestamp range (single log)"
] |
Please provide a description of the function:def filter_data(self, data, values=None, args=None):
if args:
if not args.rprotocol:
return data
if not values: values = args.rprotocol
newdata = {}
if 'parser' in data.keys():
newdata['parser']... | [
"Return entries without specified protocol (single log)"
] |
Please provide a description of the function:def optimise_partition(self, partition):
# Perhaps we
diff = _c_louvain._Optimiser_optimise_partition(self._optimiser, partition._partition)
partition._update_internal_membership()
return diff | [
" Optimise the given partition.\n\n Parameters\n ----------\n partition\n The :class:`~VertexPartition.MutableVertexPartition` to optimise.\n\n Returns\n -------\n float\n Improvement in quality function.\n\n Examples\n --------\n\n >>> G = ig.Graph.Famous('Zachary')\n >>> op... |
Please provide a description of the function:def optimise_partition_multiplex(self, partitions, layer_weights=None):
if not layer_weights:
layer_weights = [1]*len(partitions)
diff = _c_louvain._Optimiser_optimise_partition_multiplex(
self._optimiser,
[partition._partition for partition in... | [
" Optimise the given partitions simultaneously.\n\n Parameters\n ----------\n partitions\n List of :class:`~VertexPartition.MutableVertexPartition` layers to optimise.\n\n layer_weights\n List of weights of layers.\n\n Returns\n -------\n float\n Improvement in quality of combine... |
Please provide a description of the function:def find_partition(graph, partition_type, initial_membership=None, weights=None, **kwargs):
if not weights is None:
kwargs['weights'] = weights
partition = partition_type(graph,
initial_membership=initial_membership,
... | [
" Detect communities using the default settings.\n\n This function detects communities given the specified method in the\n ``partition_type``. This should be type derived from\n :class:`VertexPartition.MutableVertexPartition`, e.g.\n :class:`ModularityVertexPartition` or :class:`CPMVertexPartition`. Optionally\... |
Please provide a description of the function:def find_partition_multiplex(graphs, partition_type, **kwargs):
n_layers = len(graphs)
partitions = []
layer_weights = [1]*n_layers
for graph in graphs:
partitions.append(partition_type(graph, **kwargs))
optimiser = Optimiser()
improvement = optimiser.opti... | [
" Detect communities for multiplex graphs.\n\n Each graph should be defined on the same set of vertices, only the edges may\n differ for different graphs. See\n :func:`Optimiser.optimise_partition_multiplex` for a more detailed\n explanation.\n\n Parameters\n ----------\n graphs : list of :class:`ig.Graph`\n... |
Please provide a description of the function:def find_partition_temporal(graphs, partition_type,
interslice_weight=1,
slice_attr='slice', vertex_id_attr='id',
edge_type_attr='type', weight_attr='weight',
**kw... | [
" Detect communities for temporal graphs.\n\n Each graph is considered to represent a time slice and does not necessarily\n need to be defined on the same set of vertices. Nodes in two consecutive\n slices are identified on the basis of the ``vertex_id_attr``, i.e. if two\n nodes in two consecutive slices have ... |
Please provide a description of the function:def build_ext(self):
try:
from setuptools.command.build_ext import build_ext
except ImportError:
from distutils.command.build_ext import build_ext
buildcfg = self
class custom_build_ext(build_ext):
... | [
"Returns a class that can be used as a replacement for the\n ``build_ext`` command in ``distutils`` and that will download and\n compile the C core of igraph if needed."
] |
Please provide a description of the function:def set_membership(self, membership):
_c_louvain._MutableVertexPartition_set_membership(self._partition, list(membership))
self._update_internal_membership() | [
" Set membership. "
] |
Please provide a description of the function:def diff_move(self,v,new_comm):
return _c_louvain._MutableVertexPartition_diff_move(self._partition, v, new_comm) | [
" Calculate the difference in the quality function if node ``v`` is\n moved to community ``new_comm``.\n\n Parameters\n ----------\n v\n The node to move.\n\n new_comm\n The community to move to.\n\n Returns\n -------\n float\n Difference in quality function.\n\n Notes\n ... |
Please provide a description of the function:def weight_to_comm(self, v, comm):
return _c_louvain._MutableVertexPartition_weight_to_comm(self._partition, v, comm) | [
" The total number of edges (or sum of weights) from node ``v`` to\n community ``comm``.\n\n See Also\n --------\n :func:`~VertexPartition.MutableVertexPartition.weight_from_comm`\n "
] |
Please provide a description of the function:def weight_from_comm(self, v, comm):
return _c_louvain._MutableVertexPartition_weight_from_comm(self._partition, v, comm) | [
" The total number of edges (or sum of weights) to node ``v`` from\n community ``comm``.\n\n See Also\n --------\n :func:`~VertexPartition.MutableVertexPartition.weight_to_comm`\n "
] |
Please provide a description of the function:def Bipartite(graph, resolution_parameter_01,
resolution_parameter_0 = 0, resolution_parameter_1 = 0,
degree_as_node_size=False, types='type', **kwargs):
if types is not None:
if isinstance(types, str):
types = graph.vs... | [
" Create three layers for bipartite partitions.\n\n This creates three layers for bipartite partition necessary for detecting\n communities in bipartite networks. These three layers should be passed to\n :func:`Optimiser.optimise_partition_multiplex` with\n ``layer_weights=[1,-1,-1]``.\n\n Parameters... |
Please provide a description of the function:def spacing(text):
if len(text) <= 1 or not ANY_CJK.search(text):
return text
new_text = text
# TODO: refactoring
matched = CONVERT_TO_FULLWIDTH_CJK_SYMBOLS_CJK.search(new_text)
while matched:
start, end = matched.span()
new... | [
"\n Perform paranoid text spacing on text.\n "
] |
Please provide a description of the function:def spacing_file(path):
# TODO: read line by line
with open(os.path.abspath(path)) as f:
return spacing_text(f.read()) | [
"\n Perform paranoid text spacing from file.\n "
] |
Please provide a description of the function:def compute(self,
text, # text for which to find the most similar event
lang = "eng"): # language in which the text is written
params = { "lang": lang, "text": text, "topClustersCount": self._nrOfEventsToReturn }
... | [
"\n compute the list of most similar events for the given text\n "
] |
Please provide a description of the function:def getUpdates(self):
# execute the query
ret = self._er.execQuery(self)
if ret and "recentActivityEvents" in ret:
# return the updated information
return ret["recentActivityEvents"]
# or empty
return ... | [
"\n Get the latest new or updated events from Event Registry\n NOTE: call this method exactly once per minute - calling it more frequently will return the same results multiple times,\n calling it less frequently will miss on some results. Results are computed once a minute.\n "
] |
Please provide a description of the function:def annotate(self, text, lang = None, customParams = None):
params = {"lang": lang, "text": text}
if customParams:
params.update(customParams)
return self._er.jsonRequestAnalytics("/api/v1/annotate", params) | [
"\n identify the list of entities and nonentities mentioned in the text\n @param text: input text to annotate\n @param lang: language of the provided document (can be an ISO2 or ISO3 code). If None is provided, the language will be automatically detected\n @param customParams: None or a ... |
Please provide a description of the function:def sentiment(self, text, method = "vocabulary"):
assert method == "vocabulary" or method == "rnn"
endpoint = method == "vocabulary" and "sentiment" or "sentimentRNN"
return self._er.jsonRequestAnalytics("/api/v1/" + endpoint, { "text": text ... | [
"\n determine the sentiment of the provided text in English language\n @param text: input text to categorize\n @param method: method to use to compute the sentiment. possible values are \"vocabulary\" (vocabulary based sentiment analysis)\n and \"rnn\" (neural network based sentiment... |
Please provide a description of the function:def semanticSimilarity(self, text1, text2, distanceMeasure = "cosine"):
return self._er.jsonRequestAnalytics("/api/v1/semanticSimilarity", { "text1": text1, "text2": text2, "distanceMeasure": distanceMeasure }) | [
"\n determine the semantic similarity of the two provided documents\n @param text1: first document to analyze\n @param text2: second document to analyze\n @param distanceMeasure: distance measure to use for comparing two documents. Possible values are \"cosine\" (default) or \"jaccard\"\... |
Please provide a description of the function:def extractArticleInfo(self, url, proxyUrl = None, headers = None, cookies = None):
params = { "url": url }
if proxyUrl:
params["proxyUrl"] = proxyUrl
if headers:
if isinstance(headers, dict):
headers =... | [
"\n extract all available information about an article available at url `url`. Returned information will include\n article title, body, authors, links in the articles, ...\n @param url: article url to extract article information from\n @param proxyUrl: proxy that should be used for downl... |
Please provide a description of the function:def trainTopicOnTweets(self, twitterQuery, useTweetText=True, useIdfNormalization=True,
normalization="linear", maxTweets=2000, maxUsedLinks=500, ignoreConceptTypes=[],
maxConcepts = 20, maxCategories = 10, notifyEmailAddress = None):
... | [
"\n create a new topic and train it using the tweets that match the twitterQuery\n @param twitterQuery: string containing the content to search for. It can be a Twitter user account (using \"@\" prefix or user's Twitter url),\n a hash tag (using \"#\" prefix) or a regular keyword.\n ... |
Please provide a description of the function:def trainTopicGetTrainedTopic(self, uri, maxConcepts = 20, maxCategories = 10,
ignoreConceptTypes=[], idfNormalization = True):
return self._er.jsonRequestAnalytics("/api/v1/trainTopic", { "action": "getTrainedTopic", "uri": uri, "maxConcepts": m... | [
"\n retrieve topic for the topic for which you have already finished training\n @param uri: uri of the topic (obtained by calling trainTopicCreateTopic method)\n @param maxConcepts: number of top concepts to retrieve in the topic\n @param maxCategories: number of top categories to retrie... |
Please provide a description of the function:def createTopicPage1():
topic = TopicPage(er)
topic.addKeyword("renewable energy", 30)
topic.addConcept(er.getConceptUri("biofuel"), 50)
topic.addConcept(er.getConceptUri("solar energy"), 50)
topic.addCategory(er.getCategoryUri("renewable"), 50)
... | [
"\n create a topic page directly\n "
] |
Please provide a description of the function:def createTopicPage2():
topic = TopicPage(er)
topic.addCategory(er.getCategoryUri("renewable"), 50)
topic.addKeyword("renewable energy", 30)
topic.addConcept(er.getConceptUri("biofuel"), 50)
topic.addConcept(er.getConceptUri("solar energy"), 50)
... | [
"\n create a topic page directly, set the article threshold, restrict results to set concepts and keywords\n "
] |
Please provide a description of the function:def count(self, eventRegistry):
self.setRequestedResult(RequestEventArticles(**self.queryParams))
res = eventRegistry.execQuery(self)
if "error" in res:
print(res["error"])
count = res.get(self.queryParams["eventUri"], {})... | [
"\n return the number of articles that match the criteria\n @param eventRegistry: instance of EventRegistry class. used to obtain the necessary data\n "
] |
Please provide a description of the function:def execQuery(self, eventRegistry,
sortBy = "cosSim", sortByAsc = False,
returnInfo = None,
maxItems = -1):
self._er = eventRegistry
self._articlePage = 0
self._totalPages = None
# if we want to ret... | [
"\n @param eventRegistry: instance of EventRegistry class. used to obtain the necessary data\n\n @param sortBy: order in which event articles are sorted. Options: none (no specific sorting), id (internal id), date (published date), cosSim (closeness to event centroid), sourceImportance (manually curat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.