signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def post(self, request, *args, **kwargs):
return_url = request.POST.get('<STR_LIT>', '<STR_LIT:/>')<EOL>terms_ids = request.POST.getlist('<STR_LIT>')<EOL>if not terms_ids: <EOL><INDENT>return HttpResponseRedirect(return_url)<EOL><DEDENT>if DJANGO_VERSION <= (<NUM_LIT:2>, <NUM_LIT:0>, <NUM_LIT:0>):<EOL><INDENT>user_authenticated = request.user.is_authenticated()<EOL><DEDENT>else:<EOL><INDENT>user_authenticated = request.user.is_authenticated<EOL><DEDENT>if user_authenticated:<EOL><INDENT>user = request.user<EOL><DEDENT>else:<EOL><INDENT>if '<STR_LIT>' in request.session:<EOL><INDENT>user_pk = request.session['<STR_LIT>']['<STR_LIT>']['<STR_LIT:user>']['<STR_LIT>']<EOL>user = User.objects.get(id=user_pk)<EOL><DEDENT>else:<EOL><INDENT>return HttpResponseRedirect('<STR_LIT:/>')<EOL><DEDENT><DEDENT>store_ip_address = getattr(settings, '<STR_LIT>', True)<EOL>if store_ip_address:<EOL><INDENT>ip_address = request.META.get(getattr(settings, '<STR_LIT>', DEFAULT_TERMS_IP_HEADER_NAME))<EOL><DEDENT>else:<EOL><INDENT>ip_address = "<STR_LIT>"<EOL><DEDENT>for terms_id in terms_ids:<EOL><INDENT>try:<EOL><INDENT>new_user_terms = UserTermsAndConditions(<EOL>user=user,<EOL>terms=TermsAndConditions.objects.get(pk=int(terms_id)),<EOL>ip_address=ip_address<EOL>)<EOL>new_user_terms.save()<EOL><DEDENT>except IntegrityError: <EOL><INDENT>pass<EOL><DEDENT><DEDENT>return HttpResponseRedirect(return_url)<EOL>
Handles POST request.
f956:c2:m2
def get_context_data(self, **kwargs):
context = super(EmailTermsView, self).get_context_data(**kwargs)<EOL>context['<STR_LIT>'] = getattr(settings, '<STR_LIT>', DEFAULT_TERMS_BASE_TEMPLATE)<EOL>return context<EOL>
Pass additional context data
f956:c3:m0
def get_initial(self):
LOGGER.debug('<STR_LIT>')<EOL>terms = self.get_terms(self.kwargs)<EOL>return_to = self.request.GET.get('<STR_LIT>', '<STR_LIT:/>')<EOL>return {'<STR_LIT>': terms, '<STR_LIT>': return_to}<EOL>
Override of CreateView method, queries for which T&C send, catches returnTo from URL
f956:c3:m1
def form_valid(self, form):
LOGGER.debug('<STR_LIT>')<EOL>template = get_template("<STR_LIT>")<EOL>template_rendered = template.render({"<STR_LIT>": form.cleaned_data.get('<STR_LIT>')})<EOL>LOGGER.debug("<STR_LIT>")<EOL>LOGGER.debug(template_rendered)<EOL>try:<EOL><INDENT>send_mail(form.cleaned_data.get('<STR_LIT>', _('<STR_LIT>')),<EOL>template_rendered,<EOL>settings.DEFAULT_FROM_EMAIL,<EOL>[form.cleaned_data.get('<STR_LIT>')],<EOL>fail_silently=False)<EOL>messages.add_message(self.request, messages.INFO, _("<STR_LIT>"))<EOL><DEDENT>except SMTPException: <EOL><INDENT>messages.add_message(self.request, messages.ERROR, _("<STR_LIT>"))<EOL><DEDENT>self.success_url = form.cleaned_data.get('<STR_LIT>', '<STR_LIT:/>') or '<STR_LIT:/>'<EOL>return super(EmailTermsView, self).form_valid(form)<EOL>
Override of CreateView method, sends the email.
f956:c3:m2
def form_invalid(self, form):
LOGGER.debug("<STR_LIT>")<EOL>messages.add_message(self.request, messages.ERROR, _("<STR_LIT>"))<EOL>return super(EmailTermsView, self).form_invalid(form)<EOL>
Override of CreateView method, logs invalid email form submissions.
f956:c3:m3
def is_path_protected(path):
protected = True<EOL>for exclude_path in TERMS_EXCLUDE_URL_PREFIX_LIST:<EOL><INDENT>if path.startswith(exclude_path):<EOL><INDENT>protected = False<EOL><DEDENT><DEDENT>for contains_path in TERMS_EXCLUDE_URL_CONTAINS_LIST:<EOL><INDENT>if contains_path in path:<EOL><INDENT>protected = False<EOL><DEDENT><DEDENT>if path in TERMS_EXCLUDE_URL_LIST:<EOL><INDENT>protected = False<EOL><DEDENT>if path.startswith(ACCEPT_TERMS_PATH):<EOL><INDENT>protected = False<EOL><DEDENT>return protected<EOL>
returns True if given path is to be protected, otherwise False The path is not to be protected when it appears on: TERMS_EXCLUDE_URL_PREFIX_LIST, TERMS_EXCLUDE_URL_LIST, TERMS_EXCLUDE_URL_CONTAINS_LIST or as ACCEPT_TERMS_PATH
f958:m0
def process_request(self, request):
LOGGER.debug('<STR_LIT>')<EOL>current_path = request.META['<STR_LIT>']<EOL>if DJANGO_VERSION <= (<NUM_LIT:2>, <NUM_LIT:0>, <NUM_LIT:0>):<EOL><INDENT>user_authenticated = request.user.is_authenticated()<EOL><DEDENT>else:<EOL><INDENT>user_authenticated = request.user.is_authenticated<EOL><DEDENT>if user_authenticated and is_path_protected(current_path):<EOL><INDENT>for term in TermsAndConditions.get_active_terms_not_agreed_to(request.user):<EOL><INDENT>qs = request.META['<STR_LIT>']<EOL>current_path += '<STR_LIT:?>' + qs if qs else '<STR_LIT>'<EOL>return redirect_to_terms_accept(current_path, term.slug)<EOL><DEDENT><DEDENT>return None<EOL>
Process each request to app to ensure terms have been accepted
f958:c0:m0
def user_accept_terms(backend, user, uid, social_user=None, *args, **kwargs):
LOGGER.debug('<STR_LIT>')<EOL>if TermsAndConditions.get_active_terms_not_agreed_to(user):<EOL><INDENT>return redirect_to_terms_accept('<STR_LIT:/>')<EOL><DEDENT>else:<EOL><INDENT>return {'<STR_LIT>': social_user, '<STR_LIT:user>': user}<EOL><DEDENT>
Check if the user has accepted the terms and conditions after creation.
f959:m0
def redirect_to_terms_accept(current_path='<STR_LIT:/>', slug='<STR_LIT:default>'):
redirect_url_parts = list(urlparse(ACCEPT_TERMS_PATH))<EOL>if slug != '<STR_LIT:default>':<EOL><INDENT>redirect_url_parts[<NUM_LIT:2>] += slug<EOL><DEDENT>querystring = QueryDict(redirect_url_parts[<NUM_LIT:4>], mutable=True)<EOL>querystring[TERMS_RETURNTO_PARAM] = current_path<EOL>redirect_url_parts[<NUM_LIT:4>] = querystring.urlencode(safe='<STR_LIT:/>')<EOL>return HttpResponseRedirect(urlunparse(redirect_url_parts))<EOL>
Redirect the user to the terms and conditions accept page.
f959:m1
@staticmethod<EOL><INDENT>def get_active(slug=DEFAULT_TERMS_SLUG):<DEDENT>
active_terms = cache.get('<STR_LIT>' + slug)<EOL>if active_terms is None:<EOL><INDENT>try:<EOL><INDENT>active_terms = TermsAndConditions.objects.filter(<EOL>date_active__isnull=False,<EOL>date_active__lte=timezone.now(),<EOL>slug=slug).latest('<STR_LIT>')<EOL>cache.set('<STR_LIT>' + slug, active_terms, TERMS_CACHE_SECONDS)<EOL><DEDENT>except TermsAndConditions.DoesNotExist: <EOL><INDENT>LOGGER.error("<STR_LIT>")<EOL>return None<EOL><DEDENT><DEDENT>return active_terms<EOL>
Finds the latest of a particular terms and conditions
f963:c1:m2
@staticmethod<EOL><INDENT>def get_active_terms_ids():<DEDENT>
active_terms_ids = cache.get('<STR_LIT>')<EOL>if active_terms_ids is None:<EOL><INDENT>active_terms_dict = {}<EOL>active_terms_ids = []<EOL>active_terms_set = TermsAndConditions.objects.filter(date_active__isnull=False, date_active__lte=timezone.now()).order_by('<STR_LIT>')<EOL>for active_terms in active_terms_set:<EOL><INDENT>active_terms_dict[active_terms.slug] = active_terms.id<EOL><DEDENT>active_terms_dict = OrderedDict(sorted(active_terms_dict.items(), key=lambda t: t[<NUM_LIT:0>]))<EOL>for terms in active_terms_dict:<EOL><INDENT>active_terms_ids.append(active_terms_dict[terms])<EOL><DEDENT>cache.set('<STR_LIT>', active_terms_ids, TERMS_CACHE_SECONDS)<EOL><DEDENT>return active_terms_ids<EOL>
Returns a list of the IDs of of all terms and conditions
f963:c1:m3
@staticmethod<EOL><INDENT>def get_active_terms_list():<DEDENT>
active_terms_list = cache.get('<STR_LIT>')<EOL>if active_terms_list is None:<EOL><INDENT>active_terms_list = TermsAndConditions.objects.filter(id__in=TermsAndConditions.get_active_terms_ids()).order_by('<STR_LIT>')<EOL>cache.set('<STR_LIT>', active_terms_list, TERMS_CACHE_SECONDS)<EOL><DEDENT>return active_terms_list<EOL>
Returns all the latest active terms and conditions
f963:c1:m4
@staticmethod<EOL><INDENT>def get_active_terms_not_agreed_to(user):<DEDENT>
if TERMS_EXCLUDE_USERS_WITH_PERM is not None:<EOL><INDENT>if user.has_perm(TERMS_EXCLUDE_USERS_WITH_PERM) and not user.is_superuser:<EOL><INDENT>return []<EOL><DEDENT><DEDENT>not_agreed_terms = cache.get('<STR_LIT>' + user.get_username())<EOL>if not_agreed_terms is None:<EOL><INDENT>try:<EOL><INDENT>LOGGER.debug("<STR_LIT>")<EOL>not_agreed_terms = TermsAndConditions.get_active_terms_list().exclude(<EOL>userterms__in=UserTermsAndConditions.objects.filter(user=user)<EOL>).order_by('<STR_LIT>')<EOL>cache.set('<STR_LIT>' + user.get_username(), not_agreed_terms, TERMS_CACHE_SECONDS)<EOL><DEDENT>except (TypeError, UserTermsAndConditions.DoesNotExist):<EOL><INDENT>return []<EOL><DEDENT><DEDENT>return not_agreed_terms<EOL>
Checks to see if a specified user has agreed to all the latest terms and conditions
f963:c1:m5
def setUp(self):
LOGGER.debug('<STR_LIT>')<EOL>self.su = User.objects.create_superuser('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>self.user1 = User.objects.create_user('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>self.user2 = User.objects.create_user('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>self.user3 = User.objects.create_user('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>self.terms1 = TermsAndConditions.objects.create(id=<NUM_LIT:1>, slug="<STR_LIT>", name="<STR_LIT>",<EOL>text="<STR_LIT>", version_number=<NUM_LIT:1.0>,<EOL>date_active="<STR_LIT>")<EOL>self.terms2 = TermsAndConditions.objects.create(id=<NUM_LIT:2>, slug="<STR_LIT>", name="<STR_LIT>",<EOL>text="<STR_LIT>", version_number=<NUM_LIT>,<EOL>date_active="<STR_LIT>")<EOL>self.terms3 = TermsAndConditions.objects.create(id=<NUM_LIT:3>, slug="<STR_LIT>", name="<STR_LIT>",<EOL>text="<STR_LIT>", version_number=<NUM_LIT>,<EOL>date_active="<STR_LIT>")<EOL>self.terms4 = TermsAndConditions.objects.create(id=<NUM_LIT:4>, slug="<STR_LIT>", name="<STR_LIT>",<EOL>text="<STR_LIT>", version_number=<NUM_LIT>,<EOL>date_active="<STR_LIT>")<EOL>content_type = ContentType.objects.get_for_model(type(self.user3))<EOL>self.skip_perm = Permission.objects.create(content_type=content_type, name='<STR_LIT>', codename='<STR_LIT>')<EOL>self.user3.user_permissions.add(self.skip_perm)<EOL>
Setup for each test
f964:c0:m0
def tearDown(self):
LOGGER.debug('<STR_LIT>')<EOL>User.objects.all().delete()<EOL>TermsAndConditions.objects.all().delete()<EOL>UserTermsAndConditions.objects.all().delete()<EOL>
Teardown for each test
f964:c0:m1
def setUp(self):
self.user1 = User.objects.create_user(<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>self.template_string_1 = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>self.template_string_2 = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>self.template_string_3 = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL>self.terms1 = TermsAndConditions.objects.create(id=<NUM_LIT:1>, slug="<STR_LIT>", name="<STR_LIT>",<EOL>text="<STR_LIT>", version_number=<NUM_LIT:1.0>,<EOL>date_active="<STR_LIT>")<EOL>cache.clear()<EOL>
Setup for each test
f964:c1:m0
def _make_context(self, url):
context = dict()<EOL>context['<STR_LIT>'] = RequestFactory()<EOL>context['<STR_LIT>'].user = self.user1<EOL>context['<STR_LIT>'].META = {'<STR_LIT>': url}<EOL>return context<EOL>
Build Up Context - Used in many tests
f964:c1:m1
def render_template(self, string, context=None):
request = RequestFactory().get('<STR_LIT>')<EOL>request.user = self.user1<EOL>request.context = context or {}<EOL>return Template(string).render(Context({'<STR_LIT>': request}))<EOL>
a helper method to render simplistic test templates
f964:c1:m2
def terms_required(view_func):
@wraps(view_func, assigned=available_attrs(view_func))<EOL>def _wrapped_view(request, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if DJANGO_VERSION <= (<NUM_LIT:2>, <NUM_LIT:0>, <NUM_LIT:0>):<EOL><INDENT>user_authenticated = request.user.is_authenticated()<EOL><DEDENT>else:<EOL><INDENT>user_authenticated = request.user.is_authenticated<EOL><DEDENT>if not user_authenticated or not TermsAndConditions.get_active_terms_not_agreed_to(request.user):<EOL><INDENT>return view_func(request, *args, **kwargs)<EOL><DEDENT>current_path = request.path<EOL>login_url_parts = list(urlparse(ACCEPT_TERMS_PATH))<EOL>querystring = QueryDict(login_url_parts[<NUM_LIT:4>], mutable=True)<EOL>querystring['<STR_LIT>'] = current_path<EOL>login_url_parts[<NUM_LIT:4>] = querystring.urlencode(safe='<STR_LIT:/>')<EOL>return HttpResponseRedirect(urlunparse(login_url_parts))<EOL><DEDENT>return _wrapped_view<EOL>
This decorator checks to see if the user is logged in, and if so, if they have accepted the site terms.
f965:m0
def setUp(self):
load_tag = "<STR_LIT>"<EOL>render_url = "<STR_LIT>"<EOL>self.template = Template("<STR_LIT>".join((load_tag, render_url)))<EOL>self.assets_folder = os.path.join(get_test_directory(), "<STR_LIT>")<EOL>self.image_path = os.path.join(self.assets_folder, "<STR_LIT>")<EOL>with open(self.image_path, "<STR_LIT:rb>") as image_file:<EOL><INDENT>self.image_1 = ImageFile(image_file)<EOL><DEDENT>self.image_1.open()<EOL>self.model = ResizeTestModel(image=self.image_1)<EOL>self.model.save()<EOL>self.image_1.close()<EOL>
Setup the test
f969:c0:m0
def tearDown(self):
self.image_1.close()<EOL>self.remove_dirs(("<STR_LIT>", "<STR_LIT>"))<EOL>
Cleanup some stuff
f969:c0:m1
def setUp(self):
load_tag = "<STR_LIT>"<EOL>render_url = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>self.template = Template("<STR_LIT>".join((load_tag, render_url)))<EOL>self.assets_folder = os.path.join(get_test_directory(), "<STR_LIT>")<EOL>self.image_path_1 = os.path.join(self.assets_folder, "<STR_LIT>")<EOL>self.image_path_2 = os.path.join(self.assets_folder, "<STR_LIT>")<EOL>with open(self.image_path_1, "<STR_LIT:rb>") as image_file:<EOL><INDENT>self.image_1 = ImageFile(image_file)<EOL><DEDENT>with open(self.image_path_2, "<STR_LIT:rb>") as image_file:<EOL><INDENT>self.image_2 = ImageFile(image_file)<EOL><DEDENT>self.image_1.open()<EOL>self.model = ResizeTestModel(image=self.image_1)<EOL>self.model.save()<EOL>self.image_1.close()<EOL>self.image_2.open()<EOL>self.model_2 = ResizeTestModel(image=self.image_2)<EOL>self.model_2.save()<EOL>self.image_2.close()<EOL>
Setup the test
f969:c1:m0
def tearDown(self):
self.image_1.close()<EOL>self.image_2.close()<EOL>self.remove_dirs(("<STR_LIT>", "<STR_LIT>"))<EOL>
Cleanup some stuff
f969:c1:m1
@classmethod<EOL><INDENT>def setUpClass(cls):<DEDENT>
cls.assets_folder = os.path.join(get_test_directory(), "<STR_LIT>")<EOL>cls.image_paths = (<EOL>os.path.join(cls.assets_folder, "<STR_LIT>"),<EOL>os.path.join(cls.assets_folder, "<STR_LIT>"))<EOL>super(ResizeTest, cls).setUpClass()<EOL>
Set up class based
f970:c0:m0
def setUp(self):
for idx, image_path in enumerate(self.image_paths):<EOL><INDENT>with open(image_path, "<STR_LIT:rb>") as image_file:<EOL><INDENT>setattr(self, "<STR_LIT>" % (idx + <NUM_LIT:1>), ImageFile(image_file))<EOL><DEDENT><DEDENT>
Setup the test resources
f970:c0:m1
def tearDown(self):
for idx in range(<NUM_LIT:1>, len(self.image_paths) + <NUM_LIT:1>):<EOL><INDENT>getattr(self, "<STR_LIT>" % idx).close()<EOL><DEDENT>self.remove_dirs(("<STR_LIT>", "<STR_LIT>",))<EOL>
Teardown the test
f970:c0:m2
def _get_storage():
return FileSystemStorage(location="<STR_LIT>",<EOL>base_url="<STR_LIT>")<EOL>
Create a filesystemstorage
f971:m0
@register.simple_tag<EOL>def resize(image, width=None, height=None, crop=False, namespace="<STR_LIT>"):
return resize_lazy(image=image, width=width, height=height, crop=crop,<EOL>namespace=namespace, as_url=True)<EOL>
Returns the url of the resized image
f973:m0
@register.simple_tag<EOL>def conditional_resize(image, ratio, width=None, height=None, upcrop=True,<EOL>namespace="<STR_LIT>"):
aspect = float(image.width) / float(image.height)<EOL>crop = False<EOL>if (aspect > ratio and upcrop) or (aspect <= ratio and not upcrop):<EOL><INDENT>crop = True<EOL><DEDENT>return resize_lazy(image=image, width=width, height=height, crop=crop,<EOL>namespace=namespace, as_url=True)<EOL>
Crop the image based on a ratio If upcrop is true, crops the images that have a higher ratio than the given ratio, if false crops the images that have a lower ratio
f973:m1
def remove_dirs(self, dirs):
for folder in dirs:<EOL><INDENT>try:<EOL><INDENT>shutil.rmtree(os.path.join(self.assets_folder, folder))<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>
Remove some used dirs
f975:c0:m0
def assertResize(self, image, width, height, msg_prefix="<STR_LIT>"):
if msg_prefix:<EOL><INDENT>msg_prefix += "<STR_LIT>"<EOL><DEDENT>aspect = float(width) / float(height)<EOL>image_aspect = float(image.width) / float(image.height)<EOL>if aspect > image_aspect:<EOL><INDENT>if height != image.height:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>" % (height, image.height))<EOL>self.fail(msg)<EOL><DEDENT>if image.width > width:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(width, image.width))<EOL>self.fail(msg)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if width != image.width:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>" % (width, image.width))<EOL>self.fail(msg)<EOL><DEDENT>if image.height > height:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(width, image.width))<EOL>self.fail(msg)<EOL><DEDENT><DEDENT>
Passes if the correct resizing with keep op aspect ratio is done One size should match, another should be smaller
f975:c0:m1
def assertAspectRatio(self, image_1, image_2, decimal_tolerance=<NUM_LIT:2>,<EOL>msg_prefix="<STR_LIT>"):
if msg_prefix:<EOL><INDENT>msg_prefix += "<STR_LIT>"<EOL><DEDENT>ratio_1 = round(float(image_1.width) / float(image_1.height),<EOL>decimal_tolerance)<EOL>ratio_2 = round(float(image_2.width) / float(image_2.height),<EOL>decimal_tolerance)<EOL>if ratio_1 != ratio_2:<EOL><INDENT>msg = "<STR_LIT>" % (ratio_1,<EOL>ratio_2)<EOL>self.fail(msg_prefix + msg)<EOL><DEDENT>
Passes if both images have the same aspect ratio. The number that will be compared, will be rounded to the decimal_tolerance parameter
f975:c0:m2
def assertResizeCrop(self, image, width, height, msg_prefix="<STR_LIT>"):
if msg_prefix:<EOL><INDENT>msg_prefix += "<STR_LIT>"<EOL><DEDENT>if image.width != width:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>" % (msg_prefix, image.width, width))<EOL>self.fail(msg)<EOL><DEDENT>if image.height != height:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>"<STR_LIT>" % (msg_prefix, image.height, height))<EOL>self.fail(msg)<EOL><DEDENT>
A custom assertion to recalculate the target size of an image
f975:c0:m3
def _normalize_params(image, width, height, crop):
if width is None and height is None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if width is None or height is None:<EOL><INDENT>aspect = float(image.width) / float(image.height)<EOL>if crop:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if width is None:<EOL><INDENT>width = int(round(height * aspect))<EOL><DEDENT>else:<EOL><INDENT>height = int(round(width / aspect))<EOL><DEDENT><DEDENT>return (width, height, crop)<EOL>
Normalize params and calculate aspect.
f977:m0
def _get_resized_name(image, width, height, crop, namespace):
path, name = os.path.split(image.name)<EOL>name_part = "<STR_LIT>" % (namespace, width, height)<EOL>if crop:<EOL><INDENT>name_part += "<STR_LIT>"<EOL><DEDENT>return os.path.join(path, name_part, name)<EOL>
Get the name of the resized file when assumed it exists.
f977:m1
def _resize(image, width, height, crop):
ext = os.path.splitext(image.name)[<NUM_LIT:1>].strip("<STR_LIT:.>")<EOL>with Image(file=image, format=ext) as b_image:<EOL><INDENT>if ORIENTATION_TYPES.index(b_image.orientation) > <NUM_LIT:4>:<EOL><INDENT>target_aspect = float(width) / float(height)<EOL>aspect = float(b_image.height) / float(b_image.width)<EOL><DEDENT>else:<EOL><INDENT>target_aspect = float(width) / float(height)<EOL>aspect = float(b_image.width) / float(b_image.height)<EOL><DEDENT>b_image.auto_orient()<EOL>target_aspect = float(width) / float(height)<EOL>aspect = float(b_image.width) / float(b_image.height)<EOL>if ((target_aspect > aspect and not crop) or<EOL>(target_aspect <= aspect and crop)):<EOL><INDENT>target_height = height<EOL>target_width = float(target_height) * aspect<EOL>if crop:<EOL><INDENT>target_left = (float(target_width) - float(width)) / <NUM_LIT:2><EOL>target_left = int(round(target_left))<EOL>target_top = <NUM_LIT:0><EOL><DEDENT>if width >= target_width:<EOL><INDENT>target_width = int(math.ceil(target_width))<EOL><DEDENT>else:<EOL><INDENT>target_width = int(math.floor(target_width))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>target_width = width<EOL>target_height = float(target_width) / aspect<EOL>if crop:<EOL><INDENT>target_top = (float(target_height) - float(height)) / <NUM_LIT:2><EOL>target_top = int(round(target_top))<EOL>target_left = <NUM_LIT:0><EOL><DEDENT>if height >= target_height:<EOL><INDENT>target_height = int(math.ceil(target_height))<EOL><DEDENT>else:<EOL><INDENT>target_height = int(math.floor(target_height))<EOL><DEDENT><DEDENT>b_image.strip()<EOL>b_image.resize(target_width, target_height)<EOL>if crop:<EOL><INDENT>b_image.crop(left=target_left, top=target_top, width=width,<EOL>height=height)<EOL><DEDENT>temp_file = tempfile.TemporaryFile()<EOL>b_image.save(file=temp_file)<EOL>temp_file.seek(<NUM_LIT:0>)<EOL>return temp_file<EOL><DEDENT>
Resize the image with respect to the aspect ratio
f977:m2
def resize(image, width=None, height=None, crop=False):
<EOL>width, height, crop = _normalize_params(image, width, height, crop)<EOL>try:<EOL><INDENT>is_closed = image.closed<EOL>if is_closed:<EOL><INDENT>image.open()<EOL><DEDENT>resized_image = _resize(image, width, height, crop)<EOL><DEDENT>finally:<EOL><INDENT>if is_closed:<EOL><INDENT>image.close()<EOL><DEDENT><DEDENT>return ImageFile(resized_image)<EOL>
Resize an image and return the resized file.
f977:m3
def resize_lazy(image, width=None, height=None, crop=False, force=False,<EOL>namespace="<STR_LIT>", storage=default_storage,<EOL>as_url=False):
<EOL>width, height, crop = _normalize_params(image, width, height, crop)<EOL>name = _get_resized_name(image, width, height, crop, namespace)<EOL>try:<EOL><INDENT>storage = image.storage<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>if force or not storage.exists(name):<EOL><INDENT>resized_image = None<EOL>try:<EOL><INDENT>resized_image = resize(image, width, height, crop)<EOL>name = storage.save(name, resized_image)<EOL><DEDENT>finally:<EOL><INDENT>if resized_image is not None:<EOL><INDENT>resized_image.close()<EOL><DEDENT><DEDENT><DEDENT>if as_url:<EOL><INDENT>return storage.url(name)<EOL><DEDENT>return name<EOL>
Returns the name of the resized file. Returns the url if as_url is True
f977:m4
@contextmanager<EOL>def resized(*args, **kwargs):
resized_image = None<EOL>try:<EOL><INDENT>resized_image = resize(*args, **kwargs)<EOL>yield resized_image<EOL><DEDENT>finally:<EOL><INDENT>if resized_image is not None:<EOL><INDENT>resized_image.close()<EOL><DEDENT><DEDENT>
Auto file closing resize function
f977:m5
def processEventsUntilIdle(eventTimeout=defaultEventTimeout):
if not app.hasPendingEvents():<EOL><INDENT>time.sleep(eventTimeout)<EOL><DEDENT>while app.hasPendingEvents():<EOL><INDENT>while app.hasPendingEvents():<EOL><INDENT>app.processEvents()<EOL><DEDENT>time.sleep(eventTimeout)<EOL><DEDENT>
Process Qt events until the application has not had any events for `eventTimeout` seconds
f985:m1
def tabFileNameChanged(self, tab):
if tab == self.currentTab:<EOL><INDENT>if tab.fileName:<EOL><INDENT>self.setWindowTitle("<STR_LIT>")<EOL>if globalSettings.windowTitleFullPath:<EOL><INDENT>self.setWindowTitle(tab.fileName + '<STR_LIT>')<EOL><DEDENT>self.setWindowFilePath(tab.fileName)<EOL>self.tabWidget.setTabText(self.ind, tab.getBaseName())<EOL>self.tabWidget.setTabToolTip(self.ind, tab.fileName)<EOL>QDir.setCurrent(QFileInfo(tab.fileName).dir().path())<EOL><DEDENT>else:<EOL><INDENT>self.setWindowFilePath('<STR_LIT>')<EOL>self.setWindowTitle(self.tr('<STR_LIT>') + '<STR_LIT>')<EOL><DEDENT>canReload = bool(tab.fileName) and not self.autoSaveActive(tab)<EOL>self.actionSetEncoding.setEnabled(canReload)<EOL>self.actionReload.setEnabled(canReload)<EOL><DEDENT>
Perform all UI state changes that need to be done when the filename of the current tab has changed.
f992:c0:m8
def tabActiveMarkupChanged(self, tab):
if tab == self.currentTab:<EOL><INDENT>markupClass = tab.getActiveMarkupClass()<EOL>dtMarkdown = (markupClass == markups.MarkdownMarkup)<EOL>dtMkdOrReST = dtMarkdown or (markupClass == markups.ReStructuredTextMarkup)<EOL>self.formattingBox.setEnabled(dtMarkdown)<EOL>self.symbolBox.setEnabled(dtMarkdown)<EOL>self.actionUnderline.setEnabled(dtMarkdown)<EOL>self.actionBold.setEnabled(dtMkdOrReST)<EOL>self.actionItalic.setEnabled(dtMkdOrReST)<EOL><DEDENT>
Perform all UI state changes that need to be done when the active markup class of the current tab has changed.
f992:c0:m9
def tabModificationStateChanged(self, tab):
if tab == self.currentTab:<EOL><INDENT>changed = tab.editBox.document().isModified()<EOL>if self.autoSaveActive(tab):<EOL><INDENT>changed = False<EOL><DEDENT>self.actionSave.setEnabled(changed)<EOL>self.setWindowModified(changed)<EOL><DEDENT>
Perform all UI state changes that need to be done when the modification state of the current tab has changed.
f992:c0:m10
def changeIndex(self, ind):
self.currentTab = self.tabWidget.currentWidget()<EOL>editBox = self.currentTab.editBox<EOL>previewState = self.currentTab.previewState<EOL>self.actionUndo.setEnabled(editBox.document().isUndoAvailable())<EOL>self.actionRedo.setEnabled(editBox.document().isRedoAvailable())<EOL>self.actionCopy.setEnabled(editBox.textCursor().hasSelection())<EOL>self.actionCut.setEnabled(editBox.textCursor().hasSelection())<EOL>self.actionPreview.setChecked(previewState >= PreviewLive)<EOL>self.actionLivePreview.setChecked(previewState == PreviewLive)<EOL>self.actionTableMode.setChecked(editBox.tableModeEnabled)<EOL>self.editBar.setEnabled(previewState < PreviewNormal)<EOL>self.ind = ind<EOL>editBox.setFocus(Qt.OtherFocusReason)<EOL>self.tabFileNameChanged(self.currentTab)<EOL>self.tabModificationStateChanged(self.currentTab)<EOL>self.tabActiveMarkupChanged(self.currentTab)<EOL>
This function is called when a different tab is selected. It changes the state of the window to mirror the current state of the newly selected tab. Future changes to this state will be done in response to signals emitted by the tab, to which the window was subscribed when the tab was created. The window is subscribed to all tabs like this, but only the active tab will logically generate these signals. Aside from the above this function also calls the handlers for the other changes that are implied by a tab switch: filename change, modification state change and active markup change.
f992:c0:m13
def getPageSizeByName(self, pageSizeName):
pageSize = None<EOL>lowerCaseNames = {pageSize.lower(): pageSize for pageSize in<EOL>self.availablePageSizes()}<EOL>if pageSizeName.lower() in lowerCaseNames:<EOL><INDENT>pageSize = getattr(QPagedPaintDevice, lowerCaseNames[pageSizeName.lower()])<EOL><DEDENT>return pageSize<EOL>
Returns a validated PageSize instance corresponding to the given name. Returns None if the name is not a valid PageSize.
f992:c0:m58
def availablePageSizes(self):
sizes = [x for x in dir(QPagedPaintDevice)<EOL>if type(getattr(QPagedPaintDevice, x)) == QPagedPaintDevice.PageSize]<EOL>return sizes<EOL>
List available page sizes.
f992:c0:m59
def extendMarkdown(self, md):
md.preprocessors.register(PosMapMarkPreprocessor(md), '<STR_LIT>', <NUM_LIT:50>)<EOL>md.preprocessors.register(PosMapCleanPreprocessor(md), '<STR_LIT>', <NUM_LIT:5>)<EOL>md.parser.blockprocessors.register(PosMapBlockProcessor(md.parser), '<STR_LIT>', <NUM_LIT>)<EOL>orig_codehilite_init = CodeHilite.__init__<EOL>def new_codehilite_init(self, src=None, *args, **kwargs):<EOL><INDENT>src = POSMAP_MARKER_RE.sub('<STR_LIT>', src)<EOL>orig_codehilite_init(self, src=src, *args, **kwargs)<EOL><DEDENT>CodeHilite.__init__ = new_codehilite_init<EOL>if Highlight is not None:<EOL><INDENT>orig_highlight_highlight = Highlight.highlight<EOL>def new_highlight_highlight(self, src, *args, **kwargs):<EOL><INDENT>src = POSMAP_MARKER_RE.sub('<STR_LIT>', src)<EOL>return orig_highlight_highlight(self, src, *args, **kwargs)<EOL><DEDENT>Highlight.highlight = new_highlight_highlight<EOL><DEDENT>
Insert the PosMapExtension blockprocessor before any other extensions to make sure our own markers, inserted by the preprocessor, are removed before any other extensions get confused by them.
f1002:c0:m0
def getActiveMarkupClass(self):
return self.activeMarkupClass<EOL>
Return the currently active markup class for this tab. No objects should be created of this class, it should only be used to retrieve markup class specific information.
f1004:c0:m4
def updateActiveMarkupClass(self):
previousMarkupClass = self.activeMarkupClass<EOL>self.activeMarkupClass = find_markup_class_by_name(globalSettings.defaultMarkup)<EOL>if self._fileName:<EOL><INDENT>markupClass = get_markup_for_file_name(<EOL>self._fileName, return_class=True)<EOL>if markupClass:<EOL><INDENT>self.activeMarkupClass = markupClass<EOL><DEDENT><DEDENT>if self.activeMarkupClass != previousMarkupClass:<EOL><INDENT>self.highlighter.docType = self.activeMarkupClass.name if self.activeMarkupClass else None<EOL>self.highlighter.rehighlight()<EOL>self.activeMarkupChanged.emit()<EOL>self.triggerPreviewUpdate()<EOL><DEDENT>
Update the active markup class based on the default class and the current filename. If the active markup class changes, the highlighter is rerun on the input text, the markup object of this tab is replaced with one of the new class and the activeMarkupChanged signal is emitted.
f1004:c0:m5
def detectFileEncoding(self, fileName):
try:<EOL><INDENT>import chardet<EOL><DEDENT>except ImportError:<EOL><INDENT>return<EOL><DEDENT>with open(fileName, '<STR_LIT:rb>') as inputFile:<EOL><INDENT>raw = inputFile.read(<NUM_LIT>)<EOL><DEDENT>result = chardet.detect(raw)<EOL>if result['<STR_LIT>'] > <NUM_LIT>:<EOL><INDENT>if result['<STR_LIT>'].lower() == '<STR_LIT:ascii>':<EOL><INDENT>return '<STR_LIT:utf-8>'<EOL><DEDENT>return result['<STR_LIT>']<EOL><DEDENT>
Detect content encoding of specific file. It will return None if it can't determine the encoding.
f1004:c0:m15
def openSourceFile(self, fileToOpen):
if self.fileName:<EOL><INDENT>currentExt = splitext(self.fileName)[<NUM_LIT:1>]<EOL>basename, ext = splitext(fileToOpen)<EOL>if ext in ('<STR_LIT>', '<STR_LIT>') and exists(basename + currentExt):<EOL><INDENT>self.p.openFileWrapper(basename + currentExt)<EOL>return basename + currentExt<EOL><DEDENT><DEDENT>if exists(fileToOpen) and get_markup_for_file_name(fileToOpen, return_class=True):<EOL><INDENT>self.p.openFileWrapper(fileToOpen)<EOL>return fileToOpen<EOL><DEDENT>
Finds and opens the source file for link target fileToOpen. When links like [test](test) are clicked, the file test.md is opened. It has to be located next to the current opened file. Relative paths like [test](../test) or [test](folder/test) are also possible.
f1004:c0:m22
def require_auth(function):
@functools.wraps(function)<EOL>def wrapper(self, *args, **kwargs):<EOL><INDENT>if not self.access_token():<EOL><INDENT>raise MissingAccessTokenError<EOL><DEDENT>return function(self, *args, **kwargs)<EOL><DEDENT>return wrapper<EOL>
A decorator that wraps the passed in function and raises exception if access token is missing
f1010:m0
def randomizable(function):
@functools.wraps(function)<EOL>def wrapper(self, *args, **kwargs):<EOL><INDENT>if self.randomize:<EOL><INDENT>self.randomize_headers()<EOL><DEDENT>return function(self, *args, **kwargs)<EOL><DEDENT>return wrapper<EOL>
A decorator which randomizes requests if needed
f1010:m1
@require_auth<EOL><INDENT>def get_profile(self):<DEDENT>
r = self._session.get(API_URL + "<STR_LIT>")<EOL>r.raise_for_status()<EOL>return r.json()<EOL>
Get my own profile
f1010:c4:m6
@randomizable<EOL><INDENT>def get_calendar(self, listing_id, starting_month=datetime.datetime.now().month, starting_year=datetime.datetime.now().year, calendar_months=<NUM_LIT:12>):<DEDENT>
params = {<EOL>'<STR_LIT>': str(starting_year),<EOL>'<STR_LIT>': str(listing_id),<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:count>': str(calendar_months),<EOL>'<STR_LIT>': str(starting_month)<EOL>}<EOL>r = self._session.get(API_URL + "<STR_LIT>", params=params)<EOL>r.raise_for_status()<EOL>return r.json()<EOL>
Get availability calendar for a given listing
f1010:c4:m7
@randomizable<EOL><INDENT>def get_reviews(self, listing_id, offset=<NUM_LIT:0>, limit=<NUM_LIT:20>):<DEDENT>
params = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': str(listing_id),<EOL>'<STR_LIT>': str(offset),<EOL>'<STR_LIT>': '<STR_LIT:all>',<EOL>'<STR_LIT>': str(limit),<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>print(self._session.headers)<EOL>r = self._session.get(API_URL + "<STR_LIT>", params=params)<EOL>r.raise_for_status()<EOL>return r.json()<EOL>
Get reviews for a given listing
f1010:c4:m8
@require_auth<EOL><INDENT>def get_listing_calendar(self, listing_id, starting_date=datetime.datetime.now(), calendar_months=<NUM_LIT:6>):<DEDENT>
params = {<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>starting_date_str = starting_date.strftime("<STR_LIT>")<EOL>ending_date_str = (<EOL>starting_date + datetime.timedelta(days=<NUM_LIT:30>)).strftime("<STR_LIT>")<EOL>r = self._session.get(API_URL + "<STR_LIT>".format(<EOL>str(listing_id), starting_date_str, ending_date_str), params=params)<EOL>r.raise_for_status()<EOL>return r.json()<EOL>
Get host availability calendar for a given listing
f1010:c4:m9
@randomizable<EOL><INDENT>def get_homes(self, query=None, gps_lat=None, gps_lng=None, offset=<NUM_LIT:0>, items_per_grid=<NUM_LIT:8>):<DEDENT>
params = {<EOL>'<STR_LIT>': '<STR_LIT:true>',<EOL>'<STR_LIT:version>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:0>',<EOL>'<STR_LIT>': str(offset),<EOL>'<STR_LIT>': '<STR_LIT:0>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:source>': '<STR_LIT>',<EOL>'<STR_LIT>': str(items_per_grid),<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:false>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>if not query and not (gps_lat and gps_lng):<EOL><INDENT>raise MissingParameterError("<STR_LIT>")<EOL><DEDENT>if query:<EOL><INDENT>params['<STR_LIT>'] = query<EOL><DEDENT>if gps_lat and gps_lng:<EOL><INDENT>params['<STR_LIT>'] = gps_lat<EOL>params['<STR_LIT>'] = gps_lng<EOL><DEDENT>r = self._session.get(API_URL + '<STR_LIT>', params=params)<EOL>r.raise_for_status()<EOL>return r.json()<EOL>
Search listings with * Query (e.g. query="Lisbon, Portugal") or * Location (e.g. gps_lat=55.6123352&gps_lng=37.7117917)
f1010:c4:m16
def connectionMade(self):
self._buffer = b'<STR_LIT>'<EOL>self._queue = {}<EOL>self._stopped = None<EOL>self._tag = <NUM_LIT:0><EOL>
Initializes the protocol.
f1017:c0:m0
def dataReceived(self, data):
size = len(self._buffer) + len(data)<EOL>if size > self.MAX_LENGTH:<EOL><INDENT>self.lengthLimitExceeded(size)<EOL><DEDENT>self._buffer += data<EOL>start = <NUM_LIT:0><EOL>for match in self._pattern.finditer(self._buffer):<EOL><INDENT>end = match.start()<EOL>tag = int(match.group(<NUM_LIT:1>))<EOL>self.responseReceived(self._buffer[start:end], tag)<EOL>start = match.end() + <NUM_LIT:1><EOL><DEDENT>if start:<EOL><INDENT>self._buffer = self._buffer[start:]<EOL><DEDENT>
Parses chunks of bytes into responses. Whenever a complete response is received, this method extracts its payload and calls L{responseReceived} to process it. @param data: A chunk of data representing a (possibly partial) response @type data: C{bytes}
f1017:c0:m1
def responseReceived(self, response, tag):
self._queue.pop(tag).callback(response)<EOL>
Receives some characters of a netstring. Whenever a complete response is received, this method calls the deferred associated with it. @param response: A complete response generated by exiftool. @type response: C{bytes} @param tag: The tag associated with the response @type tag: C{int}
f1017:c0:m2
def lengthLimitExceeded(self, length):
self.transport.loseConnection()<EOL>
Callback invoked when the incomming data would exceed the length limit appended to the buffer. The default implementation disconnects the transport. @param length: The total number of bytes @type length: C{int}
f1017:c0:m3
def execute(self, *args):
result = defer.Deferred()<EOL>if self.connected and not self._stopped:<EOL><INDENT>self._tag += <NUM_LIT:1><EOL>args = tuple(args) + ('<STR_LIT>'.format(self._tag), '<STR_LIT>')<EOL>safe_args = [fsencode(arg) for arg in args]<EOL>self.transport.write(b'<STR_LIT:\n>'.join(safe_args))<EOL>result = defer.Deferred()<EOL>self._queue[self._tag] = result<EOL><DEDENT>else:<EOL><INDENT>result.errback(error.ConnectionClosed('<STR_LIT>'))<EOL><DEDENT>return result<EOL>
Pass one command to exiftool and return a deferred which is fired as soon as the command completes. @param *args: Command line arguments passed to exiftool @type *args: C{unicode} @rtype: C{Deferred} @return: A deferred whose callback will be invoked when the command completed.
f1017:c0:m4
def loseConnection(self):
if self._stopped:<EOL><INDENT>result = self._stopped<EOL><DEDENT>elif self.connected:<EOL><INDENT>result = defer.Deferred()<EOL>self._stopped = result<EOL>self.transport.write(b'<STR_LIT:\n>'.join((b'<STR_LIT>', b'<STR_LIT:False>', b'<STR_LIT>')))<EOL><DEDENT>else:<EOL><INDENT>result = defer.succeed(self)<EOL><DEDENT>return result<EOL>
Close the connection and terminate the exiftool process. @rtype: C{Deferred} @return: A deferred whose callback will be invoked when the connection was closed.
f1017:c0:m5
def connectionLost(self, reason=protocol.connectionDone):
self.connected = <NUM_LIT:0><EOL>for pending in self._queue.values():<EOL><INDENT>pending.errback(reason)<EOL><DEDENT>self._queue.clear()<EOL>if self._stopped:<EOL><INDENT>result = self if reason.check(error.ConnectionDone) else reason<EOL>self._stopped.callback(result)<EOL>self._stopped = None<EOL><DEDENT>else:<EOL><INDENT>reason.raiseException()<EOL><DEDENT>
Check whether termination was intended and invoke the deferred. If the connection terminated unexpectedly, reraise the failure. @type reason: L{twisted.python.failure.Failure}
f1017:c0:m6
def __init__(self, crazyflie):
self.crazyflie = crazyflie<EOL>
:param crazyflie: A crazyflie object to be used as a bridge to the LoPo system.
f1020:c0:m0
def set_position(self, anchor_id, position):
x = position[<NUM_LIT:0>]<EOL>y = position[<NUM_LIT:1>]<EOL>z = position[<NUM_LIT:2>]<EOL>data = struct.pack('<STR_LIT>', LoPoAnchor.LPP_TYPE_POSITION, x, y, z)<EOL>self.crazyflie.loc.send_short_lpp_packet(anchor_id, data)<EOL>
Send a packet with a position to one anchor. :param anchor_id: The id of the targeted anchor. This is the first byte of the anchor address. :param position: The position of the anchor, as an array
f1020:c0:m1
def set_mode(self, anchor_id, mode):
data = struct.pack('<STR_LIT>', LoPoAnchor.LPP_TYPE_MODE, mode)<EOL>self.crazyflie.loc.send_short_lpp_packet(anchor_id, data)<EOL>
Send a packet to set the anchor mode. If the anchor receive the packet, it will change mode and resets.
f1020:c0:m3
def __init__(self, link_uri):
self._cf = Crazyflie(rw_cache='<STR_LIT>')<EOL>self._cf.connected.add_callback(self._connected)<EOL>self._cf.disconnected.add_callback(self._disconnected)<EOL>self._cf.connection_failed.add_callback(self._connection_failed)<EOL>self._cf.connection_lost.add_callback(self._connection_lost)<EOL>print('<STR_LIT>' % link_uri)<EOL>self._cf.open_link(link_uri)<EOL>self.is_connected = True<EOL>
Initialize and run the example with the specified link_uri
f1030:c0:m0
def _connected(self, link_uri):
print('<STR_LIT>' % link_uri)<EOL>self._lg_stab = LogConfig(name='<STR_LIT>', period_in_ms=<NUM_LIT:10>)<EOL>self._lg_stab.add_variable('<STR_LIT>', '<STR_LIT:float>')<EOL>self._lg_stab.add_variable('<STR_LIT>', '<STR_LIT:float>')<EOL>self._lg_stab.add_variable('<STR_LIT>', '<STR_LIT:float>')<EOL>try:<EOL><INDENT>self._cf.log.add_config(self._lg_stab)<EOL>self._lg_stab.data_received_cb.add_callback(self._stab_log_data)<EOL>self._lg_stab.error_cb.add_callback(self._stab_log_error)<EOL>self._lg_stab.start()<EOL><DEDENT>except KeyError as e:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(str(e)))<EOL><DEDENT>except AttributeError:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>t = Timer(<NUM_LIT:5>, self._cf.close_link)<EOL>t.start()<EOL>
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
f1030:c0:m1
def _stab_log_error(self, logconf, msg):
print('<STR_LIT>' % (logconf.name, msg))<EOL>
Callback from the log API when an error occurs
f1030:c0:m2
def _stab_log_data(self, timestamp, data, logconf):
print('<STR_LIT>' % (timestamp, logconf.name, data))<EOL>
Callback froma the log API when data arrives
f1030:c0:m3
def _connection_failed(self, link_uri, msg):
print('<STR_LIT>' % (link_uri, msg))<EOL>self.is_connected = False<EOL>
Callback when connection initial connection fails (i.e no Crazyflie at the speficied address)
f1030:c0:m4
def _connection_lost(self, link_uri, msg):
print('<STR_LIT>' % (link_uri, msg))<EOL>
Callback when disconnected after a connection has been made (i.e Crazyflie moves out of range)
f1030:c0:m5
def _disconnected(self, link_uri):
print('<STR_LIT>' % link_uri)<EOL>self.is_connected = False<EOL>
Callback when the Crazyflie is disconnected (called in all cases)
f1030:c0:m6
def __init__(self, link_uri):
<EOL>self._cf = Crazyflie()<EOL>self._cf.connected.add_callback(self._connected)<EOL>self._cf.disconnected.add_callback(self._disconnected)<EOL>self._cf.connection_failed.add_callback(self._connection_failed)<EOL>self._cf.connection_lost.add_callback(self._connection_lost)<EOL>print('<STR_LIT>' % link_uri)<EOL>self._cf.open_link(link_uri)<EOL>self.is_connected = True<EOL>
Initialize and run the example with the specified link_uri
f1033:c0:m0
def _connected(self, link_uri):
print('<STR_LIT>' % link_uri)<EOL>mems = self._cf.mem.get_mems(MemoryElement.TYPE_1W)<EOL>print('<STR_LIT>'.format(len(mems)))<EOL>if len(mems) > <NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(mems[<NUM_LIT:0>].id))<EOL>mems[<NUM_LIT:0>].vid = <NUM_LIT><EOL>mems[<NUM_LIT:0>].pid = <NUM_LIT><EOL>board_name_id = OWElement.element_mapping[<NUM_LIT:1>]<EOL>board_rev_id = OWElement.element_mapping[<NUM_LIT:2>]<EOL>mems[<NUM_LIT:0>].elements[board_name_id] = '<STR_LIT>'<EOL>mems[<NUM_LIT:0>].elements[board_rev_id] = '<STR_LIT:A>'<EOL>mems[<NUM_LIT:0>].write_data(self._data_written)<EOL><DEDENT>
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
f1033:c0:m1
def _stab_log_error(self, logconf, msg):
print('<STR_LIT>' % (logconf.name, msg))<EOL>
Callback from the log API when an error occurs
f1033:c0:m4
def _stab_log_data(self, timestamp, data, logconf):
print('<STR_LIT>' % (timestamp, logconf.name, data))<EOL>
Callback froma the log API when data arrives
f1033:c0:m5
def _connection_failed(self, link_uri, msg):
print('<STR_LIT>' % (link_uri, msg))<EOL>self.is_connected = False<EOL>
Callback when connection initial connection fails (i.e no Crazyflie at the speficied address)
f1033:c0:m6
def _connection_lost(self, link_uri, msg):
print('<STR_LIT>' % (link_uri, msg))<EOL>
Callback when disconnected after a connection has been made (i.e Crazyflie moves out of range)
f1033:c0:m7
def _disconnected(self, link_uri):
print('<STR_LIT>' % link_uri)<EOL>self.is_connected = False<EOL>
Callback when the Crazyflie is disconnected (called in all cases)
f1033:c0:m8
def choose(items, title_text, question_text):
print(title_text)<EOL>for i, item in enumerate(items, start=<NUM_LIT:1>):<EOL><INDENT>print('<STR_LIT>' % (i, item))<EOL><DEDENT>print('<STR_LIT>' % (i + <NUM_LIT:1>))<EOL>selected = input(question_text)<EOL>try:<EOL><INDENT>index = int(selected)<EOL><DEDENT>except ValueError:<EOL><INDENT>index = -<NUM_LIT:1><EOL><DEDENT>if not (index - <NUM_LIT:1>) in range(len(items)):<EOL><INDENT>print('<STR_LIT>')<EOL>return None<EOL><DEDENT>return items[index - <NUM_LIT:1>]<EOL>
Interactively choose one of the items.
f1036:m0
def scan():
<EOL>cflib.crtp.init_drivers(enable_debug_driver=False)<EOL>print('<STR_LIT>')<EOL>available = cflib.crtp.scan_interfaces()<EOL>interfaces = [uri for uri, _ in available]<EOL>if not interfaces:<EOL><INDENT>return None<EOL><DEDENT>return choose(interfaces, '<STR_LIT>', '<STR_LIT>')<EOL>
Scan for Crazyflie and return its URI.
f1036:m1
def connect(self):
print('<STR_LIT>' % self._link_uri)<EOL>self._cf.open_link(self._link_uri)<EOL>
Connect to the crazyflie.
f1036:c1:m1
def wait_for_connection(self, timeout=<NUM_LIT:10>):
start_time = datetime.datetime.now()<EOL>while True:<EOL><INDENT>if self.connected:<EOL><INDENT>return True<EOL><DEDENT>now = datetime.datetime.now()<EOL>if (now - start_time).total_seconds() > timeout:<EOL><INDENT>return False<EOL><DEDENT>time.sleep(<NUM_LIT:0.5>)<EOL><DEDENT>
Busy loop until connection is established. Will abort after timeout (seconds). Return value is a boolean, whether connection could be established.
f1036:c1:m3
def search_memories(self):
if not self.connected:<EOL><INDENT>raise NotConnected()<EOL><DEDENT>return self._cf.mem.get_mems(MemoryElement.TYPE_1W)<EOL>
Search and return list of 1-wire memories.
f1036:c1:m4
def __init__(self, link_uri):
self._cf = Crazyflie(rw_cache='<STR_LIT>')<EOL>self._cf.connected.add_callback(self._connected)<EOL>self._cf.disconnected.add_callback(self._disconnected)<EOL>self._cf.connection_failed.add_callback(self._connection_failed)<EOL>self._cf.connection_lost.add_callback(self._connection_lost)<EOL>self._cf.open_link(link_uri)<EOL>print('<STR_LIT>' % link_uri)<EOL>
Initialize and run the example with the specified link_uri
f1037:c0:m0
def _connected(self, link_uri):
<EOL>Thread(target=self._ramp_motors).start()<EOL>
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
f1037:c0:m1
def _connection_failed(self, link_uri, msg):
print('<STR_LIT>' % (link_uri, msg))<EOL>
Callback when connection initial connection fails (i.e no Crazyflie at the specified address)
f1037:c0:m2
def _connection_lost(self, link_uri, msg):
print('<STR_LIT>' % (link_uri, msg))<EOL>
Callback when disconnected after a connection has been made (i.e Crazyflie moves out of range)
f1037:c0:m3
def _disconnected(self, link_uri):
print('<STR_LIT>' % link_uri)<EOL>
Callback when the Crazyflie is disconnected (called in all cases)
f1037:c0:m4
def __init__(self, link_uri):
self._cf = Crazyflie()<EOL>self._cf.connected.add_callback(self._connected)<EOL>self._cf.disconnected.add_callback(self._disconnected)<EOL>self._cf.connection_failed.add_callback(self._connection_failed)<EOL>self._cf.connection_lost.add_callback(self._connection_lost)<EOL>self._cf.open_link(link_uri)<EOL>print('<STR_LIT>' % link_uri)<EOL>
Initialize and run the example with the specified link_uri
f1040:c0:m0
def _connected(self, link_uri):
<EOL>Thread(target=self._reboot_thread).start()<EOL>
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
f1040:c0:m1
def _connection_failed(self, link_uri, msg):
print('<STR_LIT>' % (link_uri, msg))<EOL>
Callback when connection initial connection fails (i.e no Crazyflie at the specified address)
f1040:c0:m2
def _connection_lost(self, link_uri, msg):
print('<STR_LIT>' % (link_uri, msg))<EOL>
Callback when disconnected after a connection has been made (i.e Crazyflie moves out of range)
f1040:c0:m3
def _disconnected(self, link_uri):
print('<STR_LIT>' % link_uri)<EOL>
Callback when the Crazyflie is disconnected (called in all cases)
f1040:c0:m4
def __init__(self, link_uri):
<EOL>self._cf = Crazyflie()<EOL>self._cf.connected.add_callback(self._connected)<EOL>self._cf.disconnected.add_callback(self._disconnected)<EOL>self._cf.connection_failed.add_callback(self._connection_failed)<EOL>self._cf.connection_lost.add_callback(self._connection_lost)<EOL>print('<STR_LIT>' % link_uri)<EOL>self._cf.open_link(link_uri)<EOL>self.is_connected = True<EOL>
Initialize and run the example with the specified link_uri
f1041:c0:m0
def _connected(self, link_uri):
print('<STR_LIT>' % link_uri)<EOL>mems = self._cf.mem.get_mems(MemoryElement.TYPE_I2C)<EOL>print('<STR_LIT>'.format(len(mems)))<EOL>if len(mems) > <NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT>'<EOL>'<STR_LIT>'.format(mems[<NUM_LIT:0>].id))<EOL>elems = mems[<NUM_LIT:0>].elements<EOL>elems['<STR_LIT:version>'] = <NUM_LIT:1><EOL>elems['<STR_LIT>'] = <NUM_LIT:0.0><EOL>elems['<STR_LIT>'] = <NUM_LIT:0.0><EOL>elems['<STR_LIT>'] = <NUM_LIT><EOL>elems['<STR_LIT>'] = <NUM_LIT:0><EOL>elems['<STR_LIT>'] = <NUM_LIT><EOL>mems[<NUM_LIT:0>].write_data(self._data_written)<EOL><DEDENT>
This callback is called form the Crazyflie API when a Crazyflie has been connected and the TOCs have been downloaded.
f1041:c0:m1
def _stab_log_error(self, logconf, msg):
print('<STR_LIT>' % (logconf.name, msg))<EOL>
Callback from the log API when an error occurs
f1041:c0:m4