{"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/views.py","language":"python","identifier":"update_parent_location_list","parameters":"(location)","argument_list":"","return_statement":"","docstring":"Update cached sublocations for added or removed location parent.","docstring_summary":"Update cached sublocations for added or removed location parent.","docstring_tokens":["Update","cached","sublocations","for","added","or","removed","location","parent","."],"function":"def update_parent_location_list(location):\n \"\"\" Update cached sublocations for added or removed location parent. \"\"\"\n if location.parent is not None and settings.USE_CACHE:\n for language in [x[0] for x in settings.LANGUAGES]:\n key = \"{}_{}_sub\".format(location.parent.slug, language)\n redis_cache.set(key, location.parent.location_set.all())","function_tokens":["def","update_parent_location_list","(","location",")",":","if","location",".","parent","is","not","None","and","settings",".","USE_CACHE",":","for","language","in","[","x","[","0","]","for","x","in","settings",".","LANGUAGES","]",":","key","=","\"{}_{}_sub\"",".","format","(","location",".","parent",".","slug",",","language",")","redis_cache",".","set","(","key",",","location",".","parent",".","location_set",".","all","(",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/views.py#L69-L74"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/views.py","language":"python","identifier":"LocationListView.get","parameters":"(self, request)","argument_list":"","return_statement":"return super(LocationListView, self).get(request)","docstring":"Returns results for autocomplete widget.","docstring_summary":"Returns results for autocomplete widget.","docstring_tokens":["Returns","results","for","autocomplete","widget","."],"function":"def get(self, request):\n \"\"\" Returns results for autocomplete widget. \"\"\"\n if request.is_ajax():\n fields = ('id', 'name', 'slug', 'parent', 'country_code',)\n term = request.GET.get('term', '')\n locations = self.model.objects.filter(name__icontains=term)\n context = serializers.serialize(\"json\", locations, fields=fields)\n return HttpResponse(context, content_type=\"application\/json\")\n return super(LocationListView, self).get(request)","function_tokens":["def","get","(","self",",","request",")",":","if","request",".","is_ajax","(",")",":","fields","=","(","'id'",",","'name'",",","'slug'",",","'parent'",",","'country_code'",",",")","term","=","request",".","GET",".","get","(","'term'",",","''",")","locations","=","self",".","model",".","objects",".","filter","(","name__icontains","=","term",")","context","=","serializers",".","serialize","(","\"json\"",",","locations",",","fields","=","fields",")","return","HttpResponse","(","context",",","content_type","=","\"application\/json\"",")","return","super","(","LocationListView",",","self",")",".","get","(","request",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/views.py#L491-L499"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/views.py","language":"python","identifier":"InviteUsersView.get_object","parameters":"(self, pk)","argument_list":"","return_statement":"return self.object","docstring":"Get location object from db.","docstring_summary":"Get location object from db.","docstring_tokens":["Get","location","object","from","db","."],"function":"def get_object(self, pk):\n \"\"\" Get location object from db. \"\"\"\n if not self.object:\n self.object = Location.objects.get(pk=pk)\n return self.object","function_tokens":["def","get_object","(","self",",","pk",")",":","if","not","self",".","object",":","self",".","object","=","Location",".","objects",".","get","(","pk","=","pk",")","return","self",".","object"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/views.py#L788-L792"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/views.py","language":"python","identifier":"InviteUsersView.get","parameters":"(self, request, pk)","argument_list":"","return_statement":"return render(request, self.template_name, {\n 'location': location,\n 'form': form,\n })","docstring":"Create invite form.","docstring_summary":"Create invite form.","docstring_tokens":["Create","invite","form","."],"function":"def get(self, request, pk):\n \"\"\" Create invite form. \"\"\"\n location = self.get_object(pk)\n form = InviteUsersForm(initial={'location': location})\n return render(request, self.template_name, {\n 'location': location,\n 'form': form,\n })","function_tokens":["def","get","(","self",",","request",",","pk",")",":","location","=","self",".","get_object","(","pk",")","form","=","InviteUsersForm","(","initial","=","{","'location'",":","location","}",")","return","render","(","request",",","self",".","template_name",",","{","'location'",":","location",",","'form'",":","form",",","}",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/views.py#L794-L801"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/views.py","language":"python","identifier":"InviteUsersView.post","parameters":"(self, request, pk)","argument_list":"","return_statement":"return HttpResponse(json.dumps(ctx))","docstring":"Send message to selected users.","docstring_summary":"Send message to selected users.","docstring_tokens":["Send","message","to","selected","users","."],"function":"def post(self, request, pk):\n \"\"\" Send message to selected users. \"\"\"\n users = request.POST.getlist('user[]')\n if users:\n for u in users:\n user = User.objects.get(pk=u)\n translation.activate(user.profile.lang)\n # Send email\n email = mails.InviteUsersMail()\n email.send(user.email, {\n 'inviting_user': request.user,\n 'location': self.get_object(pk),\n })\n # Record action for actstream\n action.send(\n request.user,\n action_object = self.get_object(pk),\n target = user,\n verb = _(\"invited you to follow\")\n )\n ctx = {\n 'success': True,\n 'message': _(\"Successfully send invitation\"),\n 'level' : 'success',\n }\n else:\n ctx = {\n 'success': False,\n 'message': _(\"User field cannot be empty\"),\n 'level' : 'danger',\n }\n return HttpResponse(json.dumps(ctx))","function_tokens":["def","post","(","self",",","request",",","pk",")",":","users","=","request",".","POST",".","getlist","(","'user[]'",")","if","users",":","for","u","in","users",":","user","=","User",".","objects",".","get","(","pk","=","u",")","translation",".","activate","(","user",".","profile",".","lang",")","# Send email","email","=","mails",".","InviteUsersMail","(",")","email",".","send","(","user",".","email",",","{","'inviting_user'",":","request",".","user",",","'location'",":","self",".","get_object","(","pk",")",",","}",")","# Record action for actstream","action",".","send","(","request",".","user",",","action_object","=","self",".","get_object","(","pk",")",",","target","=","user",",","verb","=","_","(","\"invited you to follow\"",")",")","ctx","=","{","'success'",":","True",",","'message'",":","_","(","\"Successfully send invitation\"",")",",","'level'",":","'success'",",","}","else",":","ctx","=","{","'success'",":","False",",","'message'",":","_","(","\"User field cannot be empty\"",")",",","'level'",":","'danger'",",","}","return","HttpResponse","(","json",".","dumps","(","ctx",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/views.py#L803-L834"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/loader.py","language":"python","identifier":"get_translation","parameters":"(geonameid, country_code)","argument_list":"","return_statement":"return translation","docstring":"Get native translations for geo name objects.","docstring_summary":"Get native translations for geo name objects.","docstring_tokens":["Get","native","translations","for","geo","name","objects","."],"function":"def get_translation(geonameid, country_code):\n \"\"\" Get native translations for geo name objects. \"\"\"\n translation = None\n try:\n c = CountryInfo.objects.get(code=country_code)\n lang = c.languages.split(',')[0].split('-')[0]\n except CountryInfo.DoesNotExist:\n lang = None\n if lang is not None:\n try:\n translation = AltName.objects.filter(geonameid=geonameid, language=lang)\n translation = translation[0].altername\n except IndexError:\n translation = None\n return translation","function_tokens":["def","get_translation","(","geonameid",",","country_code",")",":","translation","=","None","try",":","c","=","CountryInfo",".","objects",".","get","(","code","=","country_code",")","lang","=","c",".","languages",".","split","(","','",")","[","0","]",".","split","(","'-'",")","[","0","]","except","CountryInfo",".","DoesNotExist",":","lang","=","None","if","lang","is","not","None",":","try",":","translation","=","AltName",".","objects",".","filter","(","geonameid","=","geonameid",",","language","=","lang",")","translation","=","translation","[","0","]",".","altername","except","IndexError",":","translation","=","None","return","translation"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/loader.py#L16-L30"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/loader.py","language":"python","identifier":"load_region_data","parameters":"(region, r_location)","argument_list":"","return_statement":"","docstring":"This function takes AdminCode model instance as argument and creates city\n objects for entire region, excluding city districts. Additionally function\n takes location made based on region as argument to pass as parent for\n created cities.","docstring_summary":"This function takes AdminCode model instance as argument and creates city\n objects for entire region, excluding city districts. Additionally function\n takes location made based on region as argument to pass as parent for\n created cities.","docstring_tokens":["This","function","takes","AdminCode","model","instance","as","argument","and","creates","city","objects","for","entire","region","excluding","city","districts",".","Additionally","function","takes","location","made","based","on","region","as","argument","to","pass","as","parent","for","created","cities","."],"function":"def load_region_data(region, r_location):\n \"\"\"\n This function takes AdminCode model instance as argument and creates city\n objects for entire region, excluding city districts. Additionally function\n takes location made based on region as argument to pass as parent for\n created cities.\n \"\"\"\n city = GeoName.objects.filter(admin1=region.code, country=region.country)\n # Country capital region\n main = city.filter(feature_code='PPLC')\n # Regular admin region (e.g. state or voivodeship)\n if not main.count(): main = city.filter(feature_code='PPLA')\n forbidden = [x.admin2 for x in main]\n bad_codes = ['PPLX','PPLC','PPLA']\n city = city.exclude(admin2__in=forbidden).exclude(feature_code__in=bad_codes)\n # Get back main city removed by former query\n city = city | main\n for c in city:\n try:\n chk = Location.objects.get(pk=c.pk)\n logging.info(\"Location already exists: %s. Skipping\", chk.name)\n continue\n except Location.DoesNotExist:\n pass\n\n try:\n trans = get_translation(c.pk, region.country)\n if trans is None: trans = c.name\n nl = Location.objects.create(\n id = c.pk,\n name = trans,\n creator = admin,\n kind = c.feature_code,\n parent = r_location,\n latitude = c.latitude,\n longitude = c.longitude,\n country_code = c.country,\n population = c.population\n )\n nl.save()\n logging.info(\"Created location: %s\", nl.name)\n except Exception as ex:\n logging.error(\"Error creating location: %s - %s\", c.name, repr(ex))","function_tokens":["def","load_region_data","(","region",",","r_location",")",":","city","=","GeoName",".","objects",".","filter","(","admin1","=","region",".","code",",","country","=","region",".","country",")","# Country capital region","main","=","city",".","filter","(","feature_code","=","'PPLC'",")","# Regular admin region (e.g. state or voivodeship)","if","not","main",".","count","(",")",":","main","=","city",".","filter","(","feature_code","=","'PPLA'",")","forbidden","=","[","x",".","admin2","for","x","in","main","]","bad_codes","=","[","'PPLX'",",","'PPLC'",",","'PPLA'","]","city","=","city",".","exclude","(","admin2__in","=","forbidden",")",".","exclude","(","feature_code__in","=","bad_codes",")","# Get back main city removed by former query","city","=","city","|","main","for","c","in","city",":","try",":","chk","=","Location",".","objects",".","get","(","pk","=","c",".","pk",")","logging",".","info","(","\"Location already exists: %s. Skipping\"",",","chk",".","name",")","continue","except","Location",".","DoesNotExist",":","pass","try",":","trans","=","get_translation","(","c",".","pk",",","region",".","country",")","if","trans","is","None",":","trans","=","c",".","name","nl","=","Location",".","objects",".","create","(","id","=","c",".","pk",",","name","=","trans",",","creator","=","admin",",","kind","=","c",".","feature_code",",","parent","=","r_location",",","latitude","=","c",".","latitude",",","longitude","=","c",".","longitude",",","country_code","=","c",".","country",",","population","=","c",".","population",")","nl",".","save","(",")","logging",".","info","(","\"Created location: %s\"",",","nl",".","name",")","except","Exception","as","ex",":","logging",".","error","(","\"Error creating location: %s - %s\"",",","c",".","name",",","repr","(","ex",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/loader.py#L33-L75"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/loader.py","language":"python","identifier":"load_country_data","parameters":"(code)","argument_list":"","return_statement":"","docstring":"This function takes existing country code as argument and creates\n hierarchy - country\/district\/cities.","docstring_summary":"This function takes existing country code as argument and creates\n hierarchy - country\/district\/cities.","docstring_tokens":["This","function","takes","existing","country","code","as","argument","and","creates","hierarchy","-","country","\/","district","\/","cities","."],"function":"def load_country_data(code):\n \"\"\" \n This function takes existing country code as argument and creates\n hierarchy - country\/district\/cities.\n \"\"\"\n code = code.upper()\n country_info = CountryInfo.objects.get(code=code)\n regions_info = AdminCode.objects.filter(country=code)\n # Create location for country\n try:\n l = Location.objects.get(pk=country_info.pk)\n logging.info(\"Location already exists: %s. Skipping\", l.name)\n except Location.DoesNotExist:\n trans = get_translation(country_info.pk, code)\n if trans is None: trans = country_info.name\n l = Location.objects.create(\n id = country_info.pk,\n name = trans,\n kind = 'country',\n country_code = country_info.code,\n creator = admin,\n population = country_info.population\n )\n l.save()\n logging.info(\"Created country location: %s\", l.name)\n # Create related country instance\n try:\n l_country = Country.objects.get(location=l)\n logging.info(\"Related country already exists: %s. Skipping\", l.name)\n except Country.DoesNotExist:\n l_country = Country.objects.create(code=code, location=l)\n l_country.save()\n logging.info(\"Created related country: %s\", l.name)\n # Create location for every admin area and load cities\n for region in regions_info:\n try:\n nl = Location.objects.get(pk=region.pk)\n logging.info(\"Region already exists: %s. Skipping.\", nl.name)\n except Location.DoesNotExist:\n trans = get_translation(region.pk, region.country)\n if trans is None: trans = region.name\n nl = Location.objects.create(\n id = region.pk,\n name = trans,\n kind = 'region',\n country_code = country_info.code,\n parent = l,\n creator = admin\n )\n nl.save()\n logging.info(\"Created region location: %s\", nl.name)\n load_region_data(region, nl)","function_tokens":["def","load_country_data","(","code",")",":","code","=","code",".","upper","(",")","country_info","=","CountryInfo",".","objects",".","get","(","code","=","code",")","regions_info","=","AdminCode",".","objects",".","filter","(","country","=","code",")","# Create location for country","try",":","l","=","Location",".","objects",".","get","(","pk","=","country_info",".","pk",")","logging",".","info","(","\"Location already exists: %s. Skipping\"",",","l",".","name",")","except","Location",".","DoesNotExist",":","trans","=","get_translation","(","country_info",".","pk",",","code",")","if","trans","is","None",":","trans","=","country_info",".","name","l","=","Location",".","objects",".","create","(","id","=","country_info",".","pk",",","name","=","trans",",","kind","=","'country'",",","country_code","=","country_info",".","code",",","creator","=","admin",",","population","=","country_info",".","population",")","l",".","save","(",")","logging",".","info","(","\"Created country location: %s\"",",","l",".","name",")","# Create related country instance","try",":","l_country","=","Country",".","objects",".","get","(","location","=","l",")","logging",".","info","(","\"Related country already exists: %s. Skipping\"",",","l",".","name",")","except","Country",".","DoesNotExist",":","l_country","=","Country",".","objects",".","create","(","code","=","code",",","location","=","l",")","l_country",".","save","(",")","logging",".","info","(","\"Created related country: %s\"",",","l",".","name",")","# Create location for every admin area and load cities","for","region","in","regions_info",":","try",":","nl","=","Location",".","objects",".","get","(","pk","=","region",".","pk",")","logging",".","info","(","\"Region already exists: %s. Skipping.\"",",","nl",".","name",")","except","Location",".","DoesNotExist",":","trans","=","get_translation","(","region",".","pk",",","region",".","country",")","if","trans","is","None",":","trans","=","region",".","name","nl","=","Location",".","objects",".","create","(","id","=","region",".","pk",",","name","=","trans",",","kind","=","'region'",",","country_code","=","country_info",".","code",",","parent","=","l",",","creator","=","admin",")","nl",".","save","(",")","logging",".","info","(","\"Created region location: %s\"",",","nl",".","name",")","load_region_data","(","region",",","nl",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/loader.py#L78-L129"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/loader.py","language":"python","identifier":"load_translation_data","parameters":"(location_pk=None)","argument_list":"","return_statement":"","docstring":"This function updates location translations for registered languages.","docstring_summary":"This function updates location translations for registered languages.","docstring_tokens":["This","function","updates","location","translations","for","registered","languages","."],"function":"def load_translation_data(location_pk=None):\n \"\"\" This function updates location translations for registered languages. \"\"\"\n langs = [x[0] for x in settings.LANGUAGES]\n if location_pk is not None:\n queryset = Location.objects.filter(pk=location_pk)\n else:\n queryset = Location.objects.all()\n for l in queryset:\n alt = AltName.objects.filter(geonameid=l.pk,\n language__in=langs)\n for a in alt:\n try:\n chk = l.names.get(pk=a.pk)\n logging.info(\"Translation %s exists. Skipping\", a.pk)\n except AlterLocationName.DoesNotExist:\n alt_name = AlterLocationName.objects.create(\n altername = a.altername,\n language = a.language,\n )\n alt_name.save()\n l.names.add(alt_name)\n l.save()\n logging.info(\"Created translation %s for %s\",\n alt_name.language, l.pk)","function_tokens":["def","load_translation_data","(","location_pk","=","None",")",":","langs","=","[","x","[","0","]","for","x","in","settings",".","LANGUAGES","]","if","location_pk","is","not","None",":","queryset","=","Location",".","objects",".","filter","(","pk","=","location_pk",")","else",":","queryset","=","Location",".","objects",".","all","(",")","for","l","in","queryset",":","alt","=","AltName",".","objects",".","filter","(","geonameid","=","l",".","pk",",","language__in","=","langs",")","for","a","in","alt",":","try",":","chk","=","l",".","names",".","get","(","pk","=","a",".","pk",")","logging",".","info","(","\"Translation %s exists. Skipping\"",",","a",".","pk",")","except","AlterLocationName",".","DoesNotExist",":","alt_name","=","AlterLocationName",".","objects",".","create","(","altername","=","a",".","altername",",","language","=","a",".","language",",",")","alt_name",".","save","(",")","l",".","names",".","add","(","alt_name",")","l",".","save","(",")","logging",".","info","(","\"Created translation %s for %s\"",",","alt_name",".","language",",","l",".","pk",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/loader.py#L132-L155"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/loader.py","language":"python","identifier":"load","parameters":"()","argument_list":"","return_statement":"","docstring":"Loads entire data set for places above 1000 population.","docstring_summary":"Loads entire data set for places above 1000 population.","docstring_tokens":["Loads","entire","data","set","for","places","above","1000","population","."],"function":"def load():\n \"\"\" Loads entire data set for places above 1000 population. \"\"\"\n for country in CountryInfo.objects.all():\n load_country_data(country.code)","function_tokens":["def","load","(",")",":","for","country","in","CountryInfo",".","objects",".","all","(",")",":","load_country_data","(","country",".","code",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/loader.py#L158-L161"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/helpers.py","language":"python","identifier":"get_nearest_city","parameters":"(lat, lng)","argument_list":"","return_statement":"","docstring":"Find nearest big city for given latitude and longitude.","docstring_summary":"Find nearest big city for given latitude and longitude.","docstring_tokens":["Find","nearest","big","city","for","given","latitude","and","longitude","."],"function":"def get_nearest_city(lat, lng):\n \"\"\" Find nearest big city for given latitude and longitude.\n \"\"\"\n qs = Location.objects.filter(latitude__gte=lat-1,\n latitude__lte=lat+1,\n longitude__gte=lng-1,\n longitude__lte=lng+1)\n try:\n return qs.order_by('-population')[0]\n except IndexError:\n return None","function_tokens":["def","get_nearest_city","(","lat",",","lng",")",":","qs","=","Location",".","objects",".","filter","(","latitude__gte","=","lat","-","1",",","latitude__lte","=","lat","+","1",",","longitude__gte","=","lng","-","1",",","longitude__lte","=","lng","+","1",")","try",":","return","qs",".","order_by","(","'-population'",")","[","0","]","except","IndexError",":","return","None"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/helpers.py#L11-L21"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/helpers.py","language":"python","identifier":"get_most_followed","parameters":"(country_code=None, limit=20)","argument_list":"","return_statement":"return main + full","docstring":"We download a list of the most often followed location. We can narrow\n the list to a certain country, to do so, we first type in the country\n and its capital city. it returns a LIST, not a QuerySet!","docstring_summary":"We download a list of the most often followed location. We can narrow\n the list to a certain country, to do so, we first type in the country\n and its capital city. it returns a LIST, not a QuerySet!","docstring_tokens":["We","download","a","list","of","the","most","often","followed","location",".","We","can","narrow","the","list","to","a","certain","country","to","do","so","we","first","type","in","the","country","and","its","capital","city",".","it","returns","a","LIST","not","a","QuerySet!"],"function":"def get_most_followed(country_code=None, limit=20):\n \"\"\"\n We download a list of the most often followed location. We can narrow\n the list to a certain country, to do so, we first type in the country\n and its capital city. it returns a LIST, not a QuerySet!\n \"\"\"\n qs = Location.objects\n kinds = ['PPLC', 'country',]\n if country_code is None:\n return list(qs.all().order_by('users')[:limit])\n main = list(qs.filter(country_code=country_code,\n kind__in=kinds).order_by('kind'))\n full = list(qs.annotate(num_users=Count('users'))\\\n .filter(country_code=country_code)\\\n .exclude(kind__in=kinds)\\\n .order_by('-num_users')[:limit-len(main)])\n return main + full","function_tokens":["def","get_most_followed","(","country_code","=","None",",","limit","=","20",")",":","qs","=","Location",".","objects","kinds","=","[","'PPLC'",",","'country'",",","]","if","country_code","is","None",":","return","list","(","qs",".","all","(",")",".","order_by","(","'users'",")","[",":","limit","]",")","main","=","list","(","qs",".","filter","(","country_code","=","country_code",",","kind__in","=","kinds",")",".","order_by","(","'kind'",")",")","full","=","list","(","qs",".","annotate","(","num_users","=","Count","(","'users'",")",")",".","filter","(","country_code","=","country_code",")",".","exclude","(","kind__in","=","kinds",")",".","order_by","(","'-num_users'",")","[",":","limit","-","len","(","main",")","]",")","return","main","+","full"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/helpers.py#L24-L40"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/helpers.py","language":"python","identifier":"move_location_contents","parameters":"(old_location, new_location)","argument_list":"","return_statement":"","docstring":"This method helps us move contents between locations, mainly, if we want\n to delete one location but save contents in other one. It takes two location\n instances as arguments and move content from first to second of them.","docstring_summary":"This method helps us move contents between locations, mainly, if we want\n to delete one location but save contents in other one. It takes two location\n instances as arguments and move content from first to second of them.","docstring_tokens":["This","method","helps","us","move","contents","between","locations","mainly","if","we","want","to","delete","one","location","but","save","contents","in","other","one",".","It","takes","two","location","instances","as","arguments","and","move","content","from","first","to","second","of","them","."],"function":"def move_location_contents(old_location, new_location):\n \"\"\"\n This method helps us move contents between locations, mainly, if we want\n to delete one location but save contents in other one. It takes two location\n instances as arguments and move content from first to second of them.\n \"\"\"\n content_sets = ['news_set', 'poll_set', 'idea_set',\n 'discussion_set', 'pictures', 'projects',]\n # Get all 'standard' contents from first location and move to second one\n for content_type in content_sets:\n for item in getattr(old_location, content_type).all():\n item.location = new_location\n item.save()\n # Find all old location followers and make them follow new place\n for user in old_location.users.all():\n unfollow(user, old_location)\n if not user in new_location.users.all():\n follow(user, new_location, send_action=False)\n new_location.users.add(user)\n # Find all actions where old location acts as target and bind to new location.\n # This is not really good idea, but I hope it will be sufficient.\n actions = Action.objects.filter(target_object_id=old_location.pk,\n target_content_type=ContentType.objects.get_for_model(Location))\n for action in actions:\n action.target_object_id = new_location.pk\n action.save()","function_tokens":["def","move_location_contents","(","old_location",",","new_location",")",":","content_sets","=","[","'news_set'",",","'poll_set'",",","'idea_set'",",","'discussion_set'",",","'pictures'",",","'projects'",",","]","# Get all 'standard' contents from first location and move to second one","for","content_type","in","content_sets",":","for","item","in","getattr","(","old_location",",","content_type",")",".","all","(",")",":","item",".","location","=","new_location","item",".","save","(",")","# Find all old location followers and make them follow new place","for","user","in","old_location",".","users",".","all","(",")",":","unfollow","(","user",",","old_location",")","if","not","user","in","new_location",".","users",".","all","(",")",":","follow","(","user",",","new_location",",","send_action","=","False",")","new_location",".","users",".","add","(","user",")","# Find all actions where old location acts as target and bind to new location.","# This is not really good idea, but I hope it will be sufficient.","actions","=","Action",".","objects",".","filter","(","target_object_id","=","old_location",".","pk",",","target_content_type","=","ContentType",".","objects",".","get_for_model","(","Location",")",")","for","action","in","actions",":","action",".","target_object_id","=","new_location",".","pk","action",".","save","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/helpers.py#L43-L68"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/helpers.py","language":"python","identifier":"get_followers_from_location","parameters":"(location_pk, deep=False)","argument_list":"","return_statement":"return followers","docstring":"Helper that returns list of all followers from location with given ID.\n If `deep` is set to True, list includes also followers of child locations.","docstring_summary":"Helper that returns list of all followers from location with given ID.\n If `deep` is set to True, list includes also followers of child locations.","docstring_tokens":["Helper","that","returns","list","of","all","followers","from","location","with","given","ID",".","If","deep","is","set","to","True","list","includes","also","followers","of","child","locations","."],"function":"def get_followers_from_location(location_pk, deep=False):\n \"\"\"\n Helper that returns list of all followers from location with given ID.\n If `deep` is set to True, list includes also followers of child locations.\n \"\"\"\n location = Location.objects.get(pk=location_pk)\n followers = list(location.users.all())\n if not deep:\n return followers\n for pk in location.get_children_id_list():\n location = Location.objects.get(pk=pk)\n for user in location.users.all():\n if not user in followers:\n followers.append(user)\n return followers","function_tokens":["def","get_followers_from_location","(","location_pk",",","deep","=","False",")",":","location","=","Location",".","objects",".","get","(","pk","=","location_pk",")","followers","=","list","(","location",".","users",".","all","(",")",")","if","not","deep",":","return","followers","for","pk","in","location",".","get_children_id_list","(",")",":","location","=","Location",".","objects",".","get","(","pk","=","pk",")","for","user","in","location",".","users",".","all","(",")",":","if","not","user","in","followers",":","followers",".","append","(","user",")","return","followers"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/helpers.py#L71-L85"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/models.py","language":"python","identifier":"obj_to_dict","parameters":"(obj)","argument_list":"","return_statement":"return context","docstring":"A helper that changes various types of content into a unified format,\n that will help us show them in templates. Works as a simple serializer.\n *deprecated* - it's much better to use activities app.","docstring_summary":"A helper that changes various types of content into a unified format,\n that will help us show them in templates. Works as a simple serializer.\n *deprecated* - it's much better to use activities app.","docstring_tokens":["A","helper","that","changes","various","types","of","content","into","a","unified","format","that","will","help","us","show","them","in","templates",".","Works","as","a","simple","serializer",".","*","deprecated","*","-","it","s","much","better","to","use","activities","app","."],"function":"def obj_to_dict(obj):\n \"\"\"\n A helper that changes various types of content into a unified format,\n that will help us show them in templates. Works as a simple serializer.\n *deprecated* - it's much better to use activities app.\n \"\"\"\n content_type = ContentType.objects.get_for_model(obj)\n\n context = {\n 'type': content_type.model,\n 'name': capfirst(_(content_type.model)),\n 'slug': obj.slug,\n 'ct': content_type.pk,\n 'pk': obj.pk,\n 'url': obj.get_absolute_url(),\n 'title': obj.__unicode__(),\n 'image': obj.image_url,\n 'thumbnail': obj.thumbnail,\n 'retina_thumbnail': False,\n 'location': obj.location.__unicode__(),\n 'meta': {},\n 'date_created': obj.date_created.isoformat(),\n 'creator': {\n 'id': obj.creator.pk,\n 'url': obj.creator.profile.get_absolute_url(),\n 'img': obj.creator.profile.avatar.url,\n 'name': obj.creator.get_full_name(),\n },\n }\n\n if hasattr(obj,\n 'category') and obj.category is not None and obj.category.pk:\n context.update({\n 'category':\n {'pk': obj.category.pk,\n 'name': obj.category.__unicode__(), }\n })\n\n if hasattr(obj, 'retina_thumbnail') and not obj.has_default_image:\n context['retina_thumbnail'] = obj.retina_thumbnail\n\n if hasattr(obj, 'has_default_image'):\n context['default_image'] = obj.has_default_image\n\n if content_type.model == 'idea':\n context.update({\n 'description': obj.description,\n 'meta': {'votes': obj.get_votes(), }\n })\n\n elif content_type.model == 'poll':\n context.update({'description': obj.question})\n\n elif content_type.model == 'news':\n context.update({'description': obj.content})\n\n elif content_type.model == 'discussion':\n context.update({\n 'description': obj.intro,\n 'meta': {'answers': obj.entry_set.count(), }\n })\n\n elif content_type.model == 'socialproject':\n context['description'] = obj.get_description()\n context['name'] = _(u\"Project\")\n\n else:\n raise Exception(_(u\"Wrong model instance\"))\n context['description'] = truncatewords_html(context['description'], 15)\n return context","function_tokens":["def","obj_to_dict","(","obj",")",":","content_type","=","ContentType",".","objects",".","get_for_model","(","obj",")","context","=","{","'type'",":","content_type",".","model",",","'name'",":","capfirst","(","_","(","content_type",".","model",")",")",",","'slug'",":","obj",".","slug",",","'ct'",":","content_type",".","pk",",","'pk'",":","obj",".","pk",",","'url'",":","obj",".","get_absolute_url","(",")",",","'title'",":","obj",".","__unicode__","(",")",",","'image'",":","obj",".","image_url",",","'thumbnail'",":","obj",".","thumbnail",",","'retina_thumbnail'",":","False",",","'location'",":","obj",".","location",".","__unicode__","(",")",",","'meta'",":","{","}",",","'date_created'",":","obj",".","date_created",".","isoformat","(",")",",","'creator'",":","{","'id'",":","obj",".","creator",".","pk",",","'url'",":","obj",".","creator",".","profile",".","get_absolute_url","(",")",",","'img'",":","obj",".","creator",".","profile",".","avatar",".","url",",","'name'",":","obj",".","creator",".","get_full_name","(",")",",","}",",","}","if","hasattr","(","obj",",","'category'",")","and","obj",".","category","is","not","None","and","obj",".","category",".","pk",":","context",".","update","(","{","'category'",":","{","'pk'",":","obj",".","category",".","pk",",","'name'",":","obj",".","category",".","__unicode__","(",")",",","}","}",")","if","hasattr","(","obj",",","'retina_thumbnail'",")","and","not","obj",".","has_default_image",":","context","[","'retina_thumbnail'","]","=","obj",".","retina_thumbnail","if","hasattr","(","obj",",","'has_default_image'",")",":","context","[","'default_image'","]","=","obj",".","has_default_image","if","content_type",".","model","==","'idea'",":","context",".","update","(","{","'description'",":","obj",".","description",",","'meta'",":","{","'votes'",":","obj",".","get_votes","(",")",",","}","}",")","elif","content_type",".","model","==","'poll'",":","context",".","update","(","{","'description'",":","obj",".","question","}",")","elif","content_type",".","model","==","'news'",":","context",".","update","(","{","'description'",":","obj",".","content","}",")","elif","content_type",".","model","==","'discussion'",":","context",".","update","(","{","'description'",":","obj",".","intro",",","'meta'",":","{","'answers'",":","obj",".","entry_set",".","count","(",")",",","}","}",")","elif","content_type",".","model","==","'socialproject'",":","context","[","'description'","]","=","obj",".","get_description","(",")","context","[","'name'","]","=","_","(","u\"Project\"",")","else",":","raise","Exception","(","_","(","u\"Wrong model instance\"",")",")","context","[","'description'","]","=","truncatewords_html","(","context","[","'description'","]",",","15",")","return","context"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/models.py#L34-L103"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/charts.py","language":"python","identifier":"get_ptr","parameters":"(val, total)","argument_list":"","return_statement":"return int(float(val)\/float(total)*100)","docstring":"Returns approximated percentage value given total and subset count.","docstring_summary":"Returns approximated percentage value given total and subset count.","docstring_tokens":["Returns","approximated","percentage","value","given","total","and","subset","count","."],"function":"def get_ptr(val, total):\n \"\"\" Returns approximated percentage value given total and subset count.\n \"\"\"\n return int(float(val)\/float(total)*100)","function_tokens":["def","get_ptr","(","val",",","total",")",":","return","int","(","float","(","val",")","\/","float","(","total",")","*","100",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/charts.py#L24-L27"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/charts.py","language":"python","identifier":"qs_by_time","parameters":"(qs, current)","argument_list":"","return_statement":"return qs if qs > 0 else None","docstring":"Filter action queryset on daily basis. Pass qs to filter and current\n time to compare to. It returns number or None if count is 0.","docstring_summary":"Filter action queryset on daily basis. Pass qs to filter and current\n time to compare to. It returns number or None if count is 0.","docstring_tokens":["Filter","action","queryset","on","daily","basis",".","Pass","qs","to","filter","and","current","time","to","compare","to",".","It","returns","number","or","None","if","count","is","0","."],"function":"def qs_by_time(qs, current):\n \"\"\" Filter action queryset on daily basis. Pass qs to filter and current\n time to compare to. It returns number or None if count is 0.\n \"\"\"\n qs = qs.filter(timestamp__year=current.year,\n timestamp__month=current.month,\n timestamp__day=current.day).count()\n return qs if qs > 0 else None","function_tokens":["def","qs_by_time","(","qs",",","current",")",":","qs","=","qs",".","filter","(","timestamp__year","=","current",".","year",",","timestamp__month","=","current",".","month",",","timestamp__day","=","current",".","day",")",".","count","(",")","return","qs","if","qs",">","0","else","None"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/charts.py#L30-L37"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/charts.py","language":"python","identifier":"pie_chart","parameters":"(location)","argument_list":"","return_statement":"return json.dumps({\n 'title': location.__unicode__(),\n 'subtitle': _(u\"Published content summary\"),\n 'name': _(u\"Published items\"),\n 'series': {\n (_(u'ideas'), get_ptr(ideas, total), ),\n (_(u'polls'), get_ptr(polls, total), ),\n (_(u'news'), get_ptr(news, total), ),\n (_(u'discussions'), get_ptr(discussions, total), ),\n (_(u'projects'), get_ptr(projects, total), ),\n },\n }, cls=SetEncoder)","docstring":"Pie chart presenting content type items published in selected location.\n Data is prepared to be presented as pie chart, with percentage values.","docstring_summary":"Pie chart presenting content type items published in selected location.\n Data is prepared to be presented as pie chart, with percentage values.","docstring_tokens":["Pie","chart","presenting","content","type","items","published","in","selected","location",".","Data","is","prepared","to","be","presented","as","pie","chart","with","percentage","values","."],"function":"def pie_chart(location):\n \"\"\" Pie chart presenting content type items published in selected location.\n Data is prepared to be presented as pie chart, with percentage values.\n \"\"\"\n ideas = location.idea_set.count()\n polls = location.poll_set.count()\n news = location.news_set.count()\n discussions = location.discussion_set.count()\n projects = location.projects.count()\n total = sum([ideas, polls, discussions, projects, ])\n\n return json.dumps({\n 'title': location.__unicode__(),\n 'subtitle': _(u\"Published content summary\"),\n 'name': _(u\"Published items\"),\n 'series': {\n (_(u'ideas'), get_ptr(ideas, total), ),\n (_(u'polls'), get_ptr(polls, total), ),\n (_(u'news'), get_ptr(news, total), ),\n (_(u'discussions'), get_ptr(discussions, total), ),\n (_(u'projects'), get_ptr(projects, total), ),\n },\n }, cls=SetEncoder)","function_tokens":["def","pie_chart","(","location",")",":","ideas","=","location",".","idea_set",".","count","(",")","polls","=","location",".","poll_set",".","count","(",")","news","=","location",".","news_set",".","count","(",")","discussions","=","location",".","discussion_set",".","count","(",")","projects","=","location",".","projects",".","count","(",")","total","=","sum","(","[","ideas",",","polls",",","discussions",",","projects",",","]",")","return","json",".","dumps","(","{","'title'",":","location",".","__unicode__","(",")",",","'subtitle'",":","_","(","u\"Published content summary\"",")",",","'name'",":","_","(","u\"Published items\"",")",",","'series'",":","{","(","_","(","u'ideas'",")",",","get_ptr","(","ideas",",","total",")",",",")",",","(","_","(","u'polls'",")",",","get_ptr","(","polls",",","total",")",",",")",",","(","_","(","u'news'",")",",","get_ptr","(","news",",","total",")",",",")",",","(","_","(","u'discussions'",")",",","get_ptr","(","discussions",",","total",")",",",")",",","(","_","(","u'projects'",")",",","get_ptr","(","projects",",","total",")",",",")",",","}",",","}",",","cls","=","SetEncoder",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/charts.py#L40-L62"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/charts.py","language":"python","identifier":"actions_chart","parameters":"(location)","argument_list":"","return_statement":"return json.dumps({\n 'title': location.__unicode__(),\n 'subtitle': _(u\"Activity summary\"),\n 'started': str(started),\n 'labels': labels,\n 'series': counters, })","docstring":"Summary of different kinds of actions related to particular location.","docstring_summary":"Summary of different kinds of actions related to particular location.","docstring_tokens":["Summary","of","different","kinds","of","actions","related","to","particular","location","."],"function":"def actions_chart(location):\n \"\"\" Summary of different kinds of actions related to particular location.\n \"\"\"\n content_items = ['ideas', 'polls', 'news', 'discussions', 'projects', ]\n\n content_types = {\n 'ideas': ContentType.objects.get(app_label='ideas', model='idea'),\n 'polls': ContentType.objects.get(app_label='polls', model='poll'),\n 'news': ContentType.objects.get(app_label='blog', model='news'),\n 'discussions': ContentType.objects.get(app_label='topics', model='discussion'),\n 'projects': ContentType.objects.get(app_label='projects', model='socialproject'),\n }\n\n stream = target_stream(location)\n\n started = stream.last().timestamp\n current = started\n maximum = timezone.now() + datetime.timedelta(hours=12)\n\n labels = {\n 'ideas': _(u\"ideas\"),\n 'polls': _(u\"polls\"),\n 'news': _(u\"news\"),\n 'discussions': _(u\"discussions\"),\n 'projects': _(u\"projects\"),\n }\n\n counters = {\n 'ideas': [],\n 'polls': [],\n 'news': [],\n 'discussions': [],\n 'projects': [],\n }\n\n while current < maximum:\n for itm in content_items:\n counters[itm].append(qs_by_time(stream.filter(\n action_object_content_type=content_types[itm]), current))\n current += datetime.timedelta(days=1)\n\n return json.dumps({\n 'title': location.__unicode__(),\n 'subtitle': _(u\"Activity summary\"),\n 'started': str(started),\n 'labels': labels,\n 'series': counters, })","function_tokens":["def","actions_chart","(","location",")",":","content_items","=","[","'ideas'",",","'polls'",",","'news'",",","'discussions'",",","'projects'",",","]","content_types","=","{","'ideas'",":","ContentType",".","objects",".","get","(","app_label","=","'ideas'",",","model","=","'idea'",")",",","'polls'",":","ContentType",".","objects",".","get","(","app_label","=","'polls'",",","model","=","'poll'",")",",","'news'",":","ContentType",".","objects",".","get","(","app_label","=","'blog'",",","model","=","'news'",")",",","'discussions'",":","ContentType",".","objects",".","get","(","app_label","=","'topics'",",","model","=","'discussion'",")",",","'projects'",":","ContentType",".","objects",".","get","(","app_label","=","'projects'",",","model","=","'socialproject'",")",",","}","stream","=","target_stream","(","location",")","started","=","stream",".","last","(",")",".","timestamp","current","=","started","maximum","=","timezone",".","now","(",")","+","datetime",".","timedelta","(","hours","=","12",")","labels","=","{","'ideas'",":","_","(","u\"ideas\"",")",",","'polls'",":","_","(","u\"polls\"",")",",","'news'",":","_","(","u\"news\"",")",",","'discussions'",":","_","(","u\"discussions\"",")",",","'projects'",":","_","(","u\"projects\"",")",",","}","counters","=","{","'ideas'",":","[","]",",","'polls'",":","[","]",",","'news'",":","[","]",",","'discussions'",":","[","]",",","'projects'",":","[","]",",","}","while","current","<","maximum",":","for","itm","in","content_items",":","counters","[","itm","]",".","append","(","qs_by_time","(","stream",".","filter","(","action_object_content_type","=","content_types","[","itm","]",")",",","current",")",")","current","+=","datetime",".","timedelta","(","days","=","1",")","return","json",".","dumps","(","{","'title'",":","location",".","__unicode__","(",")",",","'subtitle'",":","_","(","u\"Activity summary\"",")",",","'started'",":","str","(","started",")",",","'labels'",":","labels",",","'series'",":","counters",",","}",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/charts.py#L80-L126"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/charts.py","language":"python","identifier":"follow_chart","parameters":"(location)","argument_list":"","return_statement":"return json.dumps({\n 'title': location.__unicode__(),\n 'subtitle': _(u\"followers activity\"),\n 'name': _(u\"followers\"),\n 'started': str(started),\n 'series': followers, })","docstring":"Presents timeline data containing target location followers.","docstring_summary":"Presents timeline data containing target location followers.","docstring_tokens":["Presents","timeline","data","containing","target","location","followers","."],"function":"def follow_chart(location):\n \"\"\" Presents timeline data containing target location followers.\n \"\"\"\n qs = Follow.objects.filter(object_id=location.pk,\n content_type=ContentType.objects.get_for_model(location))\n\n started = location.date_created\n current = started\n maximum = timezone.now() + datetime.timedelta(hours=12)\n prev_qs = 0\n\n followers = []\n while current < maximum:\n fqs = qs.filter(started__year=current.year,\n started__month=current.month,\n started__day=current.day).count()\n prev_qs += fqs\n followers.append(prev_qs)\n current += datetime.timedelta(days=1)\n\n return json.dumps({\n 'title': location.__unicode__(),\n 'subtitle': _(u\"followers activity\"),\n 'name': _(u\"followers\"),\n 'started': str(started),\n 'series': followers, })","function_tokens":["def","follow_chart","(","location",")",":","qs","=","Follow",".","objects",".","filter","(","object_id","=","location",".","pk",",","content_type","=","ContentType",".","objects",".","get_for_model","(","location",")",")","started","=","location",".","date_created","current","=","started","maximum","=","timezone",".","now","(",")","+","datetime",".","timedelta","(","hours","=","12",")","prev_qs","=","0","followers","=","[","]","while","current","<","maximum",":","fqs","=","qs",".","filter","(","started__year","=","current",".","year",",","started__month","=","current",".","month",",","started__day","=","current",".","day",")",".","count","(",")","prev_qs","+=","fqs","followers",".","append","(","prev_qs",")","current","+=","datetime",".","timedelta","(","days","=","1",")","return","json",".","dumps","(","{","'title'",":","location",".","__unicode__","(",")",",","'subtitle'",":","_","(","u\"followers activity\"",")",",","'name'",":","_","(","u\"followers\"",")",",","'started'",":","str","(","started",")",",","'series'",":","followers",",","}",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/charts.py#L129-L154"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"locations\/templatetags\/location_tags.py","language":"python","identifier":"current_location_data","parameters":"(context)","argument_list":"","return_statement":"return JSONRenderer().render(s.data)","docstring":"Get data to use in map inputs - set initial center location and zoom.\n This values depends on location's kind and size.","docstring_summary":"Get data to use in map inputs - set initial center location and zoom.\n This values depends on location's kind and size.","docstring_tokens":["Get","data","to","use","in","map","inputs","-","set","initial","center","location","and","zoom",".","This","values","depends","on","location","s","kind","and","size","."],"function":"def current_location_data(context):\n \"\"\" Get data to use in map inputs - set initial center location and zoom.\n This values depends on location's kind and size.\n \"\"\"\n location = context.get('location')\n if location is None:\n return JSONRenderer().render({})\n s = LocationMapDataSerializer(location)\n return JSONRenderer().render(s.data)","function_tokens":["def","current_location_data","(","context",")",":","location","=","context",".","get","(","'location'",")","if","location","is","None",":","return","JSONRenderer","(",")",".","render","(","{","}",")","s","=","LocationMapDataSerializer","(","location",")","return","JSONRenderer","(",")",".","render","(","s",".","data",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/locations\/templatetags\/location_tags.py#L12-L20"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"civmaps\/__init__.py","language":"python","identifier":"ping_google","parameters":"(sitemap_url=None, ping_url=PING_URL)","argument_list":"","return_statement":"","docstring":"Alerts Google that the sitemap for the current site has been updated.\n If sitemap_url is provided, it should be an absolute path to the sitemap\n for this site -- e.g., '\/sitemap.xml'. If sitemap_url is not provided, this\n function will attempt to deduce it by using urlresolvers.reverse().","docstring_summary":"Alerts Google that the sitemap for the current site has been updated.\n If sitemap_url is provided, it should be an absolute path to the sitemap\n for this site -- e.g., '\/sitemap.xml'. If sitemap_url is not provided, this\n function will attempt to deduce it by using urlresolvers.reverse().","docstring_tokens":["Alerts","Google","that","the","sitemap","for","the","current","site","has","been","updated",".","If","sitemap_url","is","provided","it","should","be","an","absolute","path","to","the","sitemap","for","this","site","--","e",".","g",".","\/","sitemap",".","xml",".","If","sitemap_url","is","not","provided","this","function","will","attempt","to","deduce","it","by","using","urlresolvers",".","reverse","()","."],"function":"def ping_google(sitemap_url=None, ping_url=PING_URL):\n \"\"\"\n Alerts Google that the sitemap for the current site has been updated.\n If sitemap_url is provided, it should be an absolute path to the sitemap\n for this site -- e.g., '\/sitemap.xml'. If sitemap_url is not provided, this\n function will attempt to deduce it by using urlresolvers.reverse().\n \"\"\"\n if sitemap_url is None:\n try:\n # First, try to get the \"index\" sitemap URL.\n sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.index')\n except urlresolvers.NoReverseMatch:\n try:\n # Next, try for the \"global\" sitemap URL.\n sitemap_url = urlresolvers.reverse('django.contrib.sitemaps.views.sitemap')\n except urlresolvers.NoReverseMatch:\n pass\n\n if sitemap_url is None:\n raise SitemapNotFound(\"You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.\")\n\n if not django_apps.is_installed('django.contrib.sites'):\n raise ImproperlyConfigured(\"ping_google requires django.contrib.sites, which isn't installed.\")\n Site = django_apps.get_model('sites.Site')\n current_site = Site.objects.get_current()\n url = \"http:\/\/%s%s\" % (current_site.domain, sitemap_url)\n params = urlencode({'sitemap': url})\n urlopen(\"%s?%s\" % (ping_url, params))","function_tokens":["def","ping_google","(","sitemap_url","=","None",",","ping_url","=","PING_URL",")",":","if","sitemap_url","is","None",":","try",":","# First, try to get the \"index\" sitemap URL.","sitemap_url","=","urlresolvers",".","reverse","(","'django.contrib.sitemaps.views.index'",")","except","urlresolvers",".","NoReverseMatch",":","try",":","# Next, try for the \"global\" sitemap URL.","sitemap_url","=","urlresolvers",".","reverse","(","'django.contrib.sitemaps.views.sitemap'",")","except","urlresolvers",".","NoReverseMatch",":","pass","if","sitemap_url","is","None",":","raise","SitemapNotFound","(","\"You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected.\"",")","if","not","django_apps",".","is_installed","(","'django.contrib.sites'",")",":","raise","ImproperlyConfigured","(","\"ping_google requires django.contrib.sites, which isn't installed.\"",")","Site","=","django_apps",".","get_model","(","'sites.Site'",")","current_site","=","Site",".","objects",".","get_current","(",")","url","=","\"http:\/\/%s%s\"","%","(","current_site",".","domain",",","sitemap_url",")","params","=","urlencode","(","{","'sitemap'",":","url","}",")","urlopen","(","\"%s?%s\"","%","(","ping_url",",","params",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/civmaps\/__init__.py#L17-L44"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"staticpages\/views.py","language":"python","identifier":"PageView.get_all_pages","parameters":"(self)","argument_list":"","return_statement":"return pages","docstring":"Searches through a folder in order to find static pages.","docstring_summary":"Searches through a folder in order to find static pages.","docstring_tokens":["Searches","through","a","folder","in","order","to","find","static","pages","."],"function":"def get_all_pages(self):\n \"\"\"\n Searches through a folder in order to find static pages.\n \"\"\"\n pages = []\n for page in os.listdir(PAGE_DIR):\n pages.append({\n 'url': str(reverse('pages:page', kwargs={'page': page[:4]})),\n 'name': page[:4],\n })\n return pages","function_tokens":["def","get_all_pages","(","self",")",":","pages","=","[","]","for","page","in","os",".","listdir","(","PAGE_DIR",")",":","pages",".","append","(","{","'url'",":","str","(","reverse","(","'pages:page'",",","kwargs","=","{","'page'",":","page","[",":","4","]","}",")",")",",","'name'",":","page","[",":","4","]",",","}",")","return","pages"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/staticpages\/views.py#L32-L42"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"geonames\/storage.py","language":"python","identifier":"import_country","parameters":"(entry)","argument_list":"","return_statement":"","docstring":"Function takes one line of file and creates Country model.","docstring_summary":"Function takes one line of file and creates Country model.","docstring_tokens":["Function","takes","one","line","of","file","and","creates","Country","model","."],"function":"def import_country(entry):\n \"\"\" Function takes one line of file and creates Country model. \"\"\"\n if entry.startswith('#'):\n return False\n entry = entry.split('\\t')\n \n # Incomplete entries are not desired\n if not entry[16] or entry[16] == ' ': return False\n \n try:\n chk = CountryInfo.objects.get(pk=int(entry[16]))\n # Entry exists. Skipping.\n logging.info(\"Country already exists: %s. Skipping\",\n unicode(entry[4]).encode('utf-8'))\n return True\n except CountryInfo.DoesNotExist:\n pass\n \n try:\n country = CountryInfo.objects.create(\n id = int(entry[16]),\n iso_alpha2 = entry[0],\n iso_alpha3 = entry[1],\n iso_numeric = entry[2],\n code = entry[3],\n name = entry[4],\n capital = entry[5],\n area = float(entry[6]) if entry[6] else 0.0,\n population = int(entry[7]) if entry[7] else 0,\n continent = entry[8],\n languages = entry[15]\n )\n \n country.save()\n\n logging.info(\"Country saved: %s\",\n unicode(entry[4]).encode('utf-8'))\n except Exception as ex:\n logging.error(\"Error importing country: %s - %s\",\n unicode(entry[4]).encode('utf-8'), ex.strerror)","function_tokens":["def","import_country","(","entry",")",":","if","entry",".","startswith","(","'#'",")",":","return","False","entry","=","entry",".","split","(","'\\t'",")","# Incomplete entries are not desired","if","not","entry","[","16","]","or","entry","[","16","]","==","' '",":","return","False","try",":","chk","=","CountryInfo",".","objects",".","get","(","pk","=","int","(","entry","[","16","]",")",")","# Entry exists. Skipping.","logging",".","info","(","\"Country already exists: %s. Skipping\"",",","unicode","(","entry","[","4","]",")",".","encode","(","'utf-8'",")",")","return","True","except","CountryInfo",".","DoesNotExist",":","pass","try",":","country","=","CountryInfo",".","objects",".","create","(","id","=","int","(","entry","[","16","]",")",",","iso_alpha2","=","entry","[","0","]",",","iso_alpha3","=","entry","[","1","]",",","iso_numeric","=","entry","[","2","]",",","code","=","entry","[","3","]",",","name","=","entry","[","4","]",",","capital","=","entry","[","5","]",",","area","=","float","(","entry","[","6","]",")","if","entry","[","6","]","else","0.0",",","population","=","int","(","entry","[","7","]",")","if","entry","[","7","]","else","0",",","continent","=","entry","[","8","]",",","languages","=","entry","[","15","]",")","country",".","save","(",")","logging",".","info","(","\"Country saved: %s\"",",","unicode","(","entry","[","4","]",")",".","encode","(","'utf-8'",")",")","except","Exception","as","ex",":","logging",".","error","(","\"Error importing country: %s - %s\"",",","unicode","(","entry","[","4","]",")",".","encode","(","'utf-8'",")",",","ex",".","strerror",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/geonames\/storage.py#L13-L52"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"geonames\/storage.py","language":"python","identifier":"import_geoname","parameters":"(entry)","argument_list":"","return_statement":"","docstring":"Function takes single line of input file and creates GeoName instance.","docstring_summary":"Function takes single line of input file and creates GeoName instance.","docstring_tokens":["Function","takes","single","line","of","input","file","and","creates","GeoName","instance","."],"function":"def import_geoname(entry):\n \"\"\" Function takes single line of input file and creates GeoName instance. \"\"\"\n if entry.startswith('#'):\n return False\n entry = entry.split('\\t')\n \n # Incomplete entries are not desired\n if not entry[0] or entry[0] == ' ': return False\n \n try:\n chk = GeoName.objects.get(pk=int(entry[0]))\n # Entry exists. Skipping.\n logging.info(\"GeoName object already exists: %s. Skipping\", entry[0])\n return True\n except GeoName.DoesNotExist:\n pass\n \n try: \n geoname = GeoName.objects.create(\n id = int(entry[0]),\n name = entry[1],\n name_std = entry[2],\n latitude = float(entry[4]) if entry[4] else 0.0,\n longitude = float(entry[5]) if entry[4] else 0.0,\n feature_class = entry[6],\n feature_code = entry[7],\n country = entry[8],\n admin1 = entry[10],\n admin2 = entry[11],\n admin3 = entry[12],\n admin4 = entry[13],\n population = int(entry[14]) if entry[14] else 0,\n )\n \n geoname.save()\n \n logging.info(\"GeoName object saved: %s\", unicode(entry[1]).encode('utf-8'))\n except Exception as ex:\n logging.error(\"Error importing GeoName: %s - %s\", entry[0], repr(ex))","function_tokens":["def","import_geoname","(","entry",")",":","if","entry",".","startswith","(","'#'",")",":","return","False","entry","=","entry",".","split","(","'\\t'",")","# Incomplete entries are not desired","if","not","entry","[","0","]","or","entry","[","0","]","==","' '",":","return","False","try",":","chk","=","GeoName",".","objects",".","get","(","pk","=","int","(","entry","[","0","]",")",")","# Entry exists. Skipping.","logging",".","info","(","\"GeoName object already exists: %s. Skipping\"",",","entry","[","0","]",")","return","True","except","GeoName",".","DoesNotExist",":","pass","try",":","geoname","=","GeoName",".","objects",".","create","(","id","=","int","(","entry","[","0","]",")",",","name","=","entry","[","1","]",",","name_std","=","entry","[","2","]",",","latitude","=","float","(","entry","[","4","]",")","if","entry","[","4","]","else","0.0",",","longitude","=","float","(","entry","[","5","]",")","if","entry","[","4","]","else","0.0",",","feature_class","=","entry","[","6","]",",","feature_code","=","entry","[","7","]",",","country","=","entry","[","8","]",",","admin1","=","entry","[","10","]",",","admin2","=","entry","[","11","]",",","admin3","=","entry","[","12","]",",","admin4","=","entry","[","13","]",",","population","=","int","(","entry","[","14","]",")","if","entry","[","14","]","else","0",",",")","geoname",".","save","(",")","logging",".","info","(","\"GeoName object saved: %s\"",",","unicode","(","entry","[","1","]",")",".","encode","(","'utf-8'",")",")","except","Exception","as","ex",":","logging",".","error","(","\"Error importing GeoName: %s - %s\"",",","entry","[","0","]",",","repr","(","ex",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/geonames\/storage.py#L55-L93"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"geonames\/storage.py","language":"python","identifier":"import_admin_code","parameters":"(entry)","argument_list":"","return_statement":"","docstring":"Function takes single line from admin1CodesASCII.txt file and creates\n admin code model in database.","docstring_summary":"Function takes single line from admin1CodesASCII.txt file and creates\n admin code model in database.","docstring_tokens":["Function","takes","single","line","from","admin1CodesASCII",".","txt","file","and","creates","admin","code","model","in","database","."],"function":"def import_admin_code(entry):\n \"\"\"\n Function takes single line from admin1CodesASCII.txt file and creates\n admin code model in database.\n \"\"\"\n if entry.startswith('#'):\n return False\n entry = entry.split('\\t')\n \n # Incomplete entries are not desired\n if not entry[0] or entry[0] == ' ': return False\n \n try:\n chk = AdminCode.objects.get(pk=int(entry[3]))\n # Entry exists. Skipping.\n logging.info(\"Admin code already exists: %s. Skipping\",\n entry[3].replace('\\n', ''))\n return True\n except AdminCode.DoesNotExist:\n pass\n \n try:\n admcode = AdminCode.objects.create(\n id = int(entry[3]),\n name = entry[1],\n name_std = entry[2],\n country = entry[0].split('.')[0],\n code = entry[0].split('.')[1]\n )\n \n admcode.save()\n \n logging.info(\"Admin code object saved: %s\", entry[3].replace('\\n', ''))\n except Exception as ex:\n logging.error(\"Error importing Admin code: %s - %s\",\n entry[3].replace('\\n', ''), repr(ex))","function_tokens":["def","import_admin_code","(","entry",")",":","if","entry",".","startswith","(","'#'",")",":","return","False","entry","=","entry",".","split","(","'\\t'",")","# Incomplete entries are not desired","if","not","entry","[","0","]","or","entry","[","0","]","==","' '",":","return","False","try",":","chk","=","AdminCode",".","objects",".","get","(","pk","=","int","(","entry","[","3","]",")",")","# Entry exists. Skipping.","logging",".","info","(","\"Admin code already exists: %s. Skipping\"",",","entry","[","3","]",".","replace","(","'\\n'",",","''",")",")","return","True","except","AdminCode",".","DoesNotExist",":","pass","try",":","admcode","=","AdminCode",".","objects",".","create","(","id","=","int","(","entry","[","3","]",")",",","name","=","entry","[","1","]",",","name_std","=","entry","[","2","]",",","country","=","entry","[","0","]",".","split","(","'.'",")","[","0","]",",","code","=","entry","[","0","]",".","split","(","'.'",")","[","1","]",")","admcode",".","save","(",")","logging",".","info","(","\"Admin code object saved: %s\"",",","entry","[","3","]",".","replace","(","'\\n'",",","''",")",")","except","Exception","as","ex",":","logging",".","error","(","\"Error importing Admin code: %s - %s\"",",","entry","[","3","]",".","replace","(","'\\n'",",","''",")",",","repr","(","ex",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/geonames\/storage.py#L96-L131"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"geonames\/storage.py","language":"python","identifier":"import_alt_name","parameters":"(entry)","argument_list":"","return_statement":"","docstring":"Takes one line of input file and returns dictionary.","docstring_summary":"Takes one line of input file and returns dictionary.","docstring_tokens":["Takes","one","line","of","input","file","and","returns","dictionary","."],"function":"def import_alt_name(entry):\n \"\"\" Takes one line of input file and returns dictionary. \"\"\"\n if entry.startswith('#'):\n return False\n entry = entry.split('\\t')\n \n # We're interested only in 1st group langs\n if len(entry[2]) != 2: return None\n # ... and objects we are really going to use\n target = None\n try:\n target = CountryInfo.objects.get(pk=int(entry[1]))\n except CountryInfo.DoesNotExist:\n target = None\n try:\n target = AdminCode.objects.get(pk=int(entry[1]))\n except AdminCode.DoesNotExist:\n target = None\n try:\n target = GeoName.objects.get(pk=int(entry[1]))\n except GeoName.DoesNotExist:\n target = None\n if target is None:\n logging.info(\"No geo entry for alternate name. Skipping\")\n return True\n \n try:\n chk = AltName.objects.get(pk=int(entry[0]))\n # Entry exists. Skipping.\n logging.info(\"Alternate name already exists: %s. Skipping\",\n unicode(entry[3]).encode('utf-8'))\n return True\n except AltName.DoesNotExist:\n pass\n \n try:\n alt_name = AltName.objects.create(\n id = int(entry[0]),\n geonameid = int(entry[1]),\n language = entry[2],\n altername = unicode(entry[3]),\n is_preferred = bool(entry[4]),\n is_short = bool(entry[5]),\n is_historic = bool(entry[6]),\n is_colloquial = bool(entry[7]),\n )\n \n alt_name.save()\n \n logging.info(\"Alternate name object saved: %s\",\n unicode(entry[3]).encode('utf-8'))\n except Exception as ex:\n logging.error(\"Error importing Alternate name: %s - %s\",\n unicode(entry[3]).encode('utf-8'), repr(ex))","function_tokens":["def","import_alt_name","(","entry",")",":","if","entry",".","startswith","(","'#'",")",":","return","False","entry","=","entry",".","split","(","'\\t'",")","# We're interested only in 1st group langs","if","len","(","entry","[","2","]",")","!=","2",":","return","None","# ... and objects we are really going to use","target","=","None","try",":","target","=","CountryInfo",".","objects",".","get","(","pk","=","int","(","entry","[","1","]",")",")","except","CountryInfo",".","DoesNotExist",":","target","=","None","try",":","target","=","AdminCode",".","objects",".","get","(","pk","=","int","(","entry","[","1","]",")",")","except","AdminCode",".","DoesNotExist",":","target","=","None","try",":","target","=","GeoName",".","objects",".","get","(","pk","=","int","(","entry","[","1","]",")",")","except","GeoName",".","DoesNotExist",":","target","=","None","if","target","is","None",":","logging",".","info","(","\"No geo entry for alternate name. Skipping\"",")","return","True","try",":","chk","=","AltName",".","objects",".","get","(","pk","=","int","(","entry","[","0","]",")",")","# Entry exists. Skipping.","logging",".","info","(","\"Alternate name already exists: %s. Skipping\"",",","unicode","(","entry","[","3","]",")",".","encode","(","'utf-8'",")",")","return","True","except","AltName",".","DoesNotExist",":","pass","try",":","alt_name","=","AltName",".","objects",".","create","(","id","=","int","(","entry","[","0","]",")",",","geonameid","=","int","(","entry","[","1","]",")",",","language","=","entry","[","2","]",",","altername","=","unicode","(","entry","[","3","]",")",",","is_preferred","=","bool","(","entry","[","4","]",")",",","is_short","=","bool","(","entry","[","5","]",")",",","is_historic","=","bool","(","entry","[","6","]",")",",","is_colloquial","=","bool","(","entry","[","7","]",")",",",")","alt_name",".","save","(",")","logging",".","info","(","\"Alternate name object saved: %s\"",",","unicode","(","entry","[","3","]",")",".","encode","(","'utf-8'",")",")","except","Exception","as","ex",":","logging",".","error","(","\"Error importing Alternate name: %s - %s\"",",","unicode","(","entry","[","3","]",")",".","encode","(","'utf-8'",")",",","repr","(","ex",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/geonames\/storage.py#L134-L187"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"blog\/models.py","language":"python","identifier":"notify_about_news_deletion","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"Notify newss author about that his news was deleted.","docstring_summary":"Notify newss author about that his news was deleted.","docstring_tokens":["Notify","newss","author","about","that","his","news","was","deleted","."],"function":"def notify_about_news_deletion(sender, instance, **kwargs):\n \"\"\" Notify newss author about that his news was deleted. \"\"\"\n # For now we assume that only superuser could delete news entries.\n admin = User.objects.filter(is_superuser=True)[0]\n notify(admin, instance.creator,\n key=\"deletion\",\n verb=\"deleted your blog entry\",\n action_object=instance\n )","function_tokens":["def","notify_about_news_deletion","(","sender",",","instance",",","*","*","kwargs",")",":","# For now we assume that only superuser could delete news entries.","admin","=","User",".","objects",".","filter","(","is_superuser","=","True",")","[","0","]","notify","(","admin",",","instance",".","creator",",","key","=","\"deletion\"",",","verb","=","\"deleted your blog entry\"",",","action_object","=","instance",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/blog\/models.py#L122-L130"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/views.py","language":"python","identifier":"create_gallery","parameters":"(gallery_name)","argument_list":"","return_statement":"return True","docstring":"Check if gallery folder exists and create new one if not.","docstring_summary":"Check if gallery folder exists and create new one if not.","docstring_tokens":["Check","if","gallery","folder","exists","and","create","new","one","if","not","."],"function":"def create_gallery(gallery_name):\n \"\"\"\n Check if gallery folder exists and create new one if not.\n \"\"\"\n filepath = os.path.join(settings.MEDIA_ROOT, gallery_name)\n thumb_path = os.path.join(filepath, 'thumbs')\n if not os.path.exists(filepath):\n try:\n os.makedirs(os.path.join(filepath, 'thumbs'))\n return True\n except IOError:\n return False\n return True","function_tokens":["def","create_gallery","(","gallery_name",")",":","filepath","=","os",".","path",".","join","(","settings",".","MEDIA_ROOT",",","gallery_name",")","thumb_path","=","os",".","path",".","join","(","filepath",",","'thumbs'",")","if","not","os",".","path",".","exists","(","filepath",")",":","try",":","os",".","makedirs","(","os",".","path",".","join","(","filepath",",","'thumbs'",")",")","return","True","except","IOError",":","return","False","return","True"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/views.py#L50-L62"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/views.py","language":"python","identifier":"create_gallery_thumbnail","parameters":"(gallery, filename)","argument_list":"","return_statement":"return True","docstring":"Create thumbnail for given image in selected gallery.\n @param gallery (string) Username or place slug\n @param filename (string) Image filename","docstring_summary":"Create thumbnail for given image in selected gallery.","docstring_tokens":["Create","thumbnail","for","given","image","in","selected","gallery","."],"function":"def create_gallery_thumbnail(gallery, filename):\n \"\"\"\n Create thumbnail for given image in selected gallery.\n @param gallery (string) Username or place slug\n @param filename (string) Image filename\n \"\"\"\n filepath = os.path.join(settings.MEDIA_ROOT, gallery)\n thumb_path = filepath + '\/thumbs\/'\n\n for w, h in settings.THUMB_SIZES:\n size = w, h\n thumbfile = str(w) + 'x' + str(h) + '_' + filename\n thumbname = os.path.join(thumb_path + thumbfile)\n try:\n thumb = Image.open(filepath + '\/' + filename)\n thumb.thumbnail(size, Image.ANTIALIAS)\n thumb.save(thumbname, 'JPEG')\n except IOError:\n return False\n return True","function_tokens":["def","create_gallery_thumbnail","(","gallery",",","filename",")",":","filepath","=","os",".","path",".","join","(","settings",".","MEDIA_ROOT",",","gallery",")","thumb_path","=","filepath","+","'\/thumbs\/'","for","w",",","h","in","settings",".","THUMB_SIZES",":","size","=","w",",","h","thumbfile","=","str","(","w",")","+","'x'","+","str","(","h",")","+","'_'","+","filename","thumbname","=","os",".","path",".","join","(","thumb_path","+","thumbfile",")","try",":","thumb","=","Image",".","open","(","filepath","+","'\/'","+","filename",")","thumb",".","thumbnail","(","size",",","Image",".","ANTIALIAS",")","thumb",".","save","(","thumbname",",","'JPEG'",")","except","IOError",":","return","False","return","True"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/views.py#L65-L84"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/views.py","language":"python","identifier":"gallery_item_name","parameters":"()","argument_list":"","return_statement":"return basename.hexdigest() + '.jpg'","docstring":"Creates name based on md5 sum of current date and time to avoid naming\n conflicts in files.","docstring_summary":"Creates name based on md5 sum of current date and time to avoid naming\n conflicts in files.","docstring_tokens":["Creates","name","based","on","md5","sum","of","current","date","and","time","to","avoid","naming","conflicts","in","files","."],"function":"def gallery_item_name():\n \"\"\"\n Creates name based on md5 sum of current date and time to avoid naming\n conflicts in files.\n \"\"\"\n rand = random.randint(0, 10000)\n basename = hashlib.md5()\n basename.update(str(datetime.now().time) + str(rand))\n return basename.hexdigest() + '.jpg'","function_tokens":["def","gallery_item_name","(",")",":","rand","=","random",".","randint","(","0",",","10000",")","basename","=","hashlib",".","md5","(",")","basename",".","update","(","str","(","datetime",".","now","(",")",".","time",")","+","str","(","rand",")",")","return","basename",".","hexdigest","(",")","+","'.jpg'"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/views.py#L87-L95"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/views.py","language":"python","identifier":"location_gallery_delete","parameters":"(request, slug=None, pk=None)","argument_list":"","return_statement":"","docstring":"A view that allows to delete images from the gallery. The 'pk' parameter is\n compulsory and when it is empty, an error will occur. The 'slug' parameter\n is here only to match the view in urlconf with the 'locations' application.","docstring_summary":"A view that allows to delete images from the gallery. The 'pk' parameter is\n compulsory and when it is empty, an error will occur. The 'slug' parameter\n is here only to match the view in urlconf with the 'locations' application.","docstring_tokens":["A","view","that","allows","to","delete","images","from","the","gallery",".","The","pk","parameter","is","compulsory","and","when","it","is","empty","an","error","will","occur",".","The","slug","parameter","is","here","only","to","match","the","view","in","urlconf","with","the","locations","application","."],"function":"def location_gallery_delete(request, slug=None, pk=None):\n \"\"\"\n A view that allows to delete images from the gallery. The 'pk' parameter is\n compulsory and when it is empty, an error will occur. The 'slug' parameter\n is here only to match the view in urlconf with the 'locations' application.\n \"\"\"\n item = get_object_or_404(LocationGalleryItem, pk=pk)\n if request.user.is_superuser or is_moderator(request.user, item.location):\n item.delete()\n return redirect(\n reverse('locations:gallery',\n kwargs={'location_slug':item.location.slug})\n )\n else:\n return HttpResponseForbidden()","function_tokens":["def","location_gallery_delete","(","request",",","slug","=","None",",","pk","=","None",")",":","item","=","get_object_or_404","(","LocationGalleryItem",",","pk","=","pk",")","if","request",".","user",".","is_superuser","or","is_moderator","(","request",".","user",",","item",".","location",")",":","item",".","delete","(",")","return","redirect","(","reverse","(","'locations:gallery'",",","kwargs","=","{","'location_slug'",":","item",".","location",".","slug","}",")",")","else",":","return","HttpResponseForbidden","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/views.py#L390-L404"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/views.py","language":"python","identifier":"ImageView.post","parameters":"(self, request, pk)","argument_list":"","return_statement":"return redirect(reverse('gallery:index'))","docstring":"Save changes in image.","docstring_summary":"Save changes in image.","docstring_tokens":["Save","changes","in","image","."],"function":"def post(self, request, pk):\n \"\"\"\n Save changes in image.\n \"\"\"\n x = request.POST.get('x')\n y = request.POST.get('y')\n x2 = request.POST.get('x2')\n y2 = request.POST.get('y2')\n item = get_object_or_404(UserGalleryItem, pk=pk)\n filename = item.picture_name\n filepath = item.get_filepath()\n file = os.path.join(filepath, filename)\n box = (int(x), int(y), int(x2), int(y2))\n\n img = Image.open(file)\n img.crop(box).save(file)\n create_gallery_thumbnail(request.user.username, filename)\n\n return redirect(reverse('gallery:index'))","function_tokens":["def","post","(","self",",","request",",","pk",")",":","x","=","request",".","POST",".","get","(","'x'",")","y","=","request",".","POST",".","get","(","'y'",")","x2","=","request",".","POST",".","get","(","'x2'",")","y2","=","request",".","POST",".","get","(","'y2'",")","item","=","get_object_or_404","(","UserGalleryItem",",","pk","=","pk",")","filename","=","item",".","picture_name","filepath","=","item",".","get_filepath","(",")","file","=","os",".","path",".","join","(","filepath",",","filename",")","box","=","(","int","(","x",")",",","int","(","y",")",",","int","(","x2",")",",","int","(","y2",")",")","img","=","Image",".","open","(","file",")","img",".","crop","(","box",")",".","save","(","file",")","create_gallery_thumbnail","(","request",".","user",".","username",",","filename",")","return","redirect","(","reverse","(","'gallery:index'",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/views.py#L274-L292"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/actions.py","language":"python","identifier":"created_gallery","parameters":"(user, instance)","argument_list":"","return_statement":"","docstring":"Send action about new gallery. Takes ContentObjectGallery as argument.","docstring_summary":"Send action about new gallery. Takes ContentObjectGallery as argument.","docstring_tokens":["Send","action","about","new","gallery",".","Takes","ContentObjectGallery","as","argument","."],"function":"def created_gallery(user, instance):\n \"\"\" Send action about new gallery. Takes ContentObjectGallery as argument.\n \"\"\"\n verb = _(u\"created gallery\")\n publisher = instance.published_in\n if publisher is None:\n action.send(user, verb=verb, action_object=instance)\n action.send(user, verb=verb, action_object=instance, target=publisher)\n if hasattr(publisher, 'creator'):\n target_user = publisher.creator\n elif hasattr(publisher, 'author'):\n target_user = publisher.author\n if target_user == user:\n return True\n notify(user, target_user,\n verb=verb,\n key=\"gallery\",\n action_object=instance,\n action_target=publisher)","function_tokens":["def","created_gallery","(","user",",","instance",")",":","verb","=","_","(","u\"created gallery\"",")","publisher","=","instance",".","published_in","if","publisher","is","None",":","action",".","send","(","user",",","verb","=","verb",",","action_object","=","instance",")","action",".","send","(","user",",","verb","=","verb",",","action_object","=","instance",",","target","=","publisher",")","if","hasattr","(","publisher",",","'creator'",")",":","target_user","=","publisher",".","creator","elif","hasattr","(","publisher",",","'author'",")",":","target_user","=","publisher",".","author","if","target_user","==","user",":","return","True","notify","(","user",",","target_user",",","verb","=","verb",",","key","=","\"gallery\"",",","action_object","=","instance",",","action_target","=","publisher",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/actions.py#L9-L27"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/actions.py","language":"python","identifier":"uploaded_picture","parameters":"(instance)","argument_list":"","return_statement":"","docstring":"Send information about new picture in existing gallery.","docstring_summary":"Send information about new picture in existing gallery.","docstring_tokens":["Send","information","about","new","picture","in","existing","gallery","."],"function":"def uploaded_picture(instance):\n \"\"\" Send information about new picture in existing gallery.\n \"\"\"\n verb = _(u\"uploaded picture\")\n action.send(instance.uploaded_by,\n verb=verb,\n action_object=instance,\n target=instance.gallery)","function_tokens":["def","uploaded_picture","(","instance",")",":","verb","=","_","(","u\"uploaded picture\"",")","action",".","send","(","instance",".","uploaded_by",",","verb","=","verb",",","action_object","=","instance",",","target","=","instance",".","gallery",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/actions.py#L30-L37"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/signals.py","language":"python","identifier":"cleanup_gallery","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"Make sure that all files will be deleted along with gallery itself.","docstring_summary":"Make sure that all files will be deleted along with gallery itself.","docstring_tokens":["Make","sure","that","all","files","will","be","deleted","along","with","gallery","itself","."],"function":"def cleanup_gallery(sender, instance, **kwargs):\n \"\"\" Make sure that all files will be deleted along with gallery itself.\n \"\"\"\n rmdir(instance)","function_tokens":["def","cleanup_gallery","(","sender",",","instance",",","*","*","kwargs",")",":","rmdir","(","instance",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/signals.py#L6-L9"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/signals.py","language":"python","identifier":"cleanup_image","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"Remove all images when model is deleted.","docstring_summary":"Remove all images when model is deleted.","docstring_tokens":["Remove","all","images","when","model","is","deleted","."],"function":"def cleanup_image(sender, instance, **kwargs):\n \"\"\" Remove all images when model is deleted.\n \"\"\"\n massrm(instance)","function_tokens":["def","cleanup_image","(","sender",",","instance",",","*","*","kwargs",")",":","massrm","(","instance",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/signals.py#L12-L15"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/signals.py","language":"python","identifier":"adjust_images","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"Crop image.","docstring_summary":"Crop image.","docstring_tokens":["Crop","image","."],"function":"def adjust_images(sender, instance, **kwargs):\n \"\"\" Crop image.\n \"\"\"\n generate_thumbs(instance.image.path)","function_tokens":["def","adjust_images","(","sender",",","instance",",","*","*","kwargs",")",":","generate_thumbs","(","instance",".","image",".","path",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/signals.py#L18-L21"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"rename_background_file","parameters":"(filepath, pref=\"s_\")","argument_list":"","return_statement":"return os.path.join(path, pref + file)","docstring":"The function takes an absolute system path to the background image (mainly\n with location and users in mind) and adds\/changes the name for the cropped\n file (prefix). The prefix can be set in any way, but only \"s_\" will work\n later on in the templates.\n\n TODO: global cropped image prefix.","docstring_summary":"The function takes an absolute system path to the background image (mainly\n with location and users in mind) and adds\/changes the name for the cropped\n file (prefix). The prefix can be set in any way, but only \"s_\" will work\n later on in the templates.","docstring_tokens":["The","function","takes","an","absolute","system","path","to","the","background","image","(","mainly","with","location","and","users","in","mind",")","and","adds","\/","changes","the","name","for","the","cropped","file","(","prefix",")",".","The","prefix","can","be","set","in","any","way","but","only","s_","will","work","later","on","in","the","templates","."],"function":"def rename_background_file(filepath, pref=\"s_\"):\n \"\"\"\n The function takes an absolute system path to the background image (mainly\n with location and users in mind) and adds\/changes the name for the cropped\n file (prefix). The prefix can be set in any way, but only \"s_\" will work\n later on in the templates.\n\n TODO: global cropped image prefix.\n \"\"\"\n path, file = os.path.split(filepath)\n return os.path.join(path, pref + file)","function_tokens":["def","rename_background_file","(","filepath",",","pref","=","\"s_\"",")",":","path",",","file","=","os",".","path",".","split","(","filepath",")","return","os",".","path",".","join","(","path",",","pref","+","file",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L14-L24"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"handle_tmp_image","parameters":"(image)","argument_list":"","return_statement":"return InMemoryUploadedFile(img_io, None, 'foo.jpg', 'image\/jpeg',\n img_io.len, None)","docstring":"A function that allows to \"change\" the images before they get uploaded and send\n to Django enginge. Used while uploading background images and avatars to create\n temporary files that can be used in ImageField model of Django.","docstring_summary":"A function that allows to \"change\" the images before they get uploaded and send\n to Django enginge. Used while uploading background images and avatars to create\n temporary files that can be used in ImageField model of Django.","docstring_tokens":["A","function","that","allows","to","change","the","images","before","they","get","uploaded","and","send","to","Django","enginge",".","Used","while","uploading","background","images","and","avatars","to","create","temporary","files","that","can","be","used","in","ImageField","model","of","Django","."],"function":"def handle_tmp_image(image):\n \"\"\"\n A function that allows to \"change\" the images before they get uploaded and send\n to Django enginge. Used while uploading background images and avatars to create\n temporary files that can be used in ImageField model of Django.\n \"\"\"\n img_io = StringIO.StringIO()\n image.save(img_io, format='JPEG')\n return InMemoryUploadedFile(img_io, None, 'foo.jpg', 'image\/jpeg',\n img_io.len, None)","function_tokens":["def","handle_tmp_image","(","image",")",":","img_io","=","StringIO",".","StringIO","(",")","image",".","save","(","img_io",",","format","=","'JPEG'",")","return","InMemoryUploadedFile","(","img_io",",","None",",","'foo.jpg'",",","'image\/jpeg'",",","img_io",".","len",",","None",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L27-L36"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"resize_image","parameters":"(image, size=None)","argument_list":"","return_statement":"return image.resize((max_w, int(height*ratio)), Image.ANTIALIAS)","docstring":"The function take the PIL image as an argument and returns the same object\n but with changed dimensions. The change of dimensions takes place to the\n maximum width.","docstring_summary":"The function take the PIL image as an argument and returns the same object\n but with changed dimensions. The change of dimensions takes place to the\n maximum width.","docstring_tokens":["The","function","take","the","PIL","image","as","an","argument","and","returns","the","same","object","but","with","changed","dimensions",".","The","change","of","dimensions","takes","place","to","the","maximum","width","."],"function":"def resize_image(image, size=None):\n \"\"\"\n The function take the PIL image as an argument and returns the same object\n but with changed dimensions. The change of dimensions takes place to the\n maximum width.\n \"\"\"\n max_w, max_h = settings.BACKGROUND_IMAGE_SIZE if size is None else size\n width, height = image.getdata().size\n ratio = float(max_w) \/ float(width)\n return image.resize((max_w, int(height*ratio)), Image.ANTIALIAS)","function_tokens":["def","resize_image","(","image",",","size","=","None",")",":","max_w",",","max_h","=","settings",".","BACKGROUND_IMAGE_SIZE","if","size","is","None","else","size","width",",","height","=","image",".","getdata","(",")",".","size","ratio","=","float","(","max_w",")","\/","float","(","width",")","return","image",".","resize","(","(","max_w",",","int","(","height","*","ratio",")",")",",","Image",".","ANTIALIAS",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L39-L48"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"delete_image","parameters":"(imagepath)","argument_list":"","return_statement":"","docstring":"A simple function that \"silences\" errors while deleting files that don't exist.","docstring_summary":"A simple function that \"silences\" errors while deleting files that don't exist.","docstring_tokens":["A","simple","function","that","silences","errors","while","deleting","files","that","don","t","exist","."],"function":"def delete_image(imagepath):\n \"\"\"\n A simple function that \"silences\" errors while deleting files that don't exist.\n \"\"\"\n try:\n os.unlink(imagepath)\n except OSError, IOError:\n pass","function_tokens":["def","delete_image","(","imagepath",")",":","try",":","os",".","unlink","(","imagepath",")","except","OSError",",","IOError",":","pass"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L51-L58"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"get_fieldname","parameters":"(instance)","argument_list":"","return_statement":"return fieldname","docstring":"A Method that takes an instance of an object as an argument and returns the\n correct name of the filed that stores the background image. Works for UserProfile\n model and Location.","docstring_summary":"A Method that takes an instance of an object as an argument and returns the\n correct name of the filed that stores the background image. Works for UserProfile\n model and Location.","docstring_tokens":["A","Method","that","takes","an","instance","of","an","object","as","an","argument","and","returns","the","correct","name","of","the","filed","that","stores","the","background","image",".","Works","for","UserProfile","model","and","Location","."],"function":"def get_fieldname(instance):\n \"\"\"\n A Method that takes an instance of an object as an argument and returns the\n correct name of the filed that stores the background image. Works for UserProfile\n model and Location.\n \"\"\"\n field_names = ('background_image', 'image')\n fieldname = None\n\n for fn in field_names:\n fieldname = instance.__dict__.get(fn)\n if fieldname is not None:\n break\n\n if fieldname is None:\n raise Exception(\"Wrong model instance\")\n\n return fieldname","function_tokens":["def","get_fieldname","(","instance",")",":","field_names","=","(","'background_image'",",","'image'",")","fieldname","=","None","for","fn","in","field_names",":","fieldname","=","instance",".","__dict__",".","get","(","fn",")","if","fieldname","is","not","None",":","break","if","fieldname","is","None",":","raise","Exception","(","\"Wrong model instance\"",")","return","fieldname"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L61-L78"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"crop_background","parameters":"(image, pathname, max_size=(270,150))","argument_list":"","return_statement":"","docstring":"Crop background images and display them in thumbs. Both arguments are\n required. Image is PIL image instance (resized and cropped to fit background\n dimmensions) and pathname means upload path (excluding MEDIA_ROOT, e.g same\n as in model's field declaration).","docstring_summary":"Crop background images and display them in thumbs. Both arguments are\n required. Image is PIL image instance (resized and cropped to fit background\n dimmensions) and pathname means upload path (excluding MEDIA_ROOT, e.g same\n as in model's field declaration).","docstring_tokens":["Crop","background","images","and","display","them","in","thumbs",".","Both","arguments","are","required",".","Image","is","PIL","image","instance","(","resized","and","cropped","to","fit","background","dimmensions",")","and","pathname","means","upload","path","(","excluding","MEDIA_ROOT","e",".","g","same","as","in","model","s","field","declaration",")","."],"function":"def crop_background(image, pathname, max_size=(270,150)):\n \"\"\"\n Crop background images and display them in thumbs. Both arguments are\n required. Image is PIL image instance (resized and cropped to fit background\n dimmensions) and pathname means upload path (excluding MEDIA_ROOT, e.g same\n as in model's field declaration).\n \"\"\"\n max_w, max_h = max_size\n width, height = image.getdata().size\n new_width = int(width * float(max_h)\/float(height))\n startx = int((new_width - max_w) \/ 2)\n\n image = image.resize((new_width, max_h), Image.ANTIALIAS)\n box = (startx, 0, startx + max_w, max_h)\n image = image.crop(box)\n path = os.path.join(settings.MEDIA_ROOT, rename_background_file(pathname))\n image.save(path, 'JPEG')","function_tokens":["def","crop_background","(","image",",","pathname",",","max_size","=","(","270",",","150",")",")",":","max_w",",","max_h","=","max_size","width",",","height","=","image",".","getdata","(",")",".","size","new_width","=","int","(","width","*","float","(","max_h",")","\/","float","(","height",")",")","startx","=","int","(","(","new_width","-","max_w",")","\/","2",")","image","=","image",".","resize","(","(","new_width",",","max_h",")",",","Image",".","ANTIALIAS",")","box","=","(","startx",",","0",",","startx","+","max_w",",","max_h",")","image","=","image",".","crop","(","box",")","path","=","os",".","path",".","join","(","settings",".","MEDIA_ROOT",",","rename_background_file","(","pathname",")",")","image",".","save","(","path",",","'JPEG'",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L81-L97"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"resize_background_image","parameters":"(sender, instance, created, **kwargs)","argument_list":"","return_statement":"","docstring":"Resize background image to fit for sizes defined in settings file. Method\n takes model instance as argument and performs resizing and cropping.","docstring_summary":"Resize background image to fit for sizes defined in settings file. Method\n takes model instance as argument and performs resizing and cropping.","docstring_tokens":["Resize","background","image","to","fit","for","sizes","defined","in","settings","file",".","Method","takes","model","instance","as","argument","and","performs","resizing","and","cropping","."],"function":"def resize_background_image(sender, instance, created, **kwargs):\n \"\"\"\n Resize background image to fit for sizes defined in settings file. Method\n takes model instance as argument and performs resizing and cropping.\n \"\"\"\n fieldname = instance.image\n\n if u'nowhere.jpg' in fieldname.path or u'background.jpg' in fieldname.path or u'default.jpg' in fieldname.path:\n return False\n\n max_width, max_height = settings.BACKGROUND_IMAGE_SIZE\n im = ImageManager(fieldname.path, \"\/\".join(fieldname.path.split('\/')[:-1]))\n im.fixed_thumb(max_width, max_height)","function_tokens":["def","resize_background_image","(","sender",",","instance",",","created",",","*","*","kwargs",")",":","fieldname","=","instance",".","image","if","u'nowhere.jpg'","in","fieldname",".","path","or","u'background.jpg'","in","fieldname",".","path","or","u'default.jpg'","in","fieldname",".","path",":","return","False","max_width",",","max_height","=","settings",".","BACKGROUND_IMAGE_SIZE","im","=","ImageManager","(","fieldname",".","path",",","\"\/\"",".","join","(","fieldname",".","path",".","split","(","'\/'",")","[",":","-","1","]",")",")","im",".","fixed_thumb","(","max_width",",","max_height",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L100-L112"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"delete_background_image","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"A Method that deletes the background image for location and user profile models","docstring_summary":"A Method that deletes the background image for location and user profile models","docstring_tokens":["A","Method","that","deletes","the","background","image","for","location","and","user","profile","models"],"function":"def delete_background_image(sender, instance, **kwargs):\n \"\"\"\n A Method that deletes the background image for location and user profile models\n \"\"\"\n fieldname = get_fieldname(instance)\n\n if u'nowhere.jpg' in fieldname or u'background.jpg' in fieldname:\n return False\n\n if (os.path.isfile(fieldname)):\n os.unlink(fieldname)\n\n path, fname = os.path.splitext(fieldname)\n fname = \"s_\" + str(fname)\n fpath = os.path.join(path, fname)\n\n if os.path.isfile(fpath):\n os.unlink(fpath)","function_tokens":["def","delete_background_image","(","sender",",","instance",",","*","*","kwargs",")",":","fieldname","=","get_fieldname","(","instance",")","if","u'nowhere.jpg'","in","fieldname","or","u'background.jpg'","in","fieldname",":","return","False","if","(","os",".","path",".","isfile","(","fieldname",")",")",":","os",".","unlink","(","fieldname",")","path",",","fname","=","os",".","path",".","splitext","(","fieldname",")","fname","=","\"s_\"","+","str","(","fname",")","fpath","=","os",".","path",".","join","(","path",",","fname",")","if","os",".","path",".","isfile","(","fpath",")",":","os",".","unlink","(","fpath",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L115-L132"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"crop_gallery_thumb","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"We crop the image to show it on the main site of the gallery.","docstring_summary":"We crop the image to show it on the main site of the gallery.","docstring_tokens":["We","crop","the","image","to","show","it","on","the","main","site","of","the","gallery","."],"function":"def crop_gallery_thumb(sender, instance, **kwargs):\n \"\"\"\n We crop the image to show it on the main site of the gallery.\n \"\"\"\n filename = 'cropped_' + instance.picture_name\n if hasattr(instance, 'location'):\n path = os.path.join(settings.MEDIA_ROOT, instance.location.slug)\n else:\n path = os.path.join(settings.MEDIA_ROOT, instance.user.username)\n image = Image.open(instance.get_filename())\n max_w, max_h = settings.GALLERY_THUMB_SIZE\n width, height = image.getdata().size\n if height > width:\n ratio = float(max_w)\/float(width)\n image = image.resize((max_w, int(height*ratio)), Image.ANTIALIAS)\n box = (0, 0, max_w, max_h)\n else:\n ratio = float(max_h)\/float(height)\n new_width = int(width*ratio)\n image = image.resize((new_width, max_h), Image.ANTIALIAS)\n start_x = 0\n x_factor = max_w\n if new_width > max_w:\n start_x = int((float(new_width)-float(max_w))\/2)\n if new_width < max_w:\n nratio = float(max_w)\/float(new_width)\n cw, ch = image.getdata().size\n image = image.resize((max_w, int(float(ch)*nratio)), Image.ANTIALIAS)\n stop_x = start_x + x_factor\n box = (start_x, 0, stop_x, max_h)\n image = image.crop(box)\n image.save(os.path.join(path, filename), 'JPEG')","function_tokens":["def","crop_gallery_thumb","(","sender",",","instance",",","*","*","kwargs",")",":","filename","=","'cropped_'","+","instance",".","picture_name","if","hasattr","(","instance",",","'location'",")",":","path","=","os",".","path",".","join","(","settings",".","MEDIA_ROOT",",","instance",".","location",".","slug",")","else",":","path","=","os",".","path",".","join","(","settings",".","MEDIA_ROOT",",","instance",".","user",".","username",")","image","=","Image",".","open","(","instance",".","get_filename","(",")",")","max_w",",","max_h","=","settings",".","GALLERY_THUMB_SIZE","width",",","height","=","image",".","getdata","(",")",".","size","if","height",">","width",":","ratio","=","float","(","max_w",")","\/","float","(","width",")","image","=","image",".","resize","(","(","max_w",",","int","(","height","*","ratio",")",")",",","Image",".","ANTIALIAS",")","box","=","(","0",",","0",",","max_w",",","max_h",")","else",":","ratio","=","float","(","max_h",")","\/","float","(","height",")","new_width","=","int","(","width","*","ratio",")","image","=","image",".","resize","(","(","new_width",",","max_h",")",",","Image",".","ANTIALIAS",")","start_x","=","0","x_factor","=","max_w","if","new_width",">","max_w",":","start_x","=","int","(","(","float","(","new_width",")","-","float","(","max_w",")",")","\/","2",")","if","new_width","<","max_w",":","nratio","=","float","(","max_w",")","\/","float","(","new_width",")","cw",",","ch","=","image",".","getdata","(",")",".","size","image","=","image",".","resize","(","(","max_w",",","int","(","float","(","ch",")","*","nratio",")",")",",","Image",".","ANTIALIAS",")","stop_x","=","start_x","+","x_factor","box","=","(","start_x",",","0",",","stop_x",",","max_h",")","image","=","image",".","crop","(","box",")","image",".","save","(","os",".","path",".","join","(","path",",","filename",")",",","'JPEG'",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L135-L166"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"delete_cropped_thumb","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"The signal that deletes the cropped image for gallery element.","docstring_summary":"The signal that deletes the cropped image for gallery element.","docstring_tokens":["The","signal","that","deletes","the","cropped","image","for","gallery","element","."],"function":"def delete_cropped_thumb(sender, instance, **kwargs):\n \"\"\"\n The signal that deletes the cropped image for gallery element.\n \"\"\"\n filename = 'cropped_' + instance.picture_name\n if hasattr(instance, 'location'):\n filepath = os.path.join(settings.MEDIA_ROOT, instance.location.slug, filename)\n else:\n filepath = os.path.join(settings.MEDIA_ROOT, instance.user.username, filename)\n delete_image(filepath)","function_tokens":["def","delete_cropped_thumb","(","sender",",","instance",",","*","*","kwargs",")",":","filename","=","'cropped_'","+","instance",".","picture_name","if","hasattr","(","instance",",","'location'",")",":","filepath","=","os",".","path",".","join","(","settings",".","MEDIA_ROOT",",","instance",".","location",".","slug",",","filename",")","else",":","filepath","=","os",".","path",".","join","(","settings",".","MEDIA_ROOT",",","instance",".","user",".","username",",","filename",")","delete_image","(","filepath",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L169-L178"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"thumb_name","parameters":"(filename, size)","argument_list":"","return_statement":"return \"%s_%dx%d%s\" % (file, size[0], size[1], ext)","docstring":"Given file name or full path and size tuple returns thumbnail name.","docstring_summary":"Given file name or full path and size tuple returns thumbnail name.","docstring_tokens":["Given","file","name","or","full","path","and","size","tuple","returns","thumbnail","name","."],"function":"def thumb_name(filename, size):\n \"\"\" Given file name or full path and size tuple returns thumbnail name. \"\"\"\n file, ext = os.path.splitext(filename)\n return \"%s_%dx%d%s\" % (file, size[0], size[1], ext)","function_tokens":["def","thumb_name","(","filename",",","size",")",":","file",",","ext","=","os",".","path",".","splitext","(","filename",")","return","\"%s_%dx%d%s\"","%","(","file",",","size","[","0","]",",","size","[","1","]",",","ext",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L181-L184"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"crop_thumb","parameters":"(filename, size)","argument_list":"","return_statement":"","docstring":"The function takes the path to the image file as an argument and creates\n a minature with the given (typed) dimensions. The image will be shrunk and\n cropped \"intelligently\".","docstring_summary":"The function takes the path to the image file as an argument and creates\n a minature with the given (typed) dimensions. The image will be shrunk and\n cropped \"intelligently\".","docstring_tokens":["The","function","takes","the","path","to","the","image","file","as","an","argument","and","creates","a","minature","with","the","given","(","typed",")","dimensions",".","The","image","will","be","shrunk","and","cropped","intelligently","."],"function":"def crop_thumb(filename, size):\n \"\"\"\n The function takes the path to the image file as an argument and creates\n a minature with the given (typed) dimensions. The image will be shrunk and\n cropped \"intelligently\".\n \"\"\"\n image = Image.open(filename)\n max_w, max_h = size\n width, height = image.getdata().size\n if height > width:\n ratio = float(max_w)\/float(width)\n image = image.resize((max_w, int(height*ratio)), Image.ANTIALIAS)\n box = (0, 0, max_w, max_h)\n else:\n ratio = float(max_h)\/float(height)\n new_width = int(width*ratio)\n image = image.resize((new_width, max_h), Image.ANTIALIAS)\n start_x = 0\n x_factor = max_w\n if new_width >= max_w:\n start_x = int((float(new_width)-float(max_w))\/2)\n else:\n nratio = float(max_w)\/float(new_width)\n cw, ch = image.getdata().size\n image = image.resize((max_w, int(float(ch)*nratio)), Image.ANTIALIAS)\n stop_x = start_x + x_factor\n box = (start_x, 0, stop_x, max_h)\n image = image.crop(box)\n image.save(thumb_name(filename, size), 'JPEG')","function_tokens":["def","crop_thumb","(","filename",",","size",")",":","image","=","Image",".","open","(","filename",")","max_w",",","max_h","=","size","width",",","height","=","image",".","getdata","(",")",".","size","if","height",">","width",":","ratio","=","float","(","max_w",")","\/","float","(","width",")","image","=","image",".","resize","(","(","max_w",",","int","(","height","*","ratio",")",")",",","Image",".","ANTIALIAS",")","box","=","(","0",",","0",",","max_w",",","max_h",")","else",":","ratio","=","float","(","max_h",")","\/","float","(","height",")","new_width","=","int","(","width","*","ratio",")","image","=","image",".","resize","(","(","new_width",",","max_h",")",",","Image",".","ANTIALIAS",")","start_x","=","0","x_factor","=","max_w","if","new_width",">=","max_w",":","start_x","=","int","(","(","float","(","new_width",")","-","float","(","max_w",")",")","\/","2",")","else",":","nratio","=","float","(","max_w",")","\/","float","(","new_width",")","cw",",","ch","=","image",".","getdata","(",")",".","size","image","=","image",".","resize","(","(","max_w",",","int","(","float","(","ch",")","*","nratio",")",")",",","Image",".","ANTIALIAS",")","stop_x","=","start_x","+","x_factor","box","=","(","start_x",",","0",",","stop_x",",","max_h",")","image","=","image",".","crop","(","box",")","image",".","save","(","thumb_name","(","filename",",","size",")",",","'JPEG'",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L187-L215"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"get_image_size","parameters":"(imagepath)","argument_list":"","return_statement":"","docstring":"A small helper. We give the path to the image and the function returns\n a tuplet with its height and width in pixels. We return the sizes of\n the images already matched (changed).","docstring_summary":"A small helper. We give the path to the image and the function returns\n a tuplet with its height and width in pixels. We return the sizes of\n the images already matched (changed).","docstring_tokens":["A","small","helper",".","We","give","the","path","to","the","image","and","the","function","returns","a","tuplet","with","its","height","and","width","in","pixels",".","We","return","the","sizes","of","the","images","already","matched","(","changed",")","."],"function":"def get_image_size(imagepath):\n \"\"\"\n A small helper. We give the path to the image and the function returns\n a tuplet with its height and width in pixels. We return the sizes of\n the images already matched (changed).\n \"\"\"\n try:\n image = Image.open(os.path.splitext(imagepath)[0] + '_fx.jpg')\n return image.getdata().size\n except IOError:\n # Element najwyra\u017aniej ma ustawiony obrazek domy\u015blny\n return 0","function_tokens":["def","get_image_size","(","imagepath",")",":","try",":","image","=","Image",".","open","(","os",".","path",".","splitext","(","imagepath",")","[","0","]","+","'_fx.jpg'",")","return","image",".","getdata","(",")",".","size","except","IOError",":","# Element najwyra\u017aniej ma ustawiony obrazek domy\u015blny","return","0"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L218-L229"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"adjust_uploaded_image","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"A unified method that manages images for our model ImagableItemMixin.\n Readies images of standarized sizes and the same for retina.\n The size of the image is set in settings.DEFAULT_IMG_SIZE. We preserve\n the original.","docstring_summary":"A unified method that manages images for our model ImagableItemMixin.\n Readies images of standarized sizes and the same for retina.\n The size of the image is set in settings.DEFAULT_IMG_SIZE. We preserve\n the original.","docstring_tokens":["A","unified","method","that","manages","images","for","our","model","ImagableItemMixin",".","Readies","images","of","standarized","sizes","and","the","same","for","retina",".","The","size","of","the","image","is","set","in","settings",".","DEFAULT_IMG_SIZE",".","We","preserve","the","original","."],"function":"def adjust_uploaded_image(sender, instance, **kwargs):\n \"\"\"\n A unified method that manages images for our model ImagableItemMixin.\n Readies images of standarized sizes and the same for retina.\n The size of the image is set in settings.DEFAULT_IMG_SIZE. We preserve\n the original.\n \"\"\"\n # Ignoruj wpisy z domy\u015blnymi obrazami\n if instance.image.name == settings.DEFAULT_IMG_PATH:\n return True\n # Zapisz kopi\u0119 orygina\u0142u jako JPEG\n base_image = Image.open(instance.image.path)\n filename = os.path.splitext(instance.image.path)[0]\n base_image.save(\"{}.jpg\".format(filename), 'JPEG')\n # Rozmiar obraz\u00f3w i miniatur pobieramy z ustawie\u0144 globalnych\n width, height = settings.DEFAULT_IMG_SIZE\n t_width, t_height = settings.DEFAULT_THUMB_SIZE\n # Normalne obrazki w pe\u0142nych wymiarach\n image = resize_image(base_image, (width * 2, height * 2))\n image.save(\"{}_fx@2x.jpg\".format(filename), 'JPEG')\n image = resize_image(base_image, (width, height))\n image.save(\"{}_fx.jpg\".format(filename), 'JPEG')\n # Miniatury do pokazania w widokach list i aktywno\u015bci\n image = resize_image(base_image, (t_width * 2, t_height * 2))\n image.save(\"{}_thumbnail@2x.jpg\".format(filename), 'JPEG')\n image = resize_image(base_image, (t_width, t_height))\n image.save(\"{}_thumbnail.jpg\".format(filename), 'JPEG')","function_tokens":["def","adjust_uploaded_image","(","sender",",","instance",",","*","*","kwargs",")",":","# Ignoruj wpisy z domy\u015blnymi obrazami","if","instance",".","image",".","name","==","settings",".","DEFAULT_IMG_PATH",":","return","True","# Zapisz kopi\u0119 orygina\u0142u jako JPEG","base_image","=","Image",".","open","(","instance",".","image",".","path",")","filename","=","os",".","path",".","splitext","(","instance",".","image",".","path",")","[","0","]","base_image",".","save","(","\"{}.jpg\"",".","format","(","filename",")",",","'JPEG'",")","# Rozmiar obraz\u00f3w i miniatur pobieramy z ustawie\u0144 globalnych","width",",","height","=","settings",".","DEFAULT_IMG_SIZE","t_width",",","t_height","=","settings",".","DEFAULT_THUMB_SIZE","# Normalne obrazki w pe\u0142nych wymiarach","image","=","resize_image","(","base_image",",","(","width","*","2",",","height","*","2",")",")","image",".","save","(","\"{}_fx@2x.jpg\"",".","format","(","filename",")",",","'JPEG'",")","image","=","resize_image","(","base_image",",","(","width",",","height",")",")","image",".","save","(","\"{}_fx.jpg\"",".","format","(","filename",")",",","'JPEG'",")","# Miniatury do pokazania w widokach list i aktywno\u015bci","image","=","resize_image","(","base_image",",","(","t_width","*","2",",","t_height","*","2",")",")","image",".","save","(","\"{}_thumbnail@2x.jpg\"",".","format","(","filename",")",",","'JPEG'",")","image","=","resize_image","(","base_image",",","(","t_width",",","t_height",")",")","image",".","save","(","\"{}_thumbnail.jpg\"",".","format","(","filename",")",",","'JPEG'",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L232-L258"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"fix_path","parameters":"(filepath, size='BIG')","argument_list":"","return_statement":"return \"\/\".join(path_parts)","docstring":"Returns path to fixed images (i.e. images with proper suffix) based on\n full path to image provided as argument.","docstring_summary":"Returns path to fixed images (i.e. images with proper suffix) based on\n full path to image provided as argument.","docstring_tokens":["Returns","path","to","fixed","images","(","i",".","e",".","images","with","proper","suffix",")","based","on","full","path","to","image","provided","as","argument","."],"function":"def fix_path(filepath, size='BIG'):\n \"\"\"\n Returns path to fixed images (i.e. images with proper suffix) based on\n full path to image provided as argument.\n \"\"\"\n path_parts = filepath.split('\/')\n name = path_parts.pop()\n size_prefix = \"%dx%d_\" % settings.CO_THUMB_SIZES.get(size.upper())\n path_parts.append(size_prefix + name)\n return \"\/\".join(path_parts)","function_tokens":["def","fix_path","(","filepath",",","size","=","'BIG'",")",":","path_parts","=","filepath",".","split","(","'\/'",")","name","=","path_parts",".","pop","(",")","size_prefix","=","\"%dx%d_\"","%","settings",".","CO_THUMB_SIZES",".","get","(","size",".","upper","(",")",")","path_parts",".","append","(","size_prefix","+","name",")","return","\"\/\"",".","join","(","path_parts",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L265-L274"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"crop","parameters":"(image, max_size)","argument_list":"","return_statement":"return image.crop(box)","docstring":"Takes PIL image and tuple with width and height and performs \"smart cut\".","docstring_summary":"Takes PIL image and tuple with width and height and performs \"smart cut\".","docstring_tokens":["Takes","PIL","image","and","tuple","with","width","and","height","and","performs","smart","cut","."],"function":"def crop(image, max_size):\n \"\"\" Takes PIL image and tuple with width and height and performs \"smart cut\".\n \"\"\"\n max_w, max_h = max_size\n width, height = image.getdata().size\n\n # Find ratio\n if height > width:\n ratio = float(max_w)\/float(width)\n image = image.resize((max_w, int(height*ratio)), Image.ANTIALIAS)\n box = (0, 0, max_w, max_h)\n else:\n ratio = float(max_h)\/float(height)\n new_width = int(width*ratio)\n image = image.resize((new_width, max_h), Image.ANTIALIAS)\n start_x = 0\n x_factor = max_w\n if new_width > max_w:\n start_x = int((float(new_width)-float(max_w))\/2)\n if new_width < max_w:\n nratio = float(max_w)\/float(new_width)\n cw, ch = image.getdata().size\n image = image.resize((max_w, int(float(ch)*nratio)), Image.ANTIALIAS)\n stop_x = start_x + x_factor\n box = (start_x, 0, stop_x, max_h)\n\n return image.crop(box)","function_tokens":["def","crop","(","image",",","max_size",")",":","max_w",",","max_h","=","max_size","width",",","height","=","image",".","getdata","(",")",".","size","# Find ratio","if","height",">","width",":","ratio","=","float","(","max_w",")","\/","float","(","width",")","image","=","image",".","resize","(","(","max_w",",","int","(","height","*","ratio",")",")",",","Image",".","ANTIALIAS",")","box","=","(","0",",","0",",","max_w",",","max_h",")","else",":","ratio","=","float","(","max_h",")","\/","float","(","height",")","new_width","=","int","(","width","*","ratio",")","image","=","image",".","resize","(","(","new_width",",","max_h",")",",","Image",".","ANTIALIAS",")","start_x","=","0","x_factor","=","max_w","if","new_width",">","max_w",":","start_x","=","int","(","(","float","(","new_width",")","-","float","(","max_w",")",")","\/","2",")","if","new_width","<","max_w",":","nratio","=","float","(","max_w",")","\/","float","(","new_width",")","cw",",","ch","=","image",".","getdata","(",")",".","size","image","=","image",".","resize","(","(","max_w",",","int","(","float","(","ch",")","*","nratio",")",")",",","Image",".","ANTIALIAS",")","stop_x","=","start_x","+","x_factor","box","=","(","start_x",",","0",",","stop_x",",","max_h",")","return","image",".","crop","(","box",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L277-L303"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image.py","language":"python","identifier":"generate_thumbs","parameters":"(filepath)","argument_list":"","return_statement":"","docstring":"Creates thumbs for all selected sizes for ContentObjectPicture.","docstring_summary":"Creates thumbs for all selected sizes for ContentObjectPicture.","docstring_tokens":["Creates","thumbs","for","all","selected","sizes","for","ContentObjectPicture","."],"function":"def generate_thumbs(filepath):\n \"\"\" Creates thumbs for all selected sizes for ContentObjectPicture.\n \"\"\"\n image = Image.open(filepath)\n\n # First convert all uploaded originals to JPG format\n image = image.convert('RGB')\n image.save(filepath, 'JPEG')\n\n for label, size in settings.CO_THUMB_SIZES.iteritems():\n thumb = crop(image.copy(), size)\n thumb.save(fix_path(filepath, label), 'JPEG')","function_tokens":["def","generate_thumbs","(","filepath",")",":","image","=","Image",".","open","(","filepath",")","# First convert all uploaded originals to JPG format","image","=","image",".","convert","(","'RGB'",")","image",".","save","(","filepath",",","'JPEG'",")","for","label",",","size","in","settings",".","CO_THUMB_SIZES",".","iteritems","(",")",":","thumb","=","crop","(","image",".","copy","(",")",",","size",")","thumb",".","save","(","fix_path","(","filepath",",","label",")",",","'JPEG'",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image.py#L306-L317"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"resize_image","parameters":"(image, max_width)","argument_list":"","return_statement":"return image.resize((max_width, int(float(img_height) * ratio)), Image.ANTIALIAS)","docstring":"Scales the image to the given width, preserving proportions.","docstring_summary":"Scales the image to the given width, preserving proportions.","docstring_tokens":["Scales","the","image","to","the","given","width","preserving","proportions","."],"function":"def resize_image(image, max_width):\n \"\"\" Scales the image to the given width, preserving proportions. \"\"\"\n img_width, img_height = image.getdata().size\n if img_width >= max_width and img_width >= img_height:\n # Obrazek do przeskalowania przez `thumbnail`\n img_copy = image.copy()\n img_copy.thumbnail((max_width, max_width), Image.ANTIALIAS)\n return img_copy\n ratio = float(max_width) \/ float(img_width)\n return image.resize((max_width, int(float(img_height) * ratio)), Image.ANTIALIAS)","function_tokens":["def","resize_image","(","image",",","max_width",")",":","img_width",",","img_height","=","image",".","getdata","(",")",".","size","if","img_width",">=","max_width","and","img_width",">=","img_height",":","# Obrazek do przeskalowania przez `thumbnail`","img_copy","=","image",".","copy","(",")","img_copy",".","thumbnail","(","(","max_width",",","max_width",")",",","Image",".","ANTIALIAS",")","return","img_copy","ratio","=","float","(","max_width",")","\/","float","(","img_width",")","return","image",".","resize","(","(","max_width",",","int","(","float","(","img_height",")","*","ratio",")",")",",","Image",".","ANTIALIAS",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L6-L15"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"perform_smart_cut","parameters":"(image, size)","argument_list":"","return_statement":"return image.crop(box)","docstring":"Crops the image to the exact sizes, preserves as much as it can.","docstring_summary":"Crops the image to the exact sizes, preserves as much as it can.","docstring_tokens":["Crops","the","image","to","the","exact","sizes","preserves","as","much","as","it","can","."],"function":"def perform_smart_cut(image, size):\n \"\"\" Crops the image to the exact sizes, preserves as much as it can. \"\"\"\n if size[0] >= size[1]:\n image = resize_image(image, size[0])\n new_width, new_height = image.getdata().size\n start_x = 0\n start_y = (new_height - size[1]) \/ 2\n stop_x = start_x + size[0]\n stop_y = start_y + size[1]\n\n box = (start_x, start_y, stop_x, stop_y)\n return image.crop(box)","function_tokens":["def","perform_smart_cut","(","image",",","size",")",":","if","size","[","0","]",">=","size","[","1","]",":","image","=","resize_image","(","image",",","size","[","0","]",")","new_width",",","new_height","=","image",".","getdata","(",")",".","size","start_x","=","0","start_y","=","(","new_height","-","size","[","1","]",")","\/","2","stop_x","=","start_x","+","size","[","0","]","stop_y","=","start_y","+","size","[","1","]","box","=","(","start_x",",","start_y",",","stop_x",",","stop_y",")","return","image",".","crop","(","box",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L18-L29"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"crop_thumbnail","parameters":"(image, size)","argument_list":"","return_statement":"return image.crop(box)","docstring":"Cuts out a minature from the cropped background image","docstring_summary":"Cuts out a minature from the cropped background image","docstring_tokens":["Cuts","out","a","minature","from","the","cropped","background","image"],"function":"def crop_thumbnail(image, size):\n \"\"\" Cuts out a minature from the cropped background image \"\"\"\n max_w, max_h = size\n width, height = image.getdata().size\n new_width = int(width * float(max_h)\/float(height))\n startx = int((new_width - max_w) \/ 2)\n image = image.resize((new_width, max_h), Image.ANTIALIAS)\n box = (startx, 0, startx + max_w, max_h)\n return image.crop(box)","function_tokens":["def","crop_thumbnail","(","image",",","size",")",":","max_w",",","max_h","=","size","width",",","height","=","image",".","getdata","(",")",".","size","new_width","=","int","(","width","*","float","(","max_h",")","\/","float","(","height",")",")","startx","=","int","(","(","new_width","-","max_w",")","\/","2",")","image","=","image",".","resize","(","(","new_width",",","max_h",")",",","Image",".","ANTIALIAS",")","box","=","(","startx",",","0",",","startx","+","max_w",",","max_h",")","return","image",".","crop","(","box",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L32-L40"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"fix_images","parameters":"()","argument_list":"","return_statement":"","docstring":"Creates image minatures and cropped background images for original files on the server.","docstring_summary":"Creates image minatures and cropped background images for original files on the server.","docstring_tokens":["Creates","image","minatures","and","cropped","background","images","for","original","files","on","the","server","."],"function":"def fix_images():\n \"\"\" Creates image minatures and cropped background images for original files on the server.\"\"\"\n import re\n from django.conf import settings\n\n max_width, max_height = settings.BACKGROUND_IMAGE_SIZE\n dirname = os.path.join(settings.BASE_DIR, 'media\/img\/locations')\n for filename in os.listdir(dirname):\n if not re.match(r'\\w+_\\d+', filename):\n im = ImageManager(os.path.join(dirname, filename), dirname)\n im.fixed_thumb(max_width, max_height)","function_tokens":["def","fix_images","(",")",":","import","re","from","django",".","conf","import","settings","max_width",",","max_height","=","settings",".","BACKGROUND_IMAGE_SIZE","dirname","=","os",".","path",".","join","(","settings",".","BASE_DIR",",","'media\/img\/locations'",")","for","filename","in","os",".","listdir","(","dirname",")",":","if","not","re",".","match","(","r'\\w+_\\d+'",",","filename",")",":","im","=","ImageManager","(","os",".","path",".","join","(","dirname",",","filename",")",",","dirname",")","im",".","fixed_thumb","(","max_width",",","max_height",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L101-L111"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"ImageManager._open_image","parameters":"(cls, filename)","argument_list":"","return_statement":"","docstring":"Returns PIL image if it is possible.","docstring_summary":"Returns PIL image if it is possible.","docstring_tokens":["Returns","PIL","image","if","it","is","possible","."],"function":"def _open_image(cls, filename):\n \"\"\" Returns PIL image if it is possible. \"\"\"\n try:\n return Image.open(filename)\n except (IOError, OSError):\n raise Exception(u\"Cannot open image file '%s'\" % filename)","function_tokens":["def","_open_image","(","cls",",","filename",")",":","try",":","return","Image",".","open","(","filename",")","except","(","IOError",",","OSError",")",":","raise","Exception","(","u\"Cannot open image file '%s'\"","%","filename",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L51-L56"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"ImageManager.create_filename","parameters":"(self, suffix, format='jpg')","argument_list":"","return_statement":"return os.path.join(self.dir, \"{}_{}.{}\".format(file, suffix, format))","docstring":"A Helper that will create a proper name for the file","docstring_summary":"A Helper that will create a proper name for the file","docstring_tokens":["A","Helper","that","will","create","a","proper","name","for","the","file"],"function":"def create_filename(self, suffix, format='jpg'):\n \"\"\" A Helper that will create a proper name for the file\"\"\"\n file, ext = os.path.splitext(self.filename)\n return os.path.join(self.dir, \"{}_{}.{}\".format(file, suffix, format))","function_tokens":["def","create_filename","(","self",",","suffix",",","format","=","'jpg'",")",":","file",",","ext","=","os",".","path",".","splitext","(","self",".","filename",")","return","os",".","path",".","join","(","self",".","dir",",","\"{}_{}.{}\"",".","format","(","file",",","suffix",",","format",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L58-L61"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"ImageManager.resize","parameters":"(self, width, height)","argument_list":"","return_statement":"","docstring":"We scale the image and preserve the proportions","docstring_summary":"We scale the image and preserve the proportions","docstring_tokens":["We","scale","the","image","and","preserve","the","proportions"],"function":"def resize(self, width, height):\n \"\"\" We scale the image and preserve the proportions\"\"\"\n image_w, image_h = self.image.size\n aspect_ratio = image_w \/ float(image_h)\n\n if image_h > image_w:\n ratio = width \/ float(image_w)\n return self.image.resize((width, int(image_h * ratio)), Image.ANTIALIAS)\n else:\n ratio = height \/ float(image_h)\n return self.image.resize((int(image_w * ratio), height), Image.ANTIALIAS)","function_tokens":["def","resize","(","self",",","width",",","height",")",":","image_w",",","image_h","=","self",".","image",".","size","aspect_ratio","=","image_w","\/","float","(","image_h",")","if","image_h",">","image_w",":","ratio","=","width","\/","float","(","image_w",")","return","self",".","image",".","resize","(","(","width",",","int","(","image_h","*","ratio",")",")",",","Image",".","ANTIALIAS",")","else",":","ratio","=","height","\/","float","(","image_h",")","return","self",".","image",".","resize","(","(","int","(","image_w","*","ratio",")",",","height",")",",","Image",".","ANTIALIAS",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L63-L73"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"ImageManager.smart_cut","parameters":"(self, width, height)","argument_list":"","return_statement":"return perform_smart_cut(self.image, (width, height))","docstring":"We crop and scale the image and preserve the proportions. Useful for\n minatures with equal proportions. The method makes sure that as much\n as possible of the original image will be visible.","docstring_summary":"We crop and scale the image and preserve the proportions. Useful for\n minatures with equal proportions. The method makes sure that as much\n as possible of the original image will be visible.","docstring_tokens":["We","crop","and","scale","the","image","and","preserve","the","proportions",".","Useful","for","minatures","with","equal","proportions",".","The","method","makes","sure","that","as","much","as","possible","of","the","original","image","will","be","visible","."],"function":"def smart_cut(self, width, height):\n \"\"\"\n We crop and scale the image and preserve the proportions. Useful for\n minatures with equal proportions. The method makes sure that as much\n as possible of the original image will be visible.\n \"\"\"\n return perform_smart_cut(self.image, (width, height))","function_tokens":["def","smart_cut","(","self",",","width",",","height",")",":","return","perform_smart_cut","(","self",".","image",",","(","width",",","height",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L75-L81"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"ImageManager.fixed_thumb","parameters":"(self, width, height)","argument_list":"","return_statement":"","docstring":"Creates a minature optimized for a given size.","docstring_summary":"Creates a minature optimized for a given size.","docstring_tokens":["Creates","a","minature","optimized","for","a","given","size","."],"function":"def fixed_thumb(self, width, height):\n \"\"\" Creates a minature optimized for a given size. \"\"\"\n img = self.smart_cut(width * 2, height * 2)\n img.save(self.create_filename(\"{}x{}@2x\".format(width, height)), 'JPEG')\n img = img.resize((width, height), Image.ANTIALIAS)\n img.save(self.create_filename(\"{}x{}\".format(width, height)), 'JPEG')\n\n # TODO: rozmiary miniatur powinny by\u0107 zdefiniowane w ustawieniach\n img = crop_thumbnail(img, (270, 190))\n img.save(self.create_filename(\"{}x{}\".format(270, 190)), 'JPEG')","function_tokens":["def","fixed_thumb","(","self",",","width",",","height",")",":","img","=","self",".","smart_cut","(","width","*","2",",","height","*","2",")","img",".","save","(","self",".","create_filename","(","\"{}x{}@2x\"",".","format","(","width",",","height",")",")",",","'JPEG'",")","img","=","img",".","resize","(","(","width",",","height",")",",","Image",".","ANTIALIAS",")","img",".","save","(","self",".","create_filename","(","\"{}x{}\"",".","format","(","width",",","height",")",")",",","'JPEG'",")","# TODO: rozmiary miniatur powinny by\u0107 zdefiniowane w ustawieniach","img","=","crop_thumbnail","(","img",",","(","270",",","190",")",")","img",".","save","(","self",".","create_filename","(","\"{}x{}\"",".","format","(","270",",","190",")",")",",","'JPEG'",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L83-L92"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/image_manager.py","language":"python","identifier":"ImageManager.__init__","parameters":"(self, filename, dirname=None)","argument_list":"","return_statement":"","docstring":"FIXME: tu nie wszystko b\u0119dzie teraz potrzebne.","docstring_summary":"FIXME: tu nie wszystko b\u0119dzie teraz potrzebne.","docstring_tokens":["FIXME",":","tu","nie","wszystko","b\u0119dzie","teraz","potrzebne","."],"function":"def __init__(self, filename, dirname=None):\n \"\"\" FIXME: tu nie wszystko b\u0119dzie teraz potrzebne. \"\"\"\n self.filename = filename.split('\/')[-1]\n self.image = self._open_image(filename)\n self.dir = dirname if dirname is not None else os.getcwd()","function_tokens":["def","__init__","(","self",",","filename",",","dirname","=","None",")",":","self",".","filename","=","filename",".","split","(","'\/'",")","[","-","1","]","self",".","image","=","self",".","_open_image","(","filename",")","self",".","dir","=","dirname","if","dirname","is","not","None","else","os",".","getcwd","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/image_manager.py#L94-L98"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/storage.py","language":"python","identifier":"check","parameters":"(gallery)","argument_list":"","return_statement":"","docstring":"Check if gallery directory exists or create new one if not.","docstring_summary":"Check if gallery directory exists or create new one if not.","docstring_tokens":["Check","if","gallery","directory","exists","or","create","new","one","if","not","."],"function":"def check(gallery):\n \"\"\" Check if gallery directory exists or create new one if not.\n \"\"\"\n if not gallery.dirname:\n gallery.dirname = uuid4().hex\n full_path = os.path.join(CONTENT_IMAGE_DIRNAME, gallery.dirname)\n if not os.path.exists(full_path):\n os.makedirs(full_path)","function_tokens":["def","check","(","gallery",")",":","if","not","gallery",".","dirname",":","gallery",".","dirname","=","uuid4","(",")",".","hex","full_path","=","os",".","path",".","join","(","CONTENT_IMAGE_DIRNAME",",","gallery",".","dirname",")","if","not","os",".","path",".","exists","(","full_path",")",":","os",".","makedirs","(","full_path",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/storage.py#L12-L19"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/storage.py","language":"python","identifier":"rmdir","parameters":"(gallery)","argument_list":"","return_statement":"","docstring":"Delete gallery image directory.","docstring_summary":"Delete gallery image directory.","docstring_tokens":["Delete","gallery","image","directory","."],"function":"def rmdir(gallery):\n \"\"\" Delete gallery image directory.\n \"\"\"\n full_path = os.path.join(CONTENT_IMAGE_DIRNAME, gallery.dirname)\n if os.path.exists(full_path):\n shutil.rmtree(full_path)","function_tokens":["def","rmdir","(","gallery",")",":","full_path","=","os",".","path",".","join","(","CONTENT_IMAGE_DIRNAME",",","gallery",".","dirname",")","if","os",".","path",".","exists","(","full_path",")",":","shutil",".","rmtree","(","full_path",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/storage.py#L22-L27"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/storage.py","language":"python","identifier":"upload_path","parameters":"(instance, filename)","argument_list":"","return_statement":"return 'galleries\/{}\/{}.jpg'.format(instance.gallery.dirname, uuid4().hex)","docstring":"Provides unique filename.","docstring_summary":"Provides unique filename.","docstring_tokens":["Provides","unique","filename","."],"function":"def upload_path(instance, filename):\n \"\"\" Provides unique filename.\n \"\"\"\n return 'galleries\/{}\/{}.jpg'.format(instance.gallery.dirname, uuid4().hex)","function_tokens":["def","upload_path","(","instance",",","filename",")",":","return","'galleries\/{}\/{}.jpg'",".","format","(","instance",".","gallery",".","dirname",",","uuid4","(",")",".","hex",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/storage.py#L30-L33"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/storage.py","language":"python","identifier":"massrm","parameters":"(picture)","argument_list":"","return_statement":"","docstring":"Delete original and all fixed files for picture.","docstring_summary":"Delete original and all fixed files for picture.","docstring_tokens":["Delete","original","and","all","fixed","files","for","picture","."],"function":"def massrm(picture):\n \"\"\" Delete original and all fixed files for picture.\n \"\"\"\n clean_filename, ext = os.path.splitext(picture.image.path.split('\/')[-1])\n full_path = os.path.join(CONTENT_IMAGE_DIRNAME, picture.gallery.dirname)\n for root, dirnames, files in os.walk(full_path):\n for name in files:\n if clean_filename in name:\n os.unlink(os.path.join(root, name))","function_tokens":["def","massrm","(","picture",")",":","clean_filename",",","ext","=","os",".","path",".","splitext","(","picture",".","image",".","path",".","split","(","'\/'",")","[","-","1","]",")","full_path","=","os",".","path",".","join","(","CONTENT_IMAGE_DIRNAME",",","picture",".","gallery",".","dirname",")","for","root",",","dirnames",",","files","in","os",".","walk","(","full_path",")",":","for","name","in","files",":","if","clean_filename","in","name",":","os",".","unlink","(","os",".","path",".","join","(","root",",","name",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/storage.py#L36-L44"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/models.py","language":"python","identifier":"UserGalleryItem.url","parameters":"(self)","argument_list":"","return_statement":"return settings.MEDIA_URL + self.user.username + '\/' + self.picture_name","docstring":"Returns picture url. This function is most useful for views.","docstring_summary":"Returns picture url. This function is most useful for views.","docstring_tokens":["Returns","picture","url",".","This","function","is","most","useful","for","views","."],"function":"def url(self):\n \"\"\"\n Returns picture url. This function is most useful for views.\n \"\"\"\n return settings.MEDIA_URL + self.user.username + '\/' + self.picture_name","function_tokens":["def","url","(","self",")",":","return","settings",".","MEDIA_URL","+","self",".","user",".","username","+","'\/'","+","self",".","picture_name"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/models.py#L83-L87"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/models.py","language":"python","identifier":"UserGalleryItem.get_thumbnail","parameters":"(self, size)","argument_list":"","return_statement":"return settings.MEDIA_URL + self.user.username + '\/thumbs\/' + thumbname","docstring":"This function returns url to thumbnail of photo. Size parameter is man-\n datory and related to thumb sizes declared in views module. It should\n be touple or list containing images width and height.","docstring_summary":"This function returns url to thumbnail of photo. Size parameter is man-\n datory and related to thumb sizes declared in views module. It should\n be touple or list containing images width and height.","docstring_tokens":["This","function","returns","url","to","thumbnail","of","photo",".","Size","parameter","is","man","-","datory","and","related","to","thumb","sizes","declared","in","views","module",".","It","should","be","touple","or","list","containing","images","width","and","height","."],"function":"def get_thumbnail(self, size):\n \"\"\"\n This function returns url to thumbnail of photo. Size parameter is man-\n datory and related to thumb sizes declared in views module. It should\n be touple or list containing images width and height.\n \"\"\"\n thumbname = str(size[0]) + 'x' + str(size[1]) + '_' + self.picture_name\n return settings.MEDIA_URL + self.user.username + '\/thumbs\/' + thumbname","function_tokens":["def","get_thumbnail","(","self",",","size",")",":","thumbname","=","str","(","size","[","0","]",")","+","'x'","+","str","(","size","[","1","]",")","+","'_'","+","self",".","picture_name","return","settings",".","MEDIA_URL","+","self",".","user",".","username","+","'\/thumbs\/'","+","thumbname"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/models.py#L89-L96"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/models.py","language":"python","identifier":"LocationGalleryItem.url","parameters":"(self)","argument_list":"","return_statement":"return settings.MEDIA_URL + self.location.slug + '\/' + self.picture_name","docstring":"Returns picture url. This function is most useful for views.","docstring_summary":"Returns picture url. This function is most useful for views.","docstring_tokens":["Returns","picture","url",".","This","function","is","most","useful","for","views","."],"function":"def url(self):\n \"\"\" Returns picture url. This function is most useful for views.\n \"\"\"\n return settings.MEDIA_URL + self.location.slug + '\/' + self.picture_name","function_tokens":["def","url","(","self",")",":","return","settings",".","MEDIA_URL","+","self",".","location",".","slug","+","'\/'","+","self",".","picture_name"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/models.py#L124-L127"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"gallery\/models.py","language":"python","identifier":"LocationGalleryItem.get_thumbnail","parameters":"(self, size)","argument_list":"","return_statement":"return settings.MEDIA_URL + self.location.slug + '\/thumbs\/' + thumbname","docstring":"This function returns url to thumbnail of photo. Size parameter is man-\n datory and related to thumb sizes declared in views module. It should\n be touple or list containing images width and height.","docstring_summary":"This function returns url to thumbnail of photo. Size parameter is man-\n datory and related to thumb sizes declared in views module. It should\n be touple or list containing images width and height.","docstring_tokens":["This","function","returns","url","to","thumbnail","of","photo",".","Size","parameter","is","man","-","datory","and","related","to","thumb","sizes","declared","in","views","module",".","It","should","be","touple","or","list","containing","images","width","and","height","."],"function":"def get_thumbnail(self, size):\n \"\"\"\n This function returns url to thumbnail of photo. Size parameter is man-\n datory and related to thumb sizes declared in views module. It should\n be touple or list containing images width and height.\n \"\"\"\n thumbname = str(size[0]) + 'x' + str(size[1]) + '_' + self.picture_name\n return settings.MEDIA_URL + self.location.slug + '\/thumbs\/' + thumbname","function_tokens":["def","get_thumbnail","(","self",",","size",")",":","thumbname","=","str","(","size","[","0","]",")","+","'x'","+","str","(","size","[","1","]",")","+","'_'","+","self",".","picture_name","return","settings",".","MEDIA_URL","+","self",".","location",".","slug","+","'\/thumbs\/'","+","thumbname"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/gallery\/models.py#L129-L136"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"ideas\/models.py","language":"python","identifier":"vote_notification","parameters":"(sender, instance, created, **kwargs)","argument_list":"","return_statement":"","docstring":"Notify users that someone voted for their ideas.","docstring_summary":"Notify users that someone voted for their ideas.","docstring_tokens":["Notify","users","that","someone","voted","for","their","ideas","."],"function":"def vote_notification(sender, instance, created, **kwargs):\n \"\"\" Notify users that someone voted for their ideas. \"\"\"\n if instance.user == instance.idea.creator or not created:\n return True\n suff = \"up\" if instance.status == 1 else \"down\"\n notify(instance.user, instance.idea.creator,\n key=\"vote\",\n verb=\"voted for your idea\",\n action_object=instance,\n action_target=instance.idea)","function_tokens":["def","vote_notification","(","sender",",","instance",",","created",",","*","*","kwargs",")",":","if","instance",".","user","==","instance",".","idea",".","creator","or","not","created",":","return","True","suff","=","\"up\"","if","instance",".","status","==","1","else","\"down\"","notify","(","instance",".","user",",","instance",".","idea",".","creator",",","key","=","\"vote\"",",","verb","=","\"voted for your idea\"",",","action_object","=","instance",",","action_target","=","instance",".","idea",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/ideas\/models.py#L264-L273"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"ideas\/templatetags\/idea_tags.py","language":"python","identifier":"vote_area","parameters":"(context, obj)","argument_list":"","return_statement":"return template.render(ctx)","docstring":"Create voting buttons and statistics. We provide common class names and\n Data parameters so that scripts can be easily added. Here, we determine\n the initial state of buttons.","docstring_summary":"Create voting buttons and statistics. We provide common class names and\n Data parameters so that scripts can be easily added. Here, we determine\n the initial state of buttons.","docstring_tokens":["Create","voting","buttons","and","statistics",".","We","provide","common","class","names","and","Data","parameters","so","that","scripts","can","be","easily","added",".","Here","we","determine","the","initial","state","of","buttons","."],"function":"def vote_area(context, obj):\n \"\"\" Create voting buttons and statistics. We provide common class names and\n Data parameters so that scripts can be easily added. Here, we determine\n the initial state of buttons.\n \"\"\"\n if context.get('experiment') is not None:\n template = loader.get_template('ideas\/vote_area_b.html')\n else:\n template = loader.get_template('ideas\/vote_area.html')\n if obj is None:\n return ''\n user = context['user']\n ctx = Context({'user': user, 'idea': obj, 'request': context['request']})\n if user.is_anonymous():\n pass\n elif len(obj.vote_set.filter(user=user, status=1)):\n ctx.update({'voted_up': True, })\n elif len(obj.vote_set.filter(user=user, status=2)):\n ctx.update({'voted_no': True, })\n return template.render(ctx)","function_tokens":["def","vote_area","(","context",",","obj",")",":","if","context",".","get","(","'experiment'",")","is","not","None",":","template","=","loader",".","get_template","(","'ideas\/vote_area_b.html'",")","else",":","template","=","loader",".","get_template","(","'ideas\/vote_area.html'",")","if","obj","is","None",":","return","''","user","=","context","[","'user'","]","ctx","=","Context","(","{","'user'",":","user",",","'idea'",":","obj",",","'request'",":","context","[","'request'","]","}",")","if","user",".","is_anonymous","(",")",":","pass","elif","len","(","obj",".","vote_set",".","filter","(","user","=","user",",","status","=","1",")",")",":","ctx",".","update","(","{","'voted_up'",":","True",",","}",")","elif","len","(","obj",".","vote_set",".","filter","(","user","=","user",",","status","=","2",")",")",":","ctx",".","update","(","{","'voted_no'",":","True",",","}",")","return","template",".","render","(","ctx",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/ideas\/templatetags\/idea_tags.py#L7-L26"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"simpleblog\/signals.py","language":"python","identifier":"blog_entry_created_action","parameters":"(sender, instance, created, **kwargs)","argument_list":"","return_statement":"","docstring":"Notify followers about new blog entries related to some other objects.","docstring_summary":"Notify followers about new blog entries related to some other objects.","docstring_tokens":["Notify","followers","about","new","blog","entries","related","to","some","other","objects","."],"function":"def blog_entry_created_action(sender, instance, created, **kwargs):\n \"\"\"\n Notify followers about new blog entries related to some other objects.\n \"\"\"\n if not created:\n return True\n if instance.content_object is None:\n action.send(instance.author,\n action_object=instance,\n verb=_('created'))\n else:\n action.send(instance.author,\n action_object=instance,\n verb=_('created'),\n target=instance.content_object)","function_tokens":["def","blog_entry_created_action","(","sender",",","instance",",","created",",","*","*","kwargs",")",":","if","not","created",":","return","True","if","instance",".","content_object","is","None",":","action",".","send","(","instance",".","author",",","action_object","=","instance",",","verb","=","_","(","'created'",")",")","else",":","action",".","send","(","instance",".","author",",","action_object","=","instance",",","verb","=","_","(","'created'",")",",","target","=","instance",".","content_object",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/simpleblog\/signals.py#L7-L21"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"simpleblog\/models.py","language":"python","identifier":"BlogManager.get_published_in","parameters":"(self, obj)","argument_list":"","return_statement":"return super(BlogManager, self).get_queryset()\\\n .filter(content_type__id=ct, object_id=obj.pk)","docstring":"Return list of blog entries published (tied to) given object.","docstring_summary":"Return list of blog entries published (tied to) given object.","docstring_tokens":["Return","list","of","blog","entries","published","(","tied","to",")","given","object","."],"function":"def get_published_in(self, obj):\n \"\"\"\n Return list of blog entries published (tied to) given object.\n \"\"\"\n ct = ContentType.objects.get_for_model(obj).pk\n return super(BlogManager, self).get_queryset()\\\n .filter(content_type__id=ct, object_id=obj.pk)","function_tokens":["def","get_published_in","(","self",",","obj",")",":","ct","=","ContentType",".","objects",".","get_for_model","(","obj",")",".","pk","return","super","(","BlogManager",",","self",")",".","get_queryset","(",")",".","filter","(","content_type__id","=","ct",",","object_id","=","obj",".","pk",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/simpleblog\/models.py#L25-L31"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"simpleblog\/models.py","language":"python","identifier":"BlogManager.get_published_by","parameters":"(self, user)","argument_list":"","return_statement":"return super(BlogManager, self).get_queryset().filter(author=user)","docstring":"Return all blog entries created by given user.","docstring_summary":"Return all blog entries created by given user.","docstring_tokens":["Return","all","blog","entries","created","by","given","user","."],"function":"def get_published_by(self, user):\n \"\"\"\n Return all blog entries created by given user.\n \"\"\"\n return super(BlogManager, self).get_queryset().filter(author=user)","function_tokens":["def","get_published_by","(","self",",","user",")",":","return","super","(","BlogManager",",","self",")",".","get_queryset","(",")",".","filter","(","author","=","user",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/simpleblog\/models.py#L33-L37"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"simpleblog\/templatetags\/simpleblog_tags.py","language":"python","identifier":"newscounter","parameters":"(obj)","argument_list":"","return_statement":"return BlogEntry.objects.get_published_in(obj).count()","docstring":"Count simpleblog entries published for selected content object.","docstring_summary":"Count simpleblog entries published for selected content object.","docstring_tokens":["Count","simpleblog","entries","published","for","selected","content","object","."],"function":"def newscounter(obj):\n \"\"\" Count simpleblog entries published for selected content object.\n\t\"\"\"\n return BlogEntry.objects.get_published_in(obj).count()","function_tokens":["def","newscounter","(","obj",")",":","return","BlogEntry",".","objects",".","get_published_in","(","obj",")",".","count","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/simpleblog\/templatetags\/simpleblog_tags.py#L7-L10"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"notifications\/views.py","language":"python","identifier":"NotificationView.get_object","parameters":"(self)","argument_list":"","return_statement":"return self.object","docstring":"Make sure that only owner can mark notification as read.","docstring_summary":"Make sure that only owner can mark notification as read.","docstring_tokens":["Make","sure","that","only","owner","can","mark","notification","as","read","."],"function":"def get_object(self):\n \"\"\" Make sure that only owner can mark notification as read. \"\"\"\n self.object = super(NotificationView, self).get_object()\n if self.object.user != self.request.user:\n raise PermissionDenied\n self.object.read()\n return self.object","function_tokens":["def","get_object","(","self",")",":","self",".","object","=","super","(","NotificationView",",","self",")",".","get_object","(",")","if","self",".","object",".","user","!=","self",".","request",".","user",":","raise","PermissionDenied","self",".","object",".","read","(",")","return","self",".","object"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/notifications\/views.py#L27-L33"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"notifications\/serializers.py","language":"python","identifier":"serializer_object","parameters":"(obj)","argument_list":"","return_statement":"return data","docstring":"Serialize object instcane via native Django seraializer and return as JSON.","docstring_summary":"Serialize object instcane via native Django seraializer and return as JSON.","docstring_tokens":["Serialize","object","instcane","via","native","Django","seraializer","and","return","as","JSON","."],"function":"def serializer_object(obj):\n \"\"\"\n Serialize object instcane via native Django seraializer and return as JSON.\n \"\"\"\n if obj is None:\n return None\n data = json.loads(dj_serializers.serialize('json', [obj,]))[0]\n if hasattr(obj, 'get_absolute_url'):\n data['url'] = obj.get_absolute_url()\n return data","function_tokens":["def","serializer_object","(","obj",")",":","if","obj","is","None",":","return","None","data","=","json",".","loads","(","dj_serializers",".","serialize","(","'json'",",","[","obj",",","]",")",")","[","0","]","if","hasattr","(","obj",",","'get_absolute_url'",")",":","data","[","'url'","]","=","obj",".","get_absolute_url","(",")","return","data"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/notifications\/serializers.py#L15-L24"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"notifications\/serializers.py","language":"python","identifier":"NotificationSerializer.get_action_url","parameters":"(self, obj)","argument_list":"","return_statement":"return action_url","docstring":"Try to find most appropriate url for this kind of notification.","docstring_summary":"Try to find most appropriate url for this kind of notification.","docstring_tokens":["Try","to","find","most","appropriate","url","for","this","kind","of","notification","."],"function":"def get_action_url(self, obj):\n \"\"\" Try to find most appropriate url for this kind of notification. \"\"\"\n # If there is no better match, point to actor profile url\n action_url = obj.action_actor.profile.get_absolute_url()\n # Fallback if action_target is undefined:\n if obj.action_object is not None:\n if hasattr(obj.action_object, 'get_absolute_url'):\n action_url = obj.action_object.get_absolute_url()\n # And most preferred option - get url from action target\n elif obj.action_target is not None:\n if hasattr(obj.action_target, 'get_absolute_url'):\n action_url = obj.action_target.get_absolute_url()\n return action_url","function_tokens":["def","get_action_url","(","self",",","obj",")",":","# If there is no better match, point to actor profile url","action_url","=","obj",".","action_actor",".","profile",".","get_absolute_url","(",")","# Fallback if action_target is undefined:","if","obj",".","action_object","is","not","None",":","if","hasattr","(","obj",".","action_object",",","'get_absolute_url'",")",":","action_url","=","obj",".","action_object",".","get_absolute_url","(",")","# And most preferred option - get url from action target","elif","obj",".","action_target","is","not","None",":","if","hasattr","(","obj",".","action_target",",","'get_absolute_url'",")",":","action_url","=","obj",".","action_target",".","get_absolute_url","(",")","return","action_url"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/notifications\/serializers.py#L61-L73"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"notifications\/api.py","language":"python","identifier":"NotificationViewSet.retrieve","parameters":"(self, request, pk=None)","argument_list":"","return_statement":"return super(NotificationViewSet, self).retrieve(request, pk)","docstring":"Be sure to mark this object as read.","docstring_summary":"Be sure to mark this object as read.","docstring_tokens":["Be","sure","to","mark","this","object","as","read","."],"function":"def retrieve(self, request, pk=None):\n \"\"\"\n Be sure to mark this object as read.\n \"\"\"\n obj = self.get_object()\n obj.read()\n return super(NotificationViewSet, self).retrieve(request, pk)","function_tokens":["def","retrieve","(","self",",","request",",","pk","=","None",")",":","obj","=","self",".","get_object","(",")","obj",".","read","(",")","return","super","(","NotificationViewSet",",","self",")",".","retrieve","(","request",",","pk",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/notifications\/api.py#L28-L34"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"notifications\/models.py","language":"python","identifier":"notify","parameters":"(actor, user, **kwargs)","argument_list":"","return_statement":"","docstring":"Create proper notification based on passed values.","docstring_summary":"Create proper notification based on passed values.","docstring_tokens":["Create","proper","notification","based","on","passed","values","."],"function":"def notify(actor, user, **kwargs):\n \"\"\" Create proper notification based on passed values. \"\"\"\n notify = Notification(user=user, action_actor=actor)\n action_object = kwargs.get('action_object')\n if action_object is not None:\n notify.action_object_ct = ContentType.objects.get_for_model(action_object)\n notify.action_object_id = action_object.pk\n action_target = kwargs.get('action_target')\n if action_target is not None:\n notify.action_target_ct = ContentType.objects.get_for_model(action_target)\n notify.action_target_id = action_target.pk\n keyword = kwargs.get('key')\n if keyword is not None:\n notify.key = keyword\n verb = kwargs.get('verb')\n if verb is not None:\n notify.action_verb = verb\n notify.save()","function_tokens":["def","notify","(","actor",",","user",",","*","*","kwargs",")",":","notify","=","Notification","(","user","=","user",",","action_actor","=","actor",")","action_object","=","kwargs",".","get","(","'action_object'",")","if","action_object","is","not","None",":","notify",".","action_object_ct","=","ContentType",".","objects",".","get_for_model","(","action_object",")","notify",".","action_object_id","=","action_object",".","pk","action_target","=","kwargs",".","get","(","'action_target'",")","if","action_target","is","not","None",":","notify",".","action_target_ct","=","ContentType",".","objects",".","get_for_model","(","action_target",")","notify",".","action_target_id","=","action_target",".","pk","keyword","=","kwargs",".","get","(","'key'",")","if","keyword","is","not","None",":","notify",".","key","=","keyword","verb","=","kwargs",".","get","(","'verb'",")","if","verb","is","not","None",":","notify",".","action_verb","=","verb","notify",".","save","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/notifications\/models.py#L106-L123"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"notifications\/models.py","language":"python","identifier":"NotificationManager.count_unread_for_user","parameters":"(self, user)","argument_list":"","return_statement":"return qs.filter(user=user, checked_at__isnull=True).count()","docstring":"This method takes user instance and returns number of unread\n notifications belonging to him.","docstring_summary":"This method takes user instance and returns number of unread\n notifications belonging to him.","docstring_tokens":["This","method","takes","user","instance","and","returns","number","of","unread","notifications","belonging","to","him","."],"function":"def count_unread_for_user(self, user):\n \"\"\" This method takes user instance and returns number of unread\n notifications belonging to him. \"\"\"\n qs = super(NotificationManager, self).get_queryset()\n return qs.filter(user=user, checked_at__isnull=True).count()","function_tokens":["def","count_unread_for_user","(","self",",","user",")",":","qs","=","super","(","NotificationManager",",","self",")",".","get_queryset","(",")","return","qs",".","filter","(","user","=","user",",","checked_at__isnull","=","True",")",".","count","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/notifications\/models.py#L20-L24"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"notifications\/models.py","language":"python","identifier":"NotificationManager.unread_for_user","parameters":"(self, user)","argument_list":"","return_statement":"return qs.filter(user=user, checked_at__isnull=True)","docstring":"Find all unread notifications for particular user instance.","docstring_summary":"Find all unread notifications for particular user instance.","docstring_tokens":["Find","all","unread","notifications","for","particular","user","instance","."],"function":"def unread_for_user(self, user):\n \"\"\" Find all unread notifications for particular user instance. \"\"\"\n qs = super(NotificationManager, self).get_queryset()\n return qs.filter(user=user, checked_at__isnull=True)","function_tokens":["def","unread_for_user","(","self",",","user",")",":","qs","=","super","(","NotificationManager",",","self",")",".","get_queryset","(",")","return","qs",".","filter","(","user","=","user",",","checked_at__isnull","=","True",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/notifications\/models.py#L26-L29"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"notifications\/templatetags\/notify_tags.py","language":"python","identifier":"unread_notifications","parameters":"(parser, token)","argument_list":"","return_statement":"","docstring":"Give the number of unread notifications for a user,\n or nothing (an empty string) for an anonymous user.\n Storing the count in a variable for further processing is advised, such as::\n {% unread_notifications as unread_count %}\n ...\n {% if unread_count %}\n You have {{ unread_count }}<\/strong> unread notifications.\n {% endif %}","docstring_summary":"Give the number of unread notifications for a user,\n or nothing (an empty string) for an anonymous user.\n Storing the count in a variable for further processing is advised, such as::\n {% unread_notifications as unread_count %}\n ...\n {% if unread_count %}\n You have {{ unread_count }}<\/strong> unread notifications.\n {% endif %}","docstring_tokens":["Give","the","number","of","unread","notifications","for","a","user","or","nothing","(","an","empty","string",")","for","an","anonymous","user",".","Storing","the","count","in","a","variable","for","further","processing","is","advised","such","as","::","{","%","unread_notifications","as","unread_count","%","}","...","{","%","if","unread_count","%","}","You","have","","{{","unread_count","}}","<","\/","strong",">","unread","notifications",".","{","%","endif","%","}"],"function":"def unread_notifications(parser, token):\n \"\"\"\n Give the number of unread notifications for a user,\n or nothing (an empty string) for an anonymous user.\n Storing the count in a variable for further processing is advised, such as::\n {% unread_notifications as unread_count %}\n ...\n {% if unread_count %}\n You have {{ unread_count }}<\/strong> unread notifications.\n {% endif %}\n \"\"\"\n bits = token.split_contents()\n if len(bits) > 1:\n if len(bits) != 3:\n raise TemplateSyntaxError(\"'{0}' tag takes no argument or exactly two arguments\".format(bits[0]))\n if bits[1] != 'as':\n raise TemplateSyntaxError(\"First argument to '{0}' tag must be 'as'\".format(bits[0]))\n return UnreadCountNode(bits[2])\n else:\n return UnreadCountNode()","function_tokens":["def","unread_notifications","(","parser",",","token",")",":","bits","=","token",".","split_contents","(",")","if","len","(","bits",")",">","1",":","if","len","(","bits",")","!=","3",":","raise","TemplateSyntaxError","(","\"'{0}' tag takes no argument or exactly two arguments\"",".","format","(","bits","[","0","]",")",")","if","bits","[","1","]","!=","'as'",":","raise","TemplateSyntaxError","(","\"First argument to '{0}' tag must be 'as'\"",".","format","(","bits","[","0","]",")",")","return","UnreadCountNode","(","bits","[","2","]",")","else",":","return","UnreadCountNode","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/notifications\/templatetags\/notify_tags.py#L36-L55"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"notifications\/templatetags\/notify_tags.py","language":"python","identifier":"UnreadCountNode.render","parameters":"(self, context)","argument_list":"","return_statement":"return count","docstring":"Return the count of unread notifications for the user found in context,\n (may be 0) or an empty string.","docstring_summary":"Return the count of unread notifications for the user found in context,\n (may be 0) or an empty string.","docstring_tokens":["Return","the","count","of","unread","notifications","for","the","user","found","in","context","(","may","be","0",")","or","an","empty","string","."],"function":"def render(self, context):\n \"\"\"\n Return the count of unread notifications for the user found in context,\n (may be 0) or an empty string.\n \"\"\"\n try:\n user = context['user']\n if user.is_anonymous():\n count = ''\n else:\n count = Notification.objects.count_unread_for_user(user)\n except (KeyError, AttributeError):\n count = ''\n if self.asvar:\n context[self.asvar] = count\n return ''\n return count","function_tokens":["def","render","(","self",",","context",")",":","try",":","user","=","context","[","'user'","]","if","user",".","is_anonymous","(",")",":","count","=","''","else",":","count","=","Notification",".","objects",".","count_unread_for_user","(","user",")","except","(","KeyError",",","AttributeError",")",":","count","=","''","if","self",".","asvar",":","context","[","self",".","asvar","]","=","count","return","''","return","count"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/notifications\/templatetags\/notify_tags.py#L16-L32"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"hitcounter\/views.py","language":"python","identifier":"visit_view","parameters":"(request, ct, pk)","argument_list":"","return_statement":"return HttpResponse(json.dumps({'id': visit.pk, }), content_type=\"application\/json\")","docstring":"This view should be used along with some front-end scripts.\n This way we can exclude robots from records.","docstring_summary":"This view should be used along with some front-end scripts.\n This way we can exclude robots from records.","docstring_tokens":["This","view","should","be","used","along","with","some","front","-","end","scripts",".","This","way","we","can","exclude","robots","from","records","."],"function":"def visit_view(request, ct, pk):\n \"\"\"\n This view should be used along with some front-end scripts.\n This way we can exclude robots from records.\n \"\"\"\n visit = Visit.objects.create(ip=get_ip(request), content_type_id=ct, object_id=pk)\n return HttpResponse(json.dumps({'id': visit.pk, }), content_type=\"application\/json\")","function_tokens":["def","visit_view","(","request",",","ct",",","pk",")",":","visit","=","Visit",".","objects",".","create","(","ip","=","get_ip","(","request",")",",","content_type_id","=","ct",",","object_id","=","pk",")","return","HttpResponse","(","json",".","dumps","(","{","'id'",":","visit",".","pk",",","}",")",",","content_type","=","\"application\/json\"",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/hitcounter\/views.py#L13-L19"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"hitcounter\/models.py","language":"python","identifier":"VisitManager.count_for_object","parameters":"(self, instance)","argument_list":"","return_statement":"return sum([x.visit_count for x in qs.filter(\n content_type=ct, object_id=instance.pk)])","docstring":"Returns total count for this object.","docstring_summary":"Returns total count for this object.","docstring_tokens":["Returns","total","count","for","this","object","."],"function":"def count_for_object(self, instance):\n \"\"\" Returns total count for this object. \"\"\"\n qs = super(VisitManager, self).get_queryset()\n ct = ContentType.objects.get_for_model(instance)\n return sum([x.visit_count for x in qs.filter(\n content_type=ct, object_id=instance.pk)])","function_tokens":["def","count_for_object","(","self",",","instance",")",":","qs","=","super","(","VisitManager",",","self",")",".","get_queryset","(",")","ct","=","ContentType",".","objects",".","get_for_model","(","instance",")","return","sum","(","[","x",".","visit_count","for","x","in","qs",".","filter","(","content_type","=","ct",",","object_id","=","instance",".","pk",")","]",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/hitcounter\/models.py#L17-L22"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"hitcounter\/models.py","language":"python","identifier":"VisitManager.count_unique_for_object","parameters":"(self, instance)","argument_list":"","return_statement":"return len(qs.filter(content_type=ct, object_id=instance.pk))","docstring":"Count only one visit for each IP address.","docstring_summary":"Count only one visit for each IP address.","docstring_tokens":["Count","only","one","visit","for","each","IP","address","."],"function":"def count_unique_for_object(self, instance):\n \"\"\" Count only one visit for each IP address. \"\"\"\n qs = super(VisitManager, self).get_queryset()\n ct = ContentType.objects.get_for_model(instance)\n return len(qs.filter(content_type=ct, object_id=instance.pk))","function_tokens":["def","count_unique_for_object","(","self",",","instance",")",":","qs","=","super","(","VisitManager",",","self",")",".","get_queryset","(",")","ct","=","ContentType",".","objects",".","get_for_model","(","instance",")","return","len","(","qs",".","filter","(","content_type","=","ct",",","object_id","=","instance",".","pk",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/hitcounter\/models.py#L24-L28"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"hitcounter\/decorators.py","language":"python","identifier":"ajax_required","parameters":"(f)","argument_list":"","return_statement":"return wrap","docstring":"AJAX request required decorator\n use it in your views:\n\n @ajax_required\n def my_view(request):\n ....","docstring_summary":"AJAX request required decorator\n use it in your views:","docstring_tokens":["AJAX","request","required","decorator","use","it","in","your","views",":"],"function":"def ajax_required(f):\n \"\"\"\n AJAX request required decorator\n use it in your views:\n\n @ajax_required\n def my_view(request):\n ....\n\n \"\"\"\n def wrap(request, *args, **kwargs):\n if not request.is_ajax():\n return HttpResponseBadRequest()\n return f(request, *args, **kwargs)\n wrap.__doc__=f.__doc__\n wrap.__name__=f.__name__\n return wrap","function_tokens":["def","ajax_required","(","f",")",":","def","wrap","(","request",",","*","args",",","*","*","kwargs",")",":","if","not","request",".","is_ajax","(",")",":","return","HttpResponseBadRequest","(",")","return","f","(","request",",","*","args",",","*","*","kwargs",")","wrap",".","__doc__","=","f",".","__doc__","wrap",".","__name__","=","f",".","__name__","return","wrap"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/hitcounter\/decorators.py#L3-L19"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"hitcounter\/templatetags\/counters.py","language":"python","identifier":"render_node","parameters":"(counter, instance)","argument_list":"","return_statement":"return '{}<\/span>'\\\n .format(ct, instance.pk, counter)","docstring":"Helper function - adds data-ct and data-pk to HTML attributes.","docstring_summary":"Helper function - adds data-ct and data-pk to HTML attributes.","docstring_tokens":["Helper","function","-","adds","data","-","ct","and","data","-","pk","to","HTML","attributes","."],"function":"def render_node(counter, instance):\n \"\"\"\n Helper function - adds data-ct and data-pk to HTML attributes.\n \"\"\"\n ct = ContentType.objects.get_for_model(instance).pk\n return '{}<\/span>'\\\n .format(ct, instance.pk, counter)","function_tokens":["def","render_node","(","counter",",","instance",")",":","ct","=","ContentType",".","objects",".","get_for_model","(","instance",")",".","pk","return","'{}<\/span>'",".","format","(","ct",",","instance",".","pk",",","counter",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/hitcounter\/templatetags\/counters.py#L10-L16"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"hitcounter\/templatetags\/counters.py","language":"python","identifier":"visit_counter","parameters":"(obj)","argument_list":"","return_statement":"return render_node(Visit.objects.count_for_object(obj), obj)","docstring":"Returns total visit count for specified object.","docstring_summary":"Returns total visit count for specified object.","docstring_tokens":["Returns","total","visit","count","for","specified","object","."],"function":"def visit_counter(obj):\n \"\"\"\n Returns total visit count for specified object.\n \"\"\"\n return render_node(Visit.objects.count_for_object(obj), obj)","function_tokens":["def","visit_counter","(","obj",")",":","return","render_node","(","Visit",".","objects",".","count_for_object","(","obj",")",",","obj",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/hitcounter\/templatetags\/counters.py#L20-L24"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"hitcounter\/templatetags\/counters.py","language":"python","identifier":"unique_counter","parameters":"(obj)","argument_list":"","return_statement":"return render_node(Visit.objects.count_unique_for_object(obj), obj)","docstring":"Returns visit count unique for ip addresses.","docstring_summary":"Returns visit count unique for ip addresses.","docstring_tokens":["Returns","visit","count","unique","for","ip","addresses","."],"function":"def unique_counter(obj):\n \"\"\"\n Returns visit count unique for ip addresses.\n \"\"\"\n return render_node(Visit.objects.count_unique_for_object(obj), obj)","function_tokens":["def","unique_counter","(","obj",")",":","return","render_node","(","Visit",".","objects",".","count_unique_for_object","(","obj",")",",","obj",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/hitcounter\/templatetags\/counters.py#L28-L32"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/tasks.py","language":"python","identifier":"update_marker_cluster_cache","parameters":"()","argument_list":"","return_statement":"","docstring":"Updates all cached map clusters related to locations.","docstring_summary":"Updates all cached map clusters related to locations.","docstring_tokens":["Updates","all","cached","map","clusters","related","to","locations","."],"function":"def update_marker_cluster_cache():\n \"\"\" Updates all cached map clusters related to locations. \"\"\"\n create_country_clusters()\n for location in Location.objects.filter(kind__in=['PPLA', 'PPLC',]):\n make_region_cluster(location)","function_tokens":["def","update_marker_cluster_cache","(",")",":","create_country_clusters","(",")","for","location","in","Location",".","objects",".","filter","(","kind__in","=","[","'PPLA'",",","'PPLC'",",","]",")",":","make_region_cluster","(","location",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/tasks.py#L15-L19"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/tasks.py","language":"python","identifier":"clear_empty_markers","parameters":"()","argument_list":"","return_statement":"","docstring":"There is a chance that deleted objects will stay on map.","docstring_summary":"There is a chance that deleted objects will stay on map.","docstring_tokens":["There","is","a","chance","that","deleted","objects","will","stay","on","map","."],"function":"def clear_empty_markers():\n \"\"\" There is a chance that deleted objects will stay on map. \"\"\"\n for marker in MapPointer.objects.all():\n if marker.content_object is None:\n marker.delete()","function_tokens":["def","clear_empty_markers","(",")",":","for","marker","in","MapPointer",".","objects",".","all","(",")",":","if","marker",".","content_object","is","None",":","marker",".","delete","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/tasks.py#L23-L27"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/signals.py","language":"python","identifier":"create_marker","parameters":"(sender, instance, created, **kwargs)","argument_list":"","return_statement":"return mp","docstring":"Create marker for new created object. Mark it's location approprietly\n if it is location or object related to location. It needs models with\n latitude and longitude fields to work, so it's mostly useful for\n locations.","docstring_summary":"Create marker for new created object. Mark it's location approprietly\n if it is location or object related to location. It needs models with\n latitude and longitude fields to work, so it's mostly useful for\n locations.","docstring_tokens":["Create","marker","for","new","created","object",".","Mark","it","s","location","approprietly","if","it","is","location","or","object","related","to","location",".","It","needs","models","with","latitude","and","longitude","fields","to","work","so","it","s","mostly","useful","for","locations","."],"function":"def create_marker(sender, instance, created, **kwargs):\n \"\"\" Create marker for new created object. Mark it's location approprietly\n if it is location or object related to location. It needs models with\n latitude and longitude fields to work, so it's mostly useful for\n locations.\n \"\"\"\n if not hasattr(instance, 'latitude') or not hasattr(instance, 'longitude'):\n return False\n\n lat = instance.latitude\n lng = instance.longitude\n\n if not lat or not lng:\n return\n\n # Try to remove obsolete markers if lat or lng has changed\n for m in MapPointer.objects.for_model(instance):\n m.delete()\n\n try:\n mp = MapPointer.objects.create_for_object(instance, lat, lng)\n except IntegrityError:\n mp = MapPointer.objects.for_model(instance).first()\n\n return mp","function_tokens":["def","create_marker","(","sender",",","instance",",","created",",","*","*","kwargs",")",":","if","not","hasattr","(","instance",",","'latitude'",")","or","not","hasattr","(","instance",",","'longitude'",")",":","return","False","lat","=","instance",".","latitude","lng","=","instance",".","longitude","if","not","lat","or","not","lng",":","return","# Try to remove obsolete markers if lat or lng has changed","for","m","in","MapPointer",".","objects",".","for_model","(","instance",")",":","m",".","delete","(",")","try",":","mp","=","MapPointer",".","objects",".","create_for_object","(","instance",",","lat",",","lng",")","except","IntegrityError",":","mp","=","MapPointer",".","objects",".","for_model","(","instance",")",".","first","(",")","return","mp"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/signals.py#L7-L31"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/managers.py","language":"python","identifier":"MapPointerManager.for_model","parameters":"(self, model)","argument_list":"","return_statement":"return qs","docstring":"QuerySet for all pointers for a particular model.","docstring_summary":"QuerySet for all pointers for a particular model.","docstring_tokens":["QuerySet","for","all","pointers","for","a","particular","model","."],"function":"def for_model(self, model):\n \"\"\" QuerySet for all pointers for a particular model.\n \"\"\"\n ct = ContentType.objects.get_for_model(model)\n qs = self.get_queryset().filter(content_type=ct)\n if isinstance(model, models.Model):\n qs = qs.filter(object_pk=force_text(model._get_pk_val()))\n return qs","function_tokens":["def","for_model","(","self",",","model",")",":","ct","=","ContentType",".","objects",".","get_for_model","(","model",")","qs","=","self",".","get_queryset","(",")",".","filter","(","content_type","=","ct",")","if","isinstance","(","model",",","models",".","Model",")",":","qs","=","qs",".","filter","(","object_pk","=","force_text","(","model",".","_get_pk_val","(",")",")",")","return","qs"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/managers.py#L10-L17"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/managers.py","language":"python","identifier":"MapPointerManager.for_location","parameters":"(self, location)","argument_list":"","return_statement":"return self.get_queryset().filter(location=location)","docstring":"QuerySet for all pointers for particular location.","docstring_summary":"QuerySet for all pointers for particular location.","docstring_tokens":["QuerySet","for","all","pointers","for","particular","location","."],"function":"def for_location(self, location):\n \"\"\" QuerySet for all pointers for particular location.\n \"\"\"\n return self.get_queryset().filter(location=location)","function_tokens":["def","for_location","(","self",",","location",")",":","return","self",".","get_queryset","(",")",".","filter","(","location","=","location",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/managers.py#L19-L22"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/managers.py","language":"python","identifier":"MapPointerManager.create_for_object","parameters":"(self, obj, lat, lng, **kwargs)","argument_list":"","return_statement":"return pointer","docstring":"Creates new map pointer for given object on passed latitude and longitude.","docstring_summary":"Creates new map pointer for given object on passed latitude and longitude.","docstring_tokens":["Creates","new","map","pointer","for","given","object","on","passed","latitude","and","longitude","."],"function":"def create_for_object(self, obj, lat, lng, **kwargs):\n \"\"\" Creates new map pointer for given object on passed latitude and longitude.\n \"\"\"\n pointer = self.model(latitude=lat, longitude=lng, object_pk=obj.pk,\n content_type=ContentType.objects.get_for_model(obj))\n if obj._meta.model_name == 'location':\n pointer.location = obj\n elif hasattr(obj, 'location'):\n pointer.location = obj.location\n pointer.save()\n return pointer","function_tokens":["def","create_for_object","(","self",",","obj",",","lat",",","lng",",","*","*","kwargs",")",":","pointer","=","self",".","model","(","latitude","=","lat",",","longitude","=","lng",",","object_pk","=","obj",".","pk",",","content_type","=","ContentType",".","objects",".","get_for_model","(","obj",")",")","if","obj",".","_meta",".","model_name","==","'location'",":","pointer",".","location","=","obj","elif","hasattr","(","obj",",","'location'",")",":","pointer",".","location","=","obj",".","location","pointer",".","save","(",")","return","pointer"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/managers.py#L24-L34"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/helpers.py","language":"python","identifier":"filter_markers","parameters":"(lat, lng, factor=1.0, filters=None, location_pk=None)","argument_list":"","return_statement":"return qs.filter(\n latitude__gt=float(lat) - float(factor),\n latitude__lt=float(lat) + float(factor),\n longitude__gt=float(lng) - float(factor),\n longitude__lt=float(lng) + float(factor),\n content_type__in=[int(x) for x in filters.split(',') if x]\n )","docstring":"Simple marker list filter. It takes latitude and longitude as arguments and\n fetch pointers in distance of `factor` degrees from this point.\n \n Filters is array of content type id's to fetch. If None is set, nothing will be returned.\n \n If you pass location pk only markers related to this location will be fetched.","docstring_summary":"Simple marker list filter. It takes latitude and longitude as arguments and\n fetch pointers in distance of `factor` degrees from this point.\n \n Filters is array of content type id's to fetch. If None is set, nothing will be returned.\n \n If you pass location pk only markers related to this location will be fetched.","docstring_tokens":["Simple","marker","list","filter",".","It","takes","latitude","and","longitude","as","arguments","and","fetch","pointers","in","distance","of","factor","degrees","from","this","point",".","Filters","is","array","of","content","type","id","s","to","fetch",".","If","None","is","set","nothing","will","be","returned",".","If","you","pass","location","pk","only","markers","related","to","this","location","will","be","fetched","."],"function":"def filter_markers(lat, lng, factor=1.0, filters=None, location_pk=None):\n \"\"\" \n Simple marker list filter. It takes latitude and longitude as arguments and\n fetch pointers in distance of `factor` degrees from this point.\n \n Filters is array of content type id's to fetch. If None is set, nothing will be returned.\n \n If you pass location pk only markers related to this location will be fetched.\n \"\"\"\n if filters is None:\n return []\n\n # if location_pk is not None:\n # qs = MapPointer.objects.for_location(\n # get_object_or_404(Location, pk=location_pk))\n # else:\n # qs = MapPointer.objects.all()\n qs = MapPointer.objects.all()\n\n return qs.filter(\n latitude__gt=float(lat) - float(factor),\n latitude__lt=float(lat) + float(factor),\n longitude__gt=float(lng) - float(factor),\n longitude__lt=float(lng) + float(factor),\n content_type__in=[int(x) for x in filters.split(',') if x]\n )","function_tokens":["def","filter_markers","(","lat",",","lng",",","factor","=","1.0",",","filters","=","None",",","location_pk","=","None",")",":","if","filters","is","None",":","return","[","]","# if location_pk is not None:","# qs = MapPointer.objects.for_location(","# get_object_or_404(Location, pk=location_pk))","# else:","# qs = MapPointer.objects.all()","qs","=","MapPointer",".","objects",".","all","(",")","return","qs",".","filter","(","latitude__gt","=","float","(","lat",")","-","float","(","factor",")",",","latitude__lt","=","float","(","lat",")","+","float","(","factor",")",",","longitude__gt","=","float","(","lng",")","-","float","(","factor",")",",","longitude__lt","=","float","(","lng",")","+","float","(","factor",")",",","content_type__in","=","[","int","(","x",")","for","x","in","filters",".","split","(","','",")","if","x","]",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/helpers.py#L16-L41"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/helpers.py","language":"python","identifier":"make_region_cluster","parameters":"(city)","argument_list":"","return_statement":"return count","docstring":"This function takes region main location as argument and creates cache.","docstring_summary":"This function takes region main location as argument and creates cache.","docstring_tokens":["This","function","takes","region","main","location","as","argument","and","creates","cache","."],"function":"def make_region_cluster(city):\n \"\"\" This function takes region main location as argument and creates cache. \"\"\"\n count = MapPointer.objects.filter(\n location__in=city.parent.get_children_id_list()).count()\n redis_cache.set(str(city.pk) + '_childlist', count, timeout=None)\n logger.info(\"Created cluster for region {} with {} items\".format(city.pk, count))\n return count","function_tokens":["def","make_region_cluster","(","city",")",":","count","=","MapPointer",".","objects",".","filter","(","location__in","=","city",".","parent",".","get_children_id_list","(",")",")",".","count","(",")","redis_cache",".","set","(","str","(","city",".","pk",")","+","'_childlist'",",","count",",","timeout","=","None",")","logger",".","info","(","\"Created cluster for region {} with {} items\"",".","format","(","city",".","pk",",","count",")",")","return","count"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/helpers.py#L44-L50"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/helpers.py","language":"python","identifier":"create_region_clusters","parameters":"(lat, lng, zoom)","argument_list":"","return_statement":"return clusters","docstring":"Create clusters for regions - usable in medium zoom. Function takes latitude\n and longitude of current map center as strings or numbers.","docstring_summary":"Create clusters for regions - usable in medium zoom. Function takes latitude\n and longitude of current map center as strings or numbers.","docstring_tokens":["Create","clusters","for","regions","-","usable","in","medium","zoom",".","Function","takes","latitude","and","longitude","of","current","map","center","as","strings","or","numbers","."],"function":"def create_region_clusters(lat, lng, zoom):\n \"\"\"\n Create clusters for regions - usable in medium zoom. Function takes latitude\n and longitude of current map center as strings or numbers.\n \"\"\"\n clusters = []\n\n if int(zoom) == 6:\n factor = 40.0\n elif int(zoom) > 6 and int(zoom) < 9:\n factor = 20.0\n else:\n factor = 10.0\n\n max_lat = float(lat) + factor\n max_lng = float(lng) + factor\n min_lat = float(lat) - factor\n min_lng = float(lng) - factor\n\n main_locations = Location.objects.filter(\n kind__in=['PPLA','PPLC'],\n latitude__gt=min_lat,\n latitude__lt=max_lat,\n longitude__gt=min_lng,\n longitude__lt=max_lng)\n\n for l in main_locations:\n # we can use this value directly - update signal takes care of cache.\n count = redis_cache.get(str(l.pk) + '_childlist')\n if count is None:\n count = make_region_cluster(l)\n cluster = {\n 'lat': l.latitude,\n 'lng': l.longitude,\n 'counter': count,\n }\n clusters.append(cluster)\n return clusters","function_tokens":["def","create_region_clusters","(","lat",",","lng",",","zoom",")",":","clusters","=","[","]","if","int","(","zoom",")","==","6",":","factor","=","40.0","elif","int","(","zoom",")",">","6","and","int","(","zoom",")","<","9",":","factor","=","20.0","else",":","factor","=","10.0","max_lat","=","float","(","lat",")","+","factor","max_lng","=","float","(","lng",")","+","factor","min_lat","=","float","(","lat",")","-","factor","min_lng","=","float","(","lng",")","-","factor","main_locations","=","Location",".","objects",".","filter","(","kind__in","=","[","'PPLA'",",","'PPLC'","]",",","latitude__gt","=","min_lat",",","latitude__lt","=","max_lat",",","longitude__gt","=","min_lng",",","longitude__lt","=","max_lng",")","for","l","in","main_locations",":","# we can use this value directly - update signal takes care of cache.","count","=","redis_cache",".","get","(","str","(","l",".","pk",")","+","'_childlist'",")","if","count","is","None",":","count","=","make_region_cluster","(","l",")","cluster","=","{","'lat'",":","l",".","latitude",",","'lng'",":","l",".","longitude",",","'counter'",":","count",",","}","clusters",".","append","(","cluster",")","return","clusters"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/helpers.py#L53-L90"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/helpers.py","language":"python","identifier":"create_country_clusters","parameters":"()","argument_list":"","return_statement":"return clusters","docstring":"Create clusters for all countries - for very low zoom level.","docstring_summary":"Create clusters for all countries - for very low zoom level.","docstring_tokens":["Create","clusters","for","all","countries","-","for","very","low","zoom","level","."],"function":"def create_country_clusters():\n \"\"\" Create clusters for all countries - for very low zoom level. \"\"\"\n clusters = []\n main_locations = Country.objects.all()\n for c in main_locations:\n try:\n l = Location.objects.get(country_code=c.code, kind='PPLC')\n cluster = {\n 'lat': l.latitude,\n 'lng': l.longitude,\n 'counter': MapPointer.objects.filter(\n location__in=c.location.get_children_id_list()).count(),\n }\n clusters.append(cluster)\n except Location.DoesNotExist:\n logger.info(u\"Cannot find capital location for %s\" % c.code)\n redis_cache.set('allcountries', clusters, timeout=None)\n return clusters","function_tokens":["def","create_country_clusters","(",")",":","clusters","=","[","]","main_locations","=","Country",".","objects",".","all","(",")","for","c","in","main_locations",":","try",":","l","=","Location",".","objects",".","get","(","country_code","=","c",".","code",",","kind","=","'PPLC'",")","cluster","=","{","'lat'",":","l",".","latitude",",","'lng'",":","l",".","longitude",",","'counter'",":","MapPointer",".","objects",".","filter","(","location__in","=","c",".","location",".","get_children_id_list","(",")",")",".","count","(",")",",","}","clusters",".","append","(","cluster",")","except","Location",".","DoesNotExist",":","logger",".","info","(","u\"Cannot find capital location for %s\"","%","c",".","code",")","redis_cache",".","set","(","'allcountries'",",","clusters",",","timeout","=","None",")","return","clusters"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/helpers.py#L93-L110"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/helpers.py","language":"python","identifier":"create_clusters","parameters":"(lat, lng, zoom)","argument_list":"","return_statement":"","docstring":"Crate clusters for map when zoom is less then 10. As above, this function\n takes latitude, longitude and map zoom level as argments and returns array\n of marker positions along with number of items in requested region.","docstring_summary":"Crate clusters for map when zoom is less then 10. As above, this function\n takes latitude, longitude and map zoom level as argments and returns array\n of marker positions along with number of items in requested region.","docstring_tokens":["Crate","clusters","for","map","when","zoom","is","less","then","10",".","As","above","this","function","takes","latitude","longitude","and","map","zoom","level","as","argments","and","returns","array","of","marker","positions","along","with","number","of","items","in","requested","region","."],"function":"def create_clusters(lat, lng, zoom):\n \"\"\"\n Crate clusters for map when zoom is less then 10. As above, this function\n takes latitude, longitude and map zoom level as argments and returns array\n of marker positions along with number of items in requested region.\n \"\"\"\n zoom = int(zoom)\n if zoom >= 6:\n return create_region_clusters(lat, lng, zoom)\n else:\n results = redis_cache.get(\"allcountries\")\n if not results:\n results = create_country_clusters()\n redis_cache.set(\"allcountries\", results, timeout=None)\n return results","function_tokens":["def","create_clusters","(","lat",",","lng",",","zoom",")",":","zoom","=","int","(","zoom",")","if","zoom",">=","6",":","return","create_region_clusters","(","lat",",","lng",",","zoom",")","else",":","results","=","redis_cache",".","get","(","\"allcountries\"",")","if","not","results",":","results","=","create_country_clusters","(",")","redis_cache",".","set","(","\"allcountries\"",",","results",",","timeout","=","None",")","return","results"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/helpers.py#L113-L127"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/storage.py","language":"python","identifier":"round_to","parameters":"(n, precision)","argument_list":"","return_statement":"return int( n\/precision+correction ) * precision","docstring":"Round floating point number to selected precision.","docstring_summary":"Round floating point number to selected precision.","docstring_tokens":["Round","floating","point","number","to","selected","precision","."],"function":"def round_to(n, precision):\n \"\"\" Round floating point number to selected precision.\n \"\"\"\n correction = 0.5 if n >= 0 else -0.5\n return int( n\/precision+correction ) * precision","function_tokens":["def","round_to","(","n",",","precision",")",":","correction","=","0.5","if","n",">=","0","else","-","0.5","return","int","(","n","\/","precision","+","correction",")","*","precision"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/storage.py#L14-L18"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/storage.py","language":"python","identifier":"round_to_05","parameters":"(n)","argument_list":"","return_statement":"return round_to(n, 0.5)","docstring":"Round float to nearest 0.5.","docstring_summary":"Round float to nearest 0.5.","docstring_tokens":["Round","float","to","nearest","0",".","5","."],"function":"def round_to_05(n):\n \"\"\" Round float to nearest 0.5.\n \"\"\"\n return round_to(n, 0.5)","function_tokens":["def","round_to_05","(","n",")",":","return","round_to","(","n",",","0.5",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/storage.py#L21-L24"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/storage.py","language":"python","identifier":"get_boundaries","parameters":"(ne, sw)","argument_list":"","return_statement":"return {\n 'ne': tuple(float(x) for x in ne.split('x')),\n 'sw': tuple(float(x) for x in sw.split('x')), }","docstring":"A little helper to decipher GET params into tuples.","docstring_summary":"A little helper to decipher GET params into tuples.","docstring_tokens":["A","little","helper","to","decipher","GET","params","into","tuples","."],"function":"def get_boundaries(ne, sw):\n \"\"\" A little helper to decipher GET params into tuples.\n \"\"\"\n return {\n 'ne': tuple(float(x) for x in ne.split('x')),\n 'sw': tuple(float(x) for x in sw.split('x')), }","function_tokens":["def","get_boundaries","(","ne",",","sw",")",":","return","{","'ne'",":","tuple","(","float","(","x",")","for","x","in","ne",".","split","(","'x'",")",")",",","'sw'",":","tuple","(","float","(","x",")","for","x","in","sw",".","split","(","'x'",")",")",",","}"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/storage.py#L27-L32"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/storage.py","language":"python","identifier":"filter_markers","parameters":"(south_west, north_east)","argument_list":"","return_statement":"return qs","docstring":"Filter markers for selected viewport.","docstring_summary":"Filter markers for selected viewport.","docstring_tokens":["Filter","markers","for","selected","viewport","."],"function":"def filter_markers(south_west, north_east):\n \"\"\" Filter markers for selected viewport.\n \"\"\"\n boundaries = get_boundaries(south_west, north_east)\n min_lat, min_lng = boundaries['ne']\n max_lat, max_lng = boundaries['sw']\n diff = max([max_lat - min_lat, max_lng - min_lng, ]) \/ 4\n qs = MapPointer.objects.filter(latitude__gte=min_lat - diff,\n latitude__lte=max_lat + diff,\n longitude__gte=min_lng - diff,\n longitude__lte=max_lng + diff)\n return qs","function_tokens":["def","filter_markers","(","south_west",",","north_east",")",":","boundaries","=","get_boundaries","(","south_west",",","north_east",")","min_lat",",","min_lng","=","boundaries","[","'ne'","]","max_lat",",","max_lng","=","boundaries","[","'sw'","]","diff","=","max","(","[","max_lat","-","min_lat",",","max_lng","-","min_lng",",","]",")","\/","4","qs","=","MapPointer",".","objects",".","filter","(","latitude__gte","=","min_lat","-","diff",",","latitude__lte","=","max_lat","+","diff",",","longitude__gte","=","min_lng","-","diff",",","longitude__lte","=","max_lng","+","diff",")","return","qs"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/storage.py#L35-L46"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/storage.py","language":"python","identifier":"find_region_cities","parameters":"(south_west, north_east)","argument_list":"","return_statement":"return Location.objects.filter(\n kind__in=kinds,\n latitude__gte=min_lat - diff,\n latitude__lte=max_lat + diff,\n longitude__gte=min_lng - diff,\n longitude__lte=max_lng + diff)","docstring":"Find main region and country cities for given lat\/lng boudaries.","docstring_summary":"Find main region and country cities for given lat\/lng boudaries.","docstring_tokens":["Find","main","region","and","country","cities","for","given","lat","\/","lng","boudaries","."],"function":"def find_region_cities(south_west, north_east):\n \"\"\" Find main region and country cities for given lat\/lng boudaries.\n \"\"\"\n kinds = ['PPLC', 'PPLA', ]\n boundaries = get_boundaries(south_west, north_east)\n min_lat, min_lng = boundaries['ne']\n max_lat, max_lng = boundaries['sw']\n diff = max([max_lat - min_lat, max_lng - min_lng, ]) \/ 4\n return Location.objects.filter(\n kind__in=kinds,\n latitude__gte=min_lat - diff,\n latitude__lte=max_lat + diff,\n longitude__gte=min_lng - diff,\n longitude__lte=max_lng + diff)","function_tokens":["def","find_region_cities","(","south_west",",","north_east",")",":","kinds","=","[","'PPLC'",",","'PPLA'",",","]","boundaries","=","get_boundaries","(","south_west",",","north_east",")","min_lat",",","min_lng","=","boundaries","[","'ne'","]","max_lat",",","max_lng","=","boundaries","[","'sw'","]","diff","=","max","(","[","max_lat","-","min_lat",",","max_lng","-","min_lng",",","]",")","\/","4","return","Location",".","objects",".","filter","(","kind__in","=","kinds",",","latitude__gte","=","min_lat","-","diff",",","latitude__lte","=","max_lat","+","diff",",","longitude__gte","=","min_lng","-","diff",",","longitude__lte","=","max_lng","+","diff",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/storage.py#L49-L62"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/storage.py","language":"python","identifier":"create_cluster","parameters":"(main_city)","argument_list":"","return_statement":"return {\n 'id': main_city.pk,\n 'lat': main_city.latitude,\n 'lng': main_city.longitude,\n 'count': len(MapPointer.objects.filter(location__pk__in=id_list)),\n }","docstring":"Creates cluster for given main city (either capital or region capital).","docstring_summary":"Creates cluster for given main city (either capital or region capital).","docstring_tokens":["Creates","cluster","for","given","main","city","(","either","capital","or","region","capital",")","."],"function":"def create_cluster(main_city):\n \"\"\" Creates cluster for given main city (either capital or region capital).\n \"\"\"\n id_list = main_city.parent.get_children_id_list()\n return {\n 'id': main_city.pk,\n 'lat': main_city.latitude,\n 'lng': main_city.longitude,\n 'count': len(MapPointer.objects.filter(location__pk__in=id_list)),\n }","function_tokens":["def","create_cluster","(","main_city",")",":","id_list","=","main_city",".","parent",".","get_children_id_list","(",")","return","{","'id'",":","main_city",".","pk",",","'lat'",":","main_city",".","latitude",",","'lng'",":","main_city",".","longitude",",","'count'",":","len","(","MapPointer",".","objects",".","filter","(","location__pk__in","=","id_list",")",")",",","}"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/storage.py#L65-L74"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/storage.py","language":"python","identifier":"update_region_cluster","parameters":"(main_city)","argument_list":"","return_statement":"return cluster","docstring":"Updates or creates cache entry for selected city cluster.","docstring_summary":"Updates or creates cache entry for selected city cluster.","docstring_tokens":["Updates","or","creates","cache","entry","for","selected","city","cluster","."],"function":"def update_region_cluster(main_city):\n \"\"\" Updates or creates cache entry for selected city cluster.\n \"\"\"\n cluster = create_cluster(main_city)\n cache.set(\"clusters_{}\".format(main_city.pk), cluster, timeout=None)\n return cluster","function_tokens":["def","update_region_cluster","(","main_city",")",":","cluster","=","create_cluster","(","main_city",")","cache",".","set","(","\"clusters_{}\"",".","format","(","main_city",".","pk",")",",","cluster",",","timeout","=","None",")","return","cluster"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/storage.py#L77-L82"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/storage.py","language":"python","identifier":"create_region_clusters","parameters":"()","argument_list":"","return_statement":"return clusters","docstring":"Creates entire set of clusters for all countries in database. Use this\n carefully as this may take A LONG time.","docstring_summary":"Creates entire set of clusters for all countries in database. Use this\n carefully as this may take A LONG time.","docstring_tokens":["Creates","entire","set","of","clusters","for","all","countries","in","database",".","Use","this","carefully","as","this","may","take","A","LONG","time","."],"function":"def create_region_clusters():\n \"\"\" Creates entire set of clusters for all countries in database. Use this\n carefully as this may take A LONG time.\n \"\"\"\n main_cities = Location.objects.filter(kind__in=['PPLA', 'PPLC', ])\n clusters = []\n for city in main_cities:\n clusters.append(update_region_cluster(city))\n return clusters","function_tokens":["def","create_region_clusters","(",")",":","main_cities","=","Location",".","objects",".","filter","(","kind__in","=","[","'PPLA'",",","'PPLC'",",","]",")","clusters","=","[","]","for","city","in","main_cities",":","clusters",".","append","(","update_region_cluster","(","city",")",")","return","clusters"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/storage.py#L85-L93"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/storage.py","language":"python","identifier":"get_clusters","parameters":"(south_west, north_east)","argument_list":"","return_statement":"return clusters","docstring":"Try to serve cached content first, and fallback to creating new clusters.\n This is not recommended - it is VERY heavy database operation.","docstring_summary":"Try to serve cached content first, and fallback to creating new clusters.\n This is not recommended - it is VERY heavy database operation.","docstring_tokens":["Try","to","serve","cached","content","first","and","fallback","to","creating","new","clusters",".","This","is","not","recommended","-","it","is","VERY","heavy","database","operation","."],"function":"def get_clusters(south_west, north_east):\n \"\"\" Try to serve cached content first, and fallback to creating new clusters.\n This is not recommended - it is VERY heavy database operation.\n \"\"\"\n main_cities = find_region_cities(south_west, north_east)\n clusters = []\n for city in main_cities:\n cluster = cache.get('clusters_{}'.format(city.pk))\n if cluster is None:\n cluster = update_region_cluster(city)\n clusters.append(cluster)\n return clusters","function_tokens":["def","get_clusters","(","south_west",",","north_east",")",":","main_cities","=","find_region_cities","(","south_west",",","north_east",")","clusters","=","[","]","for","city","in","main_cities",":","cluster","=","cache",".","get","(","'clusters_{}'",".","format","(","city",".","pk",")",")","if","cluster","is","None",":","cluster","=","update_region_cluster","(","city",")","clusters",".","append","(","cluster",")","return","clusters"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/storage.py#L96-L107"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"maps\/templatetags\/map_tags.py","language":"python","identifier":"get_map_pointers","parameters":"(obj)","argument_list":"","return_statement":"return MapPointer.objects.for_model(obj)","docstring":"Returns a list of map points connected with the object.","docstring_summary":"Returns a list of map points connected with the object.","docstring_tokens":["Returns","a","list","of","map","points","connected","with","the","object","."],"function":"def get_map_pointers(obj):\n \"\"\" Returns a list of map points connected with the object. \"\"\"\n return MapPointer.objects.for_model(obj)","function_tokens":["def","get_map_pointers","(","obj",")",":","return","MapPointer",".","objects",".","for_model","(","obj",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/maps\/templatetags\/map_tags.py#L10-L12"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/views.py","language":"python","identifier":"_get_referer","parameters":"(request)","argument_list":"","return_statement":"","docstring":"Return the HTTP_REFERER, if existing.","docstring_summary":"Return the HTTP_REFERER, if existing.","docstring_tokens":["Return","the","HTTP_REFERER","if","existing","."],"function":"def _get_referer(request):\n \"\"\"Return the HTTP_REFERER, if existing.\"\"\"\n if 'HTTP_REFERER' in request.META:\n sr = urlsplit(request.META['HTTP_REFERER'])\n return urlunsplit(('', '', sr.path, sr.query, sr.fragment))","function_tokens":["def","_get_referer","(","request",")",":","if","'HTTP_REFERER'","in","request",".","META",":","sr","=","urlsplit","(","request",".","META","[","'HTTP_REFERER'","]",")","return","urlunsplit","(","(","''",",","''",",","sr",".","path",",","sr",".","query",",","sr",".","fragment",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/views.py#L45-L49"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/fields.py","language":"python","identifier":"BasicCommaSeparatedUserField.set_max","parameters":"(self, max)","argument_list":"","return_statement":"","docstring":"Supersede the max value and ajust accordingly the label.","docstring_summary":"Supersede the max value and ajust accordingly the label.","docstring_tokens":["Supersede","the","max","value","and","ajust","accordingly","the","label","."],"function":"def set_max(self, max):\n \"\"\"Supersede the max value and ajust accordingly the label.\"\"\"\n pluralized_labels = getattr(self, 'pluralized_labels', None)\n if pluralized_labels:\n self.label = pluralized_labels[max == 1]\n self.max = max","function_tokens":["def","set_max","(","self",",","max",")",":","pluralized_labels","=","getattr","(","self",",","'pluralized_labels'",",","None",")","if","pluralized_labels",":","self",".","label","=","pluralized_labels","[","max","==","1","]","self",".","max","=","max"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/fields.py#L43-L48"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/fields.py","language":"python","identifier":"BasicCommaSeparatedUserField.to_python","parameters":"(self, value)","argument_list":"","return_statement":"return list(set([name.strip() for name in value.split(',') if name and not name.isspace()]))","docstring":"Normalize data to an unordered list of distinct, non empty, whitespace-stripped strings.","docstring_summary":"Normalize data to an unordered list of distinct, non empty, whitespace-stripped strings.","docstring_tokens":["Normalize","data","to","an","unordered","list","of","distinct","non","empty","whitespace","-","stripped","strings","."],"function":"def to_python(self, value):\n \"\"\"Normalize data to an unordered list of distinct, non empty, whitespace-stripped strings.\"\"\"\n value = super(BasicCommaSeparatedUserField, self).to_python(value)\n if value in EMPTY_VALUES: # Return an empty list if no useful input was given.\n return []\n return list(set([name.strip() for name in value.split(',') if name and not name.isspace()]))","function_tokens":["def","to_python","(","self",",","value",")",":","value","=","super","(","BasicCommaSeparatedUserField",",","self",")",".","to_python","(","value",")","if","value","in","EMPTY_VALUES",":","# Return an empty list if no useful input was given.","return","[","]","return","list","(","set","(","[","name",".","strip","(",")","for","name","in","value",".","split","(","','",")","if","name","and","not","name",".","isspace","(",")","]",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/fields.py#L50-L55"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/fields.py","language":"python","identifier":"BasicCommaSeparatedUserField.validate","parameters":"(self, value)","argument_list":"","return_statement":"","docstring":"Check the limits.","docstring_summary":"Check the limits.","docstring_tokens":["Check","the","limits","."],"function":"def validate(self, value):\n \"\"\"Check the limits.\"\"\"\n super(BasicCommaSeparatedUserField, self).validate(value)\n if value in EMPTY_VALUES:\n return\n count = len(value)\n if self.max and count > self.max:\n raise ValidationError(self.error_messages['max'].format(limit_value=self.max, show_value=count))\n if self.min and count < self.min:\n raise ValidationError(self.error_messages['min'].format(limit_value=self.min, show_value=count))","function_tokens":["def","validate","(","self",",","value",")",":","super","(","BasicCommaSeparatedUserField",",","self",")",".","validate","(","value",")","if","value","in","EMPTY_VALUES",":","return","count","=","len","(","value",")","if","self",".","max","and","count",">","self",".","max",":","raise","ValidationError","(","self",".","error_messages","[","'max'","]",".","format","(","limit_value","=","self",".","max",",","show_value","=","count",")",")","if","self",".","min","and","count","<","self",".","min",":","raise","ValidationError","(","self",".","error_messages","[","'min'","]",".","format","(","limit_value","=","self",".","min",",","show_value","=","count",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/fields.py#L57-L66"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/fields.py","language":"python","identifier":"BasicCommaSeparatedUserField.clean","parameters":"(self, value)","argument_list":"","return_statement":"return users","docstring":"Check names are valid and filter them.","docstring_summary":"Check names are valid and filter them.","docstring_tokens":["Check","names","are","valid","and","filter","them","."],"function":"def clean(self, value):\n \"\"\"Check names are valid and filter them.\"\"\"\n names = super(BasicCommaSeparatedUserField, self).clean(value)\n if not names:\n return []\n user_model = get_user_model()\n users = list(user_model.objects.filter(is_active=True, **{'{0}__in'.format(user_model.USERNAME_FIELD): names}))\n unknown_names = set(names) ^ set([u.get_username() for u in users])\n errors = []\n if unknown_names:\n errors.append(self.error_messages['unknown'].format(users=', '.join(unknown_names)))\n if self.user_filter:\n filtered_names = []\n for u in users[:]:\n try:\n reason = self.user_filter(u)\n if reason is not None:\n users.remove(u)\n filtered_names.append(\n self.error_messages[\n 'filtered_user_with_reason' if reason else 'filtered_user'\n ].format(username=u.get_username(), reason=reason)\n )\n except ValidationError as e:\n users.remove(u)\n errors.extend(e.messages)\n if filtered_names:\n errors.append(self.error_messages['filtered'].format(users=', '.join(filtered_names)))\n if errors:\n raise ValidationError(errors)\n return users","function_tokens":["def","clean","(","self",",","value",")",":","names","=","super","(","BasicCommaSeparatedUserField",",","self",")",".","clean","(","value",")","if","not","names",":","return","[","]","user_model","=","get_user_model","(",")","users","=","list","(","user_model",".","objects",".","filter","(","is_active","=","True",",","*","*","{","'{0}__in'",".","format","(","user_model",".","USERNAME_FIELD",")",":","names","}",")",")","unknown_names","=","set","(","names",")","^","set","(","[","u",".","get_username","(",")","for","u","in","users","]",")","errors","=","[","]","if","unknown_names",":","errors",".","append","(","self",".","error_messages","[","'unknown'","]",".","format","(","users","=","', '",".","join","(","unknown_names",")",")",")","if","self",".","user_filter",":","filtered_names","=","[","]","for","u","in","users","[",":","]",":","try",":","reason","=","self",".","user_filter","(","u",")","if","reason","is","not","None",":","users",".","remove","(","u",")","filtered_names",".","append","(","self",".","error_messages","[","'filtered_user_with_reason'","if","reason","else","'filtered_user'","]",".","format","(","username","=","u",".","get_username","(",")",",","reason","=","reason",")",")","except","ValidationError","as","e",":","users",".","remove","(","u",")","errors",".","extend","(","e",".","messages",")","if","filtered_names",":","errors",".","append","(","self",".","error_messages","[","'filtered'","]",".","format","(","users","=","', '",".","join","(","filtered_names",")",")",")","if","errors",":","raise","ValidationError","(","errors",")","return","users"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/fields.py#L68-L98"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/query.py","language":"python","identifier":"CompilerProxy.union","parameters":"(self, querysets)","argument_list":"","return_statement":"return ' UNION '.join(result_sql), tuple(result_params)","docstring":"Join several querysets by a UNION clause. Returns the SQL string and the list of parameters.","docstring_summary":"Join several querysets by a UNION clause. Returns the SQL string and the list of parameters.","docstring_tokens":["Join","several","querysets","by","a","UNION","clause",".","Returns","the","SQL","string","and","the","list","of","parameters","."],"function":"def union(self, querysets):\n \"\"\"\n Join several querysets by a UNION clause. Returns the SQL string and the list of parameters.\n \"\"\"\n result_sql, result_params = [], []\n for qs in querysets:\n sql, params = qs.query.sql_with_params()\n result_sql.append(sql)\n result_params.extend(params)\n return ' UNION '.join(result_sql), tuple(result_params)","function_tokens":["def","union","(","self",",","querysets",")",":","result_sql",",","result_params","=","[","]",",","[","]","for","qs","in","querysets",":","sql",",","params","=","qs",".","query",".","sql_with_params","(",")","result_sql",".","append","(","sql",")","result_params",".","extend","(","params",")","return","' UNION '",".","join","(","result_sql",")",",","tuple","(","result_params",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/query.py#L79-L88"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/utils.py","language":"python","identifier":"format_body","parameters":"(sender, body, indent=_(\"> \"), width=WRAP_WIDTH)","argument_list":"","return_statement":"return ugettext(\"\\n\\n{sender} wrote:\\n{body}\\n\").format(sender=sender, body=quote)","docstring":"Wrap the text and prepend lines with a prefix.\n\n The aim is to get lines with at most `width` chars.\n But does not wrap if the line is already prefixed.\n\n Prepends each line with a localized prefix, even empty lines.\n Existing line breaks are preserved.\n Used for quoting messages in replies.","docstring_summary":"Wrap the text and prepend lines with a prefix.","docstring_tokens":["Wrap","the","text","and","prepend","lines","with","a","prefix","."],"function":"def format_body(sender, body, indent=_(\"> \"), width=WRAP_WIDTH):\n \"\"\"\n Wrap the text and prepend lines with a prefix.\n\n The aim is to get lines with at most `width` chars.\n But does not wrap if the line is already prefixed.\n\n Prepends each line with a localized prefix, even empty lines.\n Existing line breaks are preserved.\n Used for quoting messages in replies.\n\n \"\"\"\n indent = force_text(indent) # join() doesn't work on lists with lazy translation objects ; nor startswith()\n wrapper = TextWrapper(width=width, initial_indent=indent, subsequent_indent=indent)\n # rem: TextWrapper doesn't add the indent on an empty text\n quote = '\\n'.join([line.startswith(indent) and indent+line or wrapper.fill(line) or indent for line in body.splitlines()])\n return ugettext(\"\\n\\n{sender} wrote:\\n{body}\\n\").format(sender=sender, body=quote)","function_tokens":["def","format_body","(","sender",",","body",",","indent","=","_","(","\"> \"",")",",","width","=","WRAP_WIDTH",")",":","indent","=","force_text","(","indent",")","# join() doesn't work on lists with lazy translation objects ; nor startswith()","wrapper","=","TextWrapper","(","width","=","width",",","initial_indent","=","indent",",","subsequent_indent","=","indent",")","# rem: TextWrapper doesn't add the indent on an empty text","quote","=","'\\n'",".","join","(","[","line",".","startswith","(","indent",")","and","indent","+","line","or","wrapper",".","fill","(","line",")","or","indent","for","line","in","body",".","splitlines","(",")","]",")","return","ugettext","(","\"\\n\\n{sender} wrote:\\n{body}\\n\"",")",".","format","(","sender","=","sender",",","body","=","quote",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/utils.py#L38-L54"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/utils.py","language":"python","identifier":"format_subject","parameters":"(subject)","argument_list":"","return_statement":"return subject if re.match(pattern, subject, re.IGNORECASE) else str.format(subject=subject)","docstring":"Prepend a pattern to the subject, unless already there.\n\n Matching is case-insensitive.","docstring_summary":"Prepend a pattern to the subject, unless already there.","docstring_tokens":["Prepend","a","pattern","to","the","subject","unless","already","there","."],"function":"def format_subject(subject):\n \"\"\"\n Prepend a pattern to the subject, unless already there.\n\n Matching is case-insensitive.\n\n \"\"\"\n str = ugettext(\"Re: {subject}\")\n pattern = '^' + str.replace('{subject}', '.*') + '$'\n return subject if re.match(pattern, subject, re.IGNORECASE) else str.format(subject=subject)","function_tokens":["def","format_subject","(","subject",")",":","str","=","ugettext","(","\"Re: {subject}\"",")","pattern","=","'^'","+","str",".","replace","(","'{subject}'",",","'.*'",")","+","'$'","return","subject","if","re",".","match","(","pattern",",","subject",",","re",".","IGNORECASE",")","else","str",".","format","(","subject","=","subject",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/utils.py#L57-L66"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/utils.py","language":"python","identifier":"email","parameters":"(subject_template, message_template, recipient_list, object, action, site)","argument_list":"","return_statement":"","docstring":"Compose and send an email.","docstring_summary":"Compose and send an email.","docstring_tokens":["Compose","and","send","an","email","."],"function":"def email(subject_template, message_template, recipient_list, object, action, site):\n \"\"\"Compose and send an email.\"\"\"\n ctx_dict = {'site': site, 'object': object, 'action': action}\n message = PostmanNotifyMail()\n for recipient in recipient_list:\n message.send(recipient, ctx_dict)","function_tokens":["def","email","(","subject_template",",","message_template",",","recipient_list",",","object",",","action",",","site",")",":","ctx_dict","=","{","'site'",":","site",",","'object'",":","object",",","'action'",":","action","}","message","=","PostmanNotifyMail","(",")","for","recipient","in","recipient_list",":","message",".","send","(","recipient",",","ctx_dict",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/utils.py#L69-L74"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/utils.py","language":"python","identifier":"email_visitor","parameters":"(object, action, site)","argument_list":"","return_statement":"","docstring":"Email a visitor.","docstring_summary":"Email a visitor.","docstring_tokens":["Email","a","visitor","."],"function":"def email_visitor(object, action, site):\n \"\"\"Email a visitor.\"\"\"\n email('postman\/email_visitor_subject.txt', 'postman\/email_visitor.txt', [object.email], object, action, site)","function_tokens":["def","email_visitor","(","object",",","action",",","site",")",":","email","(","'postman\/email_visitor_subject.txt'",",","'postman\/email_visitor.txt'",",","[","object",".","email","]",",","object",",","action",",","site",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/utils.py#L77-L79"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/utils.py","language":"python","identifier":"notify_user","parameters":"(object, action, site)","argument_list":"","return_statement":"","docstring":"Notify a user.","docstring_summary":"Notify a user.","docstring_tokens":["Notify","a","user","."],"function":"def notify_user(object, action, site):\n \"\"\"Notify a user.\"\"\"\n if action == 'rejection':\n user = object.sender\n label = 'postman_rejection'\n elif action == 'acceptance':\n user = object.recipient\n parent = object.parent\n label = 'postman_reply' if (parent and parent.sender_id == object.recipient_id) else 'postman_message'\n else:\n return\n if notification:\n # the context key 'message' is already used in django-notification\/models.py\/send_now() (v0.2.0)\n notification.send(users=[user], label=label, extra_context={'pm_message': object, 'pm_action': action})\n else:\n if not DISABLE_USER_EMAILING and user.email and user.is_active:\n email('postman\/email_user_subject.txt', 'postman\/email_user.txt', [user.email], object, action, site)","function_tokens":["def","notify_user","(","object",",","action",",","site",")",":","if","action","==","'rejection'",":","user","=","object",".","sender","label","=","'postman_rejection'","elif","action","==","'acceptance'",":","user","=","object",".","recipient","parent","=","object",".","parent","label","=","'postman_reply'","if","(","parent","and","parent",".","sender_id","==","object",".","recipient_id",")","else","'postman_message'","else",":","return","if","notification",":","# the context key 'message' is already used in django-notification\/models.py\/send_now() (v0.2.0)","notification",".","send","(","users","=","[","user","]",",","label","=","label",",","extra_context","=","{","'pm_message'",":","object",",","'pm_action'",":","action","}",")","else",":","if","not","DISABLE_USER_EMAILING","and","user",".","email","and","user",".","is_active",":","email","(","'postman\/email_user_subject.txt'",",","'postman\/email_user.txt'",",","[","user",".","email","]",",","object",",","action",",","site",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/utils.py#L82-L98"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/api.py","language":"python","identifier":"pm_broadcast","parameters":"(sender, recipients, subject, body='', skip_notification=False)","argument_list":"","return_statement":"","docstring":"Broadcast a message to multiple Users.\n For an easier cleanup, all these messages are directly marked as archived\n and deleted on the sender side.\n The message is expected to be issued from a trusted application, so moderation\n is not necessary and the status is automatically set to 'accepted'.\n\n Optional argument:\n ``skip_notification``: if the normal notification event is not wished","docstring_summary":"Broadcast a message to multiple Users.\n For an easier cleanup, all these messages are directly marked as archived\n and deleted on the sender side.\n The message is expected to be issued from a trusted application, so moderation\n is not necessary and the status is automatically set to 'accepted'.","docstring_tokens":["Broadcast","a","message","to","multiple","Users",".","For","an","easier","cleanup","all","these","messages","are","directly","marked","as","archived","and","deleted","on","the","sender","side",".","The","message","is","expected","to","be","issued","from","a","trusted","application","so","moderation","is","not","necessary","and","the","status","is","automatically","set","to","accepted","."],"function":"def pm_broadcast(sender, recipients, subject, body='', skip_notification=False):\n \"\"\"\n Broadcast a message to multiple Users.\n For an easier cleanup, all these messages are directly marked as archived\n and deleted on the sender side.\n The message is expected to be issued from a trusted application, so moderation\n is not necessary and the status is automatically set to 'accepted'.\n\n Optional argument:\n ``skip_notification``: if the normal notification event is not wished\n \"\"\"\n message = Message(subject=subject, body=body, sender=sender,\n sender_archived=True, sender_deleted_at=now(),\n moderation_status=STATUS_ACCEPTED, moderation_date=now())\n if not isinstance(recipients, (tuple, list)):\n recipients = (recipients,)\n for recipient in recipients:\n message.recipient = recipient\n message.pk = None\n message.save()\n if not skip_notification:\n message.notify_users(STATUS_PENDING, _get_site())","function_tokens":["def","pm_broadcast","(","sender",",","recipients",",","subject",",","body","=","''",",","skip_notification","=","False",")",":","message","=","Message","(","subject","=","subject",",","body","=","body",",","sender","=","sender",",","sender_archived","=","True",",","sender_deleted_at","=","now","(",")",",","moderation_status","=","STATUS_ACCEPTED",",","moderation_date","=","now","(",")",")","if","not","isinstance","(","recipients",",","(","tuple",",","list",")",")",":","recipients","=","(","recipients",",",")","for","recipient","in","recipients",":","message",".","recipient","=","recipient","message",".","pk","=","None","message",".","save","(",")","if","not","skip_notification",":","message",".","notify_users","(","STATUS_PENDING",",","_get_site","(",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/api.py#L36-L57"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/api.py","language":"python","identifier":"pm_write","parameters":"(sender, recipient, subject, body='', skip_notification=False,\n auto_archive=False, auto_delete=False, auto_moderators=None)","argument_list":"","return_statement":"","docstring":"Write a message to a User.\n Contrary to pm_broadcast(), the message is archived and\/or deleted on\n the sender side only if requested.\n The message may come from an untrusted application, a gateway for example,\n so it may be useful to involve some auto moderators in the processing.\n\n Optional arguments:\n ``skip_notification``: if the normal notification event is not wished\n ``auto_archive``: to mark the message as archived on the sender side\n ``auto_delete``: to mark the message as deleted on the sender side\n ``auto_moderators``: a list of auto-moderation functions","docstring_summary":"Write a message to a User.\n Contrary to pm_broadcast(), the message is archived and\/or deleted on\n the sender side only if requested.\n The message may come from an untrusted application, a gateway for example,\n so it may be useful to involve some auto moderators in the processing.","docstring_tokens":["Write","a","message","to","a","User",".","Contrary","to","pm_broadcast","()","the","message","is","archived","and","\/","or","deleted","on","the","sender","side","only","if","requested",".","The","message","may","come","from","an","untrusted","application","a","gateway","for","example","so","it","may","be","useful","to","involve","some","auto","moderators","in","the","processing","."],"function":"def pm_write(sender, recipient, subject, body='', skip_notification=False,\n auto_archive=False, auto_delete=False, auto_moderators=None):\n \"\"\"\n Write a message to a User.\n Contrary to pm_broadcast(), the message is archived and\/or deleted on\n the sender side only if requested.\n The message may come from an untrusted application, a gateway for example,\n so it may be useful to involve some auto moderators in the processing.\n\n Optional arguments:\n ``skip_notification``: if the normal notification event is not wished\n ``auto_archive``: to mark the message as archived on the sender side\n ``auto_delete``: to mark the message as deleted on the sender side\n ``auto_moderators``: a list of auto-moderation functions\n \"\"\"\n message = Message(subject=subject, body=body, sender=sender, recipient=recipient)\n initial_status = message.moderation_status\n if auto_moderators:\n message.auto_moderate(auto_moderators)\n else:\n message.moderation_status = STATUS_ACCEPTED\n message.clean_moderation(initial_status)\n if auto_archive:\n message.sender_archived = True\n if auto_delete:\n message.sender_deleted_at = now()\n message.save()\n if not skip_notification:\n message.notify_users(initial_status, _get_site())","function_tokens":["def","pm_write","(","sender",",","recipient",",","subject",",","body","=","''",",","skip_notification","=","False",",","auto_archive","=","False",",","auto_delete","=","False",",","auto_moderators","=","None",")",":","message","=","Message","(","subject","=","subject",",","body","=","body",",","sender","=","sender",",","recipient","=","recipient",")","initial_status","=","message",".","moderation_status","if","auto_moderators",":","message",".","auto_moderate","(","auto_moderators",")","else",":","message",".","moderation_status","=","STATUS_ACCEPTED","message",".","clean_moderation","(","initial_status",")","if","auto_archive",":","message",".","sender_archived","=","True","if","auto_delete",":","message",".","sender_deleted_at","=","now","(",")","message",".","save","(",")","if","not","skip_notification",":","message",".","notify_users","(","initial_status",",","_get_site","(",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/api.py#L60-L88"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/forms.py","language":"python","identifier":"BaseWriteForm.clean_recipients","parameters":"(self)","argument_list":"","return_statement":"return recipients","docstring":"Check no filter prohibit the exchange.","docstring_summary":"Check no filter prohibit the exchange.","docstring_tokens":["Check","no","filter","prohibit","the","exchange","."],"function":"def clean_recipients(self):\n \"\"\"Check no filter prohibit the exchange.\"\"\"\n recipients = self.cleaned_data['recipients']\n exchange_filter = getattr(self, 'exchange_filter', None)\n if exchange_filter:\n errors = []\n filtered_names = []\n recipients_list = recipients[:]\n for u in recipients_list:\n try:\n reason = exchange_filter(self.instance.sender, u, recipients_list)\n if reason is not None:\n recipients.remove(u)\n filtered_names.append(\n self.error_messages[\n 'filtered_user_with_reason' if reason else 'filtered_user'\n ].format(username=u.get_username(), reason=reason)\n )\n except forms.ValidationError as e:\n recipients.remove(u)\n errors.extend(e.messages)\n if filtered_names:\n errors.append(self.error_messages['filtered'].format(users=', '.join(filtered_names)))\n if errors:\n raise forms.ValidationError(errors)\n return recipients","function_tokens":["def","clean_recipients","(","self",")",":","recipients","=","self",".","cleaned_data","[","'recipients'","]","exchange_filter","=","getattr","(","self",",","'exchange_filter'",",","None",")","if","exchange_filter",":","errors","=","[","]","filtered_names","=","[","]","recipients_list","=","recipients","[",":","]","for","u","in","recipients_list",":","try",":","reason","=","exchange_filter","(","self",".","instance",".","sender",",","u",",","recipients_list",")","if","reason","is","not","None",":","recipients",".","remove","(","u",")","filtered_names",".","append","(","self",".","error_messages","[","'filtered_user_with_reason'","if","reason","else","'filtered_user'","]",".","format","(","username","=","u",".","get_username","(",")",",","reason","=","reason",")",")","except","forms",".","ValidationError","as","e",":","recipients",".","remove","(","u",")","errors",".","extend","(","e",".","messages",")","if","filtered_names",":","errors",".","append","(","self",".","error_messages","[","'filtered'","]",".","format","(","users","=","', '",".","join","(","filtered_names",")",")",")","if","errors",":","raise","forms",".","ValidationError","(","errors",")","return","recipients"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/forms.py#L75-L100"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/forms.py","language":"python","identifier":"BaseWriteForm.save","parameters":"(self, recipient=None, parent=None, auto_moderators=[])","argument_list":"","return_statement":"return is_successful","docstring":"Save as many messages as there are recipients.\n\n Additional actions:\n - If it's a reply, build a conversation\n - Call auto-moderators\n - Notify parties if needed\n\n Return False if one of the messages is rejected.","docstring_summary":"Save as many messages as there are recipients.","docstring_tokens":["Save","as","many","messages","as","there","are","recipients","."],"function":"def save(self, recipient=None, parent=None, auto_moderators=[]):\n \"\"\"\n Save as many messages as there are recipients.\n\n Additional actions:\n - If it's a reply, build a conversation\n - Call auto-moderators\n - Notify parties if needed\n\n Return False if one of the messages is rejected.\n\n \"\"\"\n recipients = self.cleaned_data.get('recipients', [])\n if parent and not parent.thread_id: # at the very first reply, make it a conversation\n parent.thread = parent\n parent.save()\n # but delay the setting of parent.replied_at to the moderation step\n if parent:\n self.instance.parent = parent\n self.instance.thread_id = parent.thread_id\n initial_moderation = self.instance.get_moderation()\n initial_dates = self.instance.get_dates()\n initial_status = self.instance.moderation_status\n if recipient:\n if isinstance(recipient, get_user_model()) and recipient in recipients:\n recipients.remove(recipient)\n recipients.insert(0, recipient)\n is_successful = True\n for r in recipients:\n if isinstance(r, get_user_model()):\n self.instance.recipient = r\n else:\n self.instance.recipient = None\n self.instance.email = r\n self.instance.pk = None # force_insert=True is not accessible from here\n self.instance.auto_moderate(auto_moderators)\n self.instance.clean_moderation(initial_status)\n self.instance.clean_for_visitor()\n m = super(BaseWriteForm, self).save()\n if self.instance.is_rejected():\n is_successful = False\n self.instance.update_parent(initial_status)\n self.instance.notify_users(initial_status, self.site)\n # some resets for next reuse\n if not isinstance(r, get_user_model()):\n self.instance.email = ''\n self.instance.set_moderation(*initial_moderation)\n self.instance.set_dates(*initial_dates)\n return is_successful","function_tokens":["def","save","(","self",",","recipient","=","None",",","parent","=","None",",","auto_moderators","=","[","]",")",":","recipients","=","self",".","cleaned_data",".","get","(","'recipients'",",","[","]",")","if","parent","and","not","parent",".","thread_id",":","# at the very first reply, make it a conversation","parent",".","thread","=","parent","parent",".","save","(",")","# but delay the setting of parent.replied_at to the moderation step","if","parent",":","self",".","instance",".","parent","=","parent","self",".","instance",".","thread_id","=","parent",".","thread_id","initial_moderation","=","self",".","instance",".","get_moderation","(",")","initial_dates","=","self",".","instance",".","get_dates","(",")","initial_status","=","self",".","instance",".","moderation_status","if","recipient",":","if","isinstance","(","recipient",",","get_user_model","(",")",")","and","recipient","in","recipients",":","recipients",".","remove","(","recipient",")","recipients",".","insert","(","0",",","recipient",")","is_successful","=","True","for","r","in","recipients",":","if","isinstance","(","r",",","get_user_model","(",")",")",":","self",".","instance",".","recipient","=","r","else",":","self",".","instance",".","recipient","=","None","self",".","instance",".","email","=","r","self",".","instance",".","pk","=","None","# force_insert=True is not accessible from here","self",".","instance",".","auto_moderate","(","auto_moderators",")","self",".","instance",".","clean_moderation","(","initial_status",")","self",".","instance",".","clean_for_visitor","(",")","m","=","super","(","BaseWriteForm",",","self",")",".","save","(",")","if","self",".","instance",".","is_rejected","(",")",":","is_successful","=","False","self",".","instance",".","update_parent","(","initial_status",")","self",".","instance",".","notify_users","(","initial_status",",","self",".","site",")","# some resets for next reuse","if","not","isinstance","(","r",",","get_user_model","(",")",")",":","self",".","instance",".","email","=","''","self",".","instance",".","set_moderation","(","*","initial_moderation",")","self",".","instance",".","set_dates","(","*","initial_dates",")","return","is_successful"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/forms.py#L102-L150"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/forms.py","language":"python","identifier":"BaseReplyForm.clean","parameters":"(self)","argument_list":"","return_statement":"return super(BaseReplyForm, self).clean()","docstring":"Check that the recipient is correctly initialized.","docstring_summary":"Check that the recipient is correctly initialized.","docstring_tokens":["Check","that","the","recipient","is","correctly","initialized","."],"function":"def clean(self):\n \"\"\"Check that the recipient is correctly initialized.\"\"\"\n if not self.recipient:\n raise forms.ValidationError(ugettext(\"Undefined recipient.\"))\n return super(BaseReplyForm, self).clean()","function_tokens":["def","clean","(","self",")",":","if","not","self",".","recipient",":","raise","forms",".","ValidationError","(","ugettext","(","\"Undefined recipient.\"",")",")","return","super","(","BaseReplyForm",",","self",")",".","clean","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/forms.py#L184-L188"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/admin.py","language":"python","identifier":"MessageAdminForm.clean","parameters":"(self)","argument_list":"","return_statement":"return cleaned_data","docstring":"Check data validity and coherence.","docstring_summary":"Check data validity and coherence.","docstring_tokens":["Check","data","validity","and","coherence","."],"function":"def clean(self):\n \"\"\"Check data validity and coherence.\"\"\"\n cleaned_data = super(MessageAdminForm, self).clean()\n sender = cleaned_data.get('sender')\n recipient = cleaned_data.get('recipient')\n email = cleaned_data.get('email')\n errors = []\n if not sender and not recipient:\n errors.append(ugettext(\"Sender and Recipient cannot be both undefined.\"))\n if 'sender' in cleaned_data:\n del cleaned_data['sender']\n if 'recipient' in cleaned_data:\n del cleaned_data['recipient']\n elif sender and recipient:\n if email:\n errors.append(ugettext(\"Visitor's email is in excess.\"))\n if 'email' in cleaned_data:\n del cleaned_data['email']\n else:\n if not email:\n errors.append(ugettext(\"Visitor's email is missing.\"))\n if 'email' in cleaned_data:\n del cleaned_data['email']\n sent_at = cleaned_data.get('sent_at')\n read_at = cleaned_data.get('read_at')\n if read_at and read_at < sent_at:\n errors.append(ugettext(\"Reading date must be later to sending date.\"))\n if 'read_at' in cleaned_data:\n del cleaned_data['read_at']\n sender_deleted_at = cleaned_data.get('sender_deleted_at')\n if sender_deleted_at and sender_deleted_at < sent_at:\n errors.append(ugettext(\"Deletion date by sender must be later to sending date.\"))\n if 'sender_deleted_at' in cleaned_data:\n del cleaned_data['sender_deleted_at']\n recipient_deleted_at = cleaned_data.get('recipient_deleted_at')\n if recipient_deleted_at and recipient_deleted_at < sent_at:\n errors.append(ugettext(\"Deletion date by recipient must be later to sending date.\"))\n if 'recipient_deleted_at' in cleaned_data:\n del cleaned_data['recipient_deleted_at']\n replied_at = cleaned_data.get('replied_at')\n obj = self.instance\n if replied_at:\n len_begin = len(errors)\n if replied_at < sent_at:\n errors.append(ugettext(\"Response date must be later to sending date.\"))\n if not read_at:\n errors.append(ugettext(\"The message cannot be replied without having been read.\"))\n elif replied_at < read_at:\n errors.append(ugettext(\"Response date must be later to reading date.\"))\n if not obj.get_replies_count():\n errors.append(ugettext(\"Response date cannot be set without at least one reply.\"))\n if not obj.thread_id:\n errors.append(ugettext(\"The message cannot be replied without being in a conversation.\"))\n if len(errors) > len_begin:\n if 'replied_at' in cleaned_data:\n del cleaned_data['replied_at']\n # if obj.parent_id and not obj.thread_id:# can't be set by the form\n if errors:\n raise forms.ValidationError(errors)\n\n self.initial_status = obj.moderation_status\n return cleaned_data","function_tokens":["def","clean","(","self",")",":","cleaned_data","=","super","(","MessageAdminForm",",","self",")",".","clean","(",")","sender","=","cleaned_data",".","get","(","'sender'",")","recipient","=","cleaned_data",".","get","(","'recipient'",")","email","=","cleaned_data",".","get","(","'email'",")","errors","=","[","]","if","not","sender","and","not","recipient",":","errors",".","append","(","ugettext","(","\"Sender and Recipient cannot be both undefined.\"",")",")","if","'sender'","in","cleaned_data",":","del","cleaned_data","[","'sender'","]","if","'recipient'","in","cleaned_data",":","del","cleaned_data","[","'recipient'","]","elif","sender","and","recipient",":","if","email",":","errors",".","append","(","ugettext","(","\"Visitor's email is in excess.\"",")",")","if","'email'","in","cleaned_data",":","del","cleaned_data","[","'email'","]","else",":","if","not","email",":","errors",".","append","(","ugettext","(","\"Visitor's email is missing.\"",")",")","if","'email'","in","cleaned_data",":","del","cleaned_data","[","'email'","]","sent_at","=","cleaned_data",".","get","(","'sent_at'",")","read_at","=","cleaned_data",".","get","(","'read_at'",")","if","read_at","and","read_at","<","sent_at",":","errors",".","append","(","ugettext","(","\"Reading date must be later to sending date.\"",")",")","if","'read_at'","in","cleaned_data",":","del","cleaned_data","[","'read_at'","]","sender_deleted_at","=","cleaned_data",".","get","(","'sender_deleted_at'",")","if","sender_deleted_at","and","sender_deleted_at","<","sent_at",":","errors",".","append","(","ugettext","(","\"Deletion date by sender must be later to sending date.\"",")",")","if","'sender_deleted_at'","in","cleaned_data",":","del","cleaned_data","[","'sender_deleted_at'","]","recipient_deleted_at","=","cleaned_data",".","get","(","'recipient_deleted_at'",")","if","recipient_deleted_at","and","recipient_deleted_at","<","sent_at",":","errors",".","append","(","ugettext","(","\"Deletion date by recipient must be later to sending date.\"",")",")","if","'recipient_deleted_at'","in","cleaned_data",":","del","cleaned_data","[","'recipient_deleted_at'","]","replied_at","=","cleaned_data",".","get","(","'replied_at'",")","obj","=","self",".","instance","if","replied_at",":","len_begin","=","len","(","errors",")","if","replied_at","<","sent_at",":","errors",".","append","(","ugettext","(","\"Response date must be later to sending date.\"",")",")","if","not","read_at",":","errors",".","append","(","ugettext","(","\"The message cannot be replied without having been read.\"",")",")","elif","replied_at","<","read_at",":","errors",".","append","(","ugettext","(","\"Response date must be later to reading date.\"",")",")","if","not","obj",".","get_replies_count","(",")",":","errors",".","append","(","ugettext","(","\"Response date cannot be set without at least one reply.\"",")",")","if","not","obj",".","thread_id",":","errors",".","append","(","ugettext","(","\"The message cannot be replied without being in a conversation.\"",")",")","if","len","(","errors",")",">","len_begin",":","if","'replied_at'","in","cleaned_data",":","del","cleaned_data","[","'replied_at'","]","# if obj.parent_id and not obj.thread_id:# can't be set by the form","if","errors",":","raise","forms",".","ValidationError","(","errors",")","self",".","initial_status","=","obj",".","moderation_status","return","cleaned_data"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/admin.py#L22-L83"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/admin.py","language":"python","identifier":"MessageAdmin.get_queryset","parameters":"(self, request)","argument_list":"","return_statement":"return super(MessageAdmin, self).get_queryset(request).select_related('sender', 'recipient')","docstring":"Add a custom select_related() to avoid a bunch of queries for users\n in the 'change list' admin view.\n\n Setting 'list_select_related = True' is not efficient as the default\n select_related() does not follow foreign keys that have null=True.","docstring_summary":"Add a custom select_related() to avoid a bunch of queries for users\n in the 'change list' admin view.","docstring_tokens":["Add","a","custom","select_related","()","to","avoid","a","bunch","of","queries","for","users","in","the","change","list","admin","view","."],"function":"def get_queryset(self, request): # changed in Django 1.6: \"The get_queryset method was previously named queryset.\"\n \"\"\"\n Add a custom select_related() to avoid a bunch of queries for users\n in the 'change list' admin view.\n\n Setting 'list_select_related = True' is not efficient as the default\n select_related() does not follow foreign keys that have null=True.\n\n \"\"\"\n return super(MessageAdmin, self).get_queryset(request).select_related('sender', 'recipient')","function_tokens":["def","get_queryset","(","self",",","request",")",":","# changed in Django 1.6: \"The get_queryset method was previously named queryset.\"","return","super","(","MessageAdmin",",","self",")",".","get_queryset","(","request",")",".","select_related","(","'sender'",",","'recipient'",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/admin.py#L121-L130"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/admin.py","language":"python","identifier":"MessageAdmin.save_model","parameters":"(self, request, obj, form, change)","argument_list":"","return_statement":"","docstring":"Add some actions around the save.\n\n Before the save, adjust some constrained fields.\n After the save, update related objects and notify parties if needed.","docstring_summary":"Add some actions around the save.","docstring_tokens":["Add","some","actions","around","the","save","."],"function":"def save_model(self, request, obj, form, change):\n \"\"\"\n Add some actions around the save.\n\n Before the save, adjust some constrained fields.\n After the save, update related objects and notify parties if needed.\n\n \"\"\"\n obj.clean_moderation(form.initial_status, request.user)\n obj.clean_for_visitor()\n super(MessageAdmin, self).save_model(request, obj, form, change)\n obj.update_parent(form.initial_status)\n obj.notify_users(form.initial_status, get_current_site(request), is_auto_moderated=False)","function_tokens":["def","save_model","(","self",",","request",",","obj",",","form",",","change",")",":","obj",".","clean_moderation","(","form",".","initial_status",",","request",".","user",")","obj",".","clean_for_visitor","(",")","super","(","MessageAdmin",",","self",")",".","save_model","(","request",",","obj",",","form",",","change",")","obj",".","update_parent","(","form",".","initial_status",")","obj",".","notify_users","(","form",".","initial_status",",","get_current_site","(","request",")",",","is_auto_moderated","=","False",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/admin.py#L133-L145"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/admin.py","language":"python","identifier":"PendingMessageAdminForm.clean","parameters":"(self)","argument_list":"","return_statement":"return cleaned_data","docstring":"Set status according to the button used to submit.","docstring_summary":"Set status according to the button used to submit.","docstring_tokens":["Set","status","according","to","the","button","used","to","submit","."],"function":"def clean(self):\n \"\"\"Set status according to the button used to submit.\"\"\"\n cleaned_data = super(PendingMessageAdminForm, self).clean()\n obj = self.instance\n self.initial_status = obj.moderation_status\n # look for for button names provided by custom admin\/postman\/pendingmessage\/change_form.html\n if '_saveasaccepted' in self.data:\n obj.set_accepted()\n elif '_saveasrejected' in self.data:\n obj.set_rejected()\n return cleaned_data","function_tokens":["def","clean","(","self",")",":","cleaned_data","=","super","(","PendingMessageAdminForm",",","self",")",".","clean","(",")","obj","=","self",".","instance","self",".","initial_status","=","obj",".","moderation_status","# look for for button names provided by custom admin\/postman\/pendingmessage\/change_form.html","if","'_saveasaccepted'","in","self",".","data",":","obj",".","set_accepted","(",")","elif","'_saveasrejected'","in","self",".","data",":","obj",".","set_rejected","(",")","return","cleaned_data"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/admin.py#L154-L164"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/admin.py","language":"python","identifier":"PendingMessageAdmin.has_add_permission","parameters":"(self, request)","argument_list":"","return_statement":"return False","docstring":"Adding is impossible","docstring_summary":"Adding is impossible","docstring_tokens":["Adding","is","impossible"],"function":"def has_add_permission(self, request):\n \"Adding is impossible\"\n return False","function_tokens":["def","has_add_permission","(","self",",","request",")",":","return","False"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/admin.py#L188-L190"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/admin.py","language":"python","identifier":"PendingMessageAdmin.has_delete_permission","parameters":"(self, request, obj=None)","argument_list":"","return_statement":"return False","docstring":"Deleting is impossible","docstring_summary":"Deleting is impossible","docstring_tokens":["Deleting","is","impossible"],"function":"def has_delete_permission(self, request, obj=None):\n \"Deleting is impossible\"\n return False","function_tokens":["def","has_delete_permission","(","self",",","request",",","obj","=","None",")",":","return","False"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/admin.py#L192-L194"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/context_processors.py","language":"python","identifier":"inbox","parameters":"(request)","argument_list":"","return_statement":"","docstring":"Provide the count of unread messages for an authenticated user.","docstring_summary":"Provide the count of unread messages for an authenticated user.","docstring_tokens":["Provide","the","count","of","unread","messages","for","an","authenticated","user","."],"function":"def inbox(request):\n \"\"\"Provide the count of unread messages for an authenticated user.\"\"\"\n if request.user.is_authenticated():\n return {'postman_unread_count': Message.objects.inbox_unread_count(request.user)}\n else:\n return {}","function_tokens":["def","inbox","(","request",")",":","if","request",".","user",".","is_authenticated","(",")",":","return","{","'postman_unread_count'",":","Message",".","objects",".","inbox_unread_count","(","request",".","user",")","}","else",":","return","{","}"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/context_processors.py#L6-L11"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"setup","parameters":"()","argument_list":"","return_statement":"","docstring":"Deferred actions, that can not be done at import time since Django 1.7.\n Normally called in AppConfig.ready().\n For backwards compatibility, also called on first need.","docstring_summary":"Deferred actions, that can not be done at import time since Django 1.7.\n Normally called in AppConfig.ready().\n For backwards compatibility, also called on first need.","docstring_tokens":["Deferred","actions","that","can","not","be","done","at","import","time","since","Django","1",".","7",".","Normally","called","in","AppConfig",".","ready","()",".","For","backwards","compatibility","also","called","on","first","need","."],"function":"def setup():\n \"\"\"\n Deferred actions, that can not be done at import time since Django 1.7.\n Normally called in AppConfig.ready().\n For backwards compatibility, also called on first need.\n\n \"\"\"\n try:\n from django.contrib.auth import get_user_model # Django 1.5\n except ImportError:\n from postman.future_1_5 import get_user_model\n ORDER_BY_FIELDS.update({\n 'f': 'sender__' + get_user_model().USERNAME_FIELD, # as 'from'\n 't': 'recipient__' + get_user_model().USERNAME_FIELD, # as 'to'\n 's': 'subject', # as 'subject'\n 'd': 'sent_at', # as 'date'\n })","function_tokens":["def","setup","(",")",":","try",":","from","django",".","contrib",".","auth","import","get_user_model","# Django 1.5","except","ImportError",":","from","postman",".","future_1_5","import","get_user_model","ORDER_BY_FIELDS",".","update","(","{","'f'",":","'sender__'","+","get_user_model","(",")",".","USERNAME_FIELD",",","# as 'from'","'t'",":","'recipient__'","+","get_user_model","(",")",".","USERNAME_FIELD",",","# as 'to'","'s'",":","'subject'",",","# as 'subject'","'d'",":","'sent_at'",",","# as 'date'","}",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L41-L57"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"get_order_by","parameters":"(query_dict)","argument_list":"","return_statement":"","docstring":"Return a field name, optionally prefixed for descending order, or None if not found.\n\n Argument:\n ``query_dict``: a dictionary to look for a key dedicated to ordering purpose","docstring_summary":"Return a field name, optionally prefixed for descending order, or None if not found.","docstring_tokens":["Return","a","field","name","optionally","prefixed","for","descending","order","or","None","if","not","found","."],"function":"def get_order_by(query_dict):\n \"\"\"\n Return a field name, optionally prefixed for descending order, or None if not found.\n\n Argument:\n ``query_dict``: a dictionary to look for a key dedicated to ordering purpose\n\n \"\"\"\n if ORDER_BY_KEY in query_dict:\n code = query_dict[ORDER_BY_KEY] # code may be uppercase or lowercase\n if not ORDER_BY_FIELDS: # backwards compatibility, before Django 1.7\n setup()\n order_by_field = ORDER_BY_FIELDS.get(code.lower())\n if order_by_field:\n if code.isupper():\n order_by_field = '-' + order_by_field\n return order_by_field","function_tokens":["def","get_order_by","(","query_dict",")",":","if","ORDER_BY_KEY","in","query_dict",":","code","=","query_dict","[","ORDER_BY_KEY","]","# code may be uppercase or lowercase","if","not","ORDER_BY_FIELDS",":","# backwards compatibility, before Django 1.7","setup","(",")","order_by_field","=","ORDER_BY_FIELDS",".","get","(","code",".","lower","(",")",")","if","order_by_field",":","if","code",".","isupper","(",")",":","order_by_field","=","'-'","+","order_by_field","return","order_by_field"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L60-L76"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"get_user_representation","parameters":"(user)","argument_list":"","return_statement":"return force_text(user)","docstring":"Return a User representation for display, configurable through an optional setting.","docstring_summary":"Return a User representation for display, configurable through an optional setting.","docstring_tokens":["Return","a","User","representation","for","display","configurable","through","an","optional","setting","."],"function":"def get_user_representation(user):\n \"\"\"\n Return a User representation for display, configurable through an optional setting.\n \"\"\"\n show_user_as = getattr(settings, 'POSTMAN_SHOW_USER_AS', None)\n if isinstance(show_user_as, six.string_types):\n attr = getattr(user, show_user_as, None)\n if callable(attr):\n attr = attr()\n if attr:\n return force_text(attr)\n elif callable(show_user_as):\n try:\n return force_text(show_user_as(user))\n except:\n pass\n return force_text(user)","function_tokens":["def","get_user_representation","(","user",")",":","show_user_as","=","getattr","(","settings",",","'POSTMAN_SHOW_USER_AS'",",","None",")","if","isinstance","(","show_user_as",",","six",".","string_types",")",":","attr","=","getattr","(","user",",","show_user_as",",","None",")","if","callable","(","attr",")",":","attr","=","attr","(",")","if","attr",":","return","force_text","(","attr",")","elif","callable","(","show_user_as",")",":","try",":","return","force_text","(","show_user_as","(","user",")",")","except",":","pass","return","force_text","(","user",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L79-L95"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager._folder","parameters":"(self, related, filters, option=None, order_by=None)","argument_list":"","return_statement":"","docstring":"Base code, in common to the folders.","docstring_summary":"Base code, in common to the folders.","docstring_tokens":["Base","code","in","common","to","the","folders","."],"function":"def _folder(self, related, filters, option=None, order_by=None):\n \"\"\"Base code, in common to the folders.\"\"\"\n qs = self.all() if option == OPTION_MESSAGES else QuerySet(self.model, PostmanQuery(self.model), using=self._db)\n if related:\n qs = qs.select_related(*related)\n if order_by:\n qs = qs.order_by(order_by)\n if isinstance(filters, (list, tuple)):\n lookups = models.Q()\n for filter in filters:\n lookups |= models.Q(**filter)\n else:\n lookups = models.Q(**filters)\n if option == OPTION_MESSAGES:\n return qs.filter(lookups)\n # Adding a 'count' attribute, to be similar to the by-conversation case,\n # should not be necessary. Otherwise add:\n # .extra(select={'count': 'SELECT 1'})\n else:\n qs = qs.extra(select={'count': '{0}.count'.format(qs.query.pm_alias_prefix)})\n qs.query.pm_set_extra(table=(\n # extra columns are always first in the SELECT query\n self.filter(lookups, thread_id__isnull=True).extra(select={'count': 0})\\\n .values_list('id', 'count').order_by(),\n # use separate annotate() to keep control of the necessary order\n self.filter(lookups, thread_id__isnull=False).values('thread').annotate(count=models.Count('pk')).annotate(id=models.Max('pk'))\\\n .values_list('id', 'count').order_by(),\n ))\n return qs","function_tokens":["def","_folder","(","self",",","related",",","filters",",","option","=","None",",","order_by","=","None",")",":","qs","=","self",".","all","(",")","if","option","==","OPTION_MESSAGES","else","QuerySet","(","self",".","model",",","PostmanQuery","(","self",".","model",")",",","using","=","self",".","_db",")","if","related",":","qs","=","qs",".","select_related","(","*","related",")","if","order_by",":","qs","=","qs",".","order_by","(","order_by",")","if","isinstance","(","filters",",","(","list",",","tuple",")",")",":","lookups","=","models",".","Q","(",")","for","filter","in","filters",":","lookups","|=","models",".","Q","(","*","*","filter",")","else",":","lookups","=","models",".","Q","(","*","*","filters",")","if","option","==","OPTION_MESSAGES",":","return","qs",".","filter","(","lookups",")","# Adding a 'count' attribute, to be similar to the by-conversation case,","# should not be necessary. Otherwise add:","# .extra(select={'count': 'SELECT 1'})","else",":","qs","=","qs",".","extra","(","select","=","{","'count'",":","'{0}.count'",".","format","(","qs",".","query",".","pm_alias_prefix",")","}",")","qs",".","query",".","pm_set_extra","(","table","=","(","# extra columns are always first in the SELECT query","self",".","filter","(","lookups",",","thread_id__isnull","=","True",")",".","extra","(","select","=","{","'count'",":","0","}",")",".","values_list","(","'id'",",","'count'",")",".","order_by","(",")",",","# use separate annotate() to keep control of the necessary order","self",".","filter","(","lookups",",","thread_id__isnull","=","False",")",".","values","(","'thread'",")",".","annotate","(","count","=","models",".","Count","(","'pk'",")",")",".","annotate","(","id","=","models",".","Max","(","'pk'",")",")",".","values_list","(","'id'",",","'count'",")",".","order_by","(",")",",",")",")","return","qs"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L101-L129"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.inbox","parameters":"(self, user, related=True, **kwargs)","argument_list":"","return_statement":"return self._folder(related, filters, **kwargs)","docstring":"Return accepted messages received by a user but not marked as archived or deleted.","docstring_summary":"Return accepted messages received by a user but not marked as archived or deleted.","docstring_tokens":["Return","accepted","messages","received","by","a","user","but","not","marked","as","archived","or","deleted","."],"function":"def inbox(self, user, related=True, **kwargs):\n \"\"\"\n Return accepted messages received by a user but not marked as archived or deleted.\n \"\"\"\n related = ('sender',) if related else None\n filters = {\n 'recipient': user,\n 'recipient_archived': False,\n 'recipient_deleted_at__isnull': True,\n 'moderation_status': STATUS_ACCEPTED,\n }\n return self._folder(related, filters, **kwargs)","function_tokens":["def","inbox","(","self",",","user",",","related","=","True",",","*","*","kwargs",")",":","related","=","(","'sender'",",",")","if","related","else","None","filters","=","{","'recipient'",":","user",",","'recipient_archived'",":","False",",","'recipient_deleted_at__isnull'",":","True",",","'moderation_status'",":","STATUS_ACCEPTED",",","}","return","self",".","_folder","(","related",",","filters",",","*","*","kwargs",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L131-L142"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.inbox_unread_count","parameters":"(self, user)","argument_list":"","return_statement":"return self.inbox(user, related=False, option=OPTION_MESSAGES).filter(read_at__isnull=True).count()","docstring":"Return the number of unread messages for a user.\n\n Designed for context_processors.py and templatetags\/postman_tags.py","docstring_summary":"Return the number of unread messages for a user.","docstring_tokens":["Return","the","number","of","unread","messages","for","a","user","."],"function":"def inbox_unread_count(self, user):\n \"\"\"\n Return the number of unread messages for a user.\n\n Designed for context_processors.py and templatetags\/postman_tags.py\n\n \"\"\"\n return self.inbox(user, related=False, option=OPTION_MESSAGES).filter(read_at__isnull=True).count()","function_tokens":["def","inbox_unread_count","(","self",",","user",")",":","return","self",".","inbox","(","user",",","related","=","False",",","option","=","OPTION_MESSAGES",")",".","filter","(","read_at__isnull","=","True",")",".","count","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L144-L151"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.sent","parameters":"(self, user, **kwargs)","argument_list":"","return_statement":"return self._folder(related, filters, **kwargs)","docstring":"Return all messages sent by a user but not marked as archived or deleted.","docstring_summary":"Return all messages sent by a user but not marked as archived or deleted.","docstring_tokens":["Return","all","messages","sent","by","a","user","but","not","marked","as","archived","or","deleted","."],"function":"def sent(self, user, **kwargs):\n \"\"\"\n Return all messages sent by a user but not marked as archived or deleted.\n \"\"\"\n related = ('recipient',)\n filters = {\n 'sender': user,\n 'sender_archived': False,\n 'sender_deleted_at__isnull': True,\n # allow to see pending and rejected messages as well\n }\n return self._folder(related, filters, **kwargs)","function_tokens":["def","sent","(","self",",","user",",","*","*","kwargs",")",":","related","=","(","'recipient'",",",")","filters","=","{","'sender'",":","user",",","'sender_archived'",":","False",",","'sender_deleted_at__isnull'",":","True",",","# allow to see pending and rejected messages as well","}","return","self",".","_folder","(","related",",","filters",",","*","*","kwargs",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L153-L164"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.archives","parameters":"(self, user, **kwargs)","argument_list":"","return_statement":"return self._folder(related, filters, **kwargs)","docstring":"Return messages belonging to a user and marked as archived.","docstring_summary":"Return messages belonging to a user and marked as archived.","docstring_tokens":["Return","messages","belonging","to","a","user","and","marked","as","archived","."],"function":"def archives(self, user, **kwargs):\n \"\"\"\n Return messages belonging to a user and marked as archived.\n \"\"\"\n related = ('sender', 'recipient')\n filters = ({\n 'recipient': user,\n 'recipient_archived': True,\n 'recipient_deleted_at__isnull': True,\n 'moderation_status': STATUS_ACCEPTED,\n }, {\n 'sender': user,\n 'sender_archived': True,\n 'sender_deleted_at__isnull': True,\n })\n return self._folder(related, filters, **kwargs)","function_tokens":["def","archives","(","self",",","user",",","*","*","kwargs",")",":","related","=","(","'sender'",",","'recipient'",")","filters","=","(","{","'recipient'",":","user",",","'recipient_archived'",":","True",",","'recipient_deleted_at__isnull'",":","True",",","'moderation_status'",":","STATUS_ACCEPTED",",","}",",","{","'sender'",":","user",",","'sender_archived'",":","True",",","'sender_deleted_at__isnull'",":","True",",","}",")","return","self",".","_folder","(","related",",","filters",",","*","*","kwargs",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L166-L181"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.trash","parameters":"(self, user, **kwargs)","argument_list":"","return_statement":"return self._folder(related, filters, **kwargs)","docstring":"Return messages belonging to a user and marked as deleted.","docstring_summary":"Return messages belonging to a user and marked as deleted.","docstring_tokens":["Return","messages","belonging","to","a","user","and","marked","as","deleted","."],"function":"def trash(self, user, **kwargs):\n \"\"\"\n Return messages belonging to a user and marked as deleted.\n \"\"\"\n related = ('sender', 'recipient')\n filters = ({\n 'recipient': user,\n 'recipient_deleted_at__isnull': False,\n 'moderation_status': STATUS_ACCEPTED,\n }, {\n 'sender': user,\n 'sender_deleted_at__isnull': False,\n })\n return self._folder(related, filters, **kwargs)","function_tokens":["def","trash","(","self",",","user",",","*","*","kwargs",")",":","related","=","(","'sender'",",","'recipient'",")","filters","=","(","{","'recipient'",":","user",",","'recipient_deleted_at__isnull'",":","False",",","'moderation_status'",":","STATUS_ACCEPTED",",","}",",","{","'sender'",":","user",",","'sender_deleted_at__isnull'",":","False",",","}",")","return","self",".","_folder","(","related",",","filters",",","*","*","kwargs",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L183-L196"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.thread","parameters":"(self, user, filter)","argument_list":"","return_statement":"return self.select_related('sender', 'recipient').filter(\n filter,\n (models.Q(recipient=user) & models.Q(moderation_status=STATUS_ACCEPTED)) | models.Q(sender=user),\n ).order_by('sent_at')","docstring":"Return message\/conversation for display.","docstring_summary":"Return message\/conversation for display.","docstring_tokens":["Return","message","\/","conversation","for","display","."],"function":"def thread(self, user, filter):\n \"\"\"\n Return message\/conversation for display.\n \"\"\"\n return self.select_related('sender', 'recipient').filter(\n filter,\n (models.Q(recipient=user) & models.Q(moderation_status=STATUS_ACCEPTED)) | models.Q(sender=user),\n ).order_by('sent_at')","function_tokens":["def","thread","(","self",",","user",",","filter",")",":","return","self",".","select_related","(","'sender'",",","'recipient'",")",".","filter","(","filter",",","(","models",".","Q","(","recipient","=","user",")","&","models",".","Q","(","moderation_status","=","STATUS_ACCEPTED",")",")","|","models",".","Q","(","sender","=","user",")",",",")",".","order_by","(","'sent_at'",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L198-L205"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.as_recipient","parameters":"(self, user, filter)","argument_list":"","return_statement":"return self.filter(filter, recipient=user, moderation_status=STATUS_ACCEPTED)","docstring":"Return messages matching a filter AND being visible to a user as the recipient.","docstring_summary":"Return messages matching a filter AND being visible to a user as the recipient.","docstring_tokens":["Return","messages","matching","a","filter","AND","being","visible","to","a","user","as","the","recipient","."],"function":"def as_recipient(self, user, filter):\n \"\"\"\n Return messages matching a filter AND being visible to a user as the recipient.\n \"\"\"\n return self.filter(filter, recipient=user, moderation_status=STATUS_ACCEPTED)","function_tokens":["def","as_recipient","(","self",",","user",",","filter",")",":","return","self",".","filter","(","filter",",","recipient","=","user",",","moderation_status","=","STATUS_ACCEPTED",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L207-L211"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.as_sender","parameters":"(self, user, filter)","argument_list":"","return_statement":"return self.filter(filter, sender=user)","docstring":"Return messages matching a filter AND being visible to a user as the sender.","docstring_summary":"Return messages matching a filter AND being visible to a user as the sender.","docstring_tokens":["Return","messages","matching","a","filter","AND","being","visible","to","a","user","as","the","sender","."],"function":"def as_sender(self, user, filter):\n \"\"\"\n Return messages matching a filter AND being visible to a user as the sender.\n \"\"\"\n return self.filter(filter, sender=user)","function_tokens":["def","as_sender","(","self",",","user",",","filter",")",":","return","self",".","filter","(","filter",",","sender","=","user",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L213-L217"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.perms","parameters":"(self, user)","argument_list":"","return_statement":"return models.Q(recipient=user) & models.Q(moderation_status=STATUS_ACCEPTED) & models.Q(recipient_deleted_at__isnull=True)","docstring":"Return a field-lookups filter as a permission controller for a reply request.\n\n The user must be the recipient of the accepted, non-deleted, message","docstring_summary":"Return a field-lookups filter as a permission controller for a reply request.","docstring_tokens":["Return","a","field","-","lookups","filter","as","a","permission","controller","for","a","reply","request","."],"function":"def perms(self, user):\n \"\"\"\n Return a field-lookups filter as a permission controller for a reply request.\n\n The user must be the recipient of the accepted, non-deleted, message\n\n \"\"\"\n return models.Q(recipient=user) & models.Q(moderation_status=STATUS_ACCEPTED) & models.Q(recipient_deleted_at__isnull=True)","function_tokens":["def","perms","(","self",",","user",")",":","return","models",".","Q","(","recipient","=","user",")","&","models",".","Q","(","moderation_status","=","STATUS_ACCEPTED",")","&","models",".","Q","(","recipient_deleted_at__isnull","=","True",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L219-L226"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"MessageManager.set_read","parameters":"(self, user, filter)","argument_list":"","return_statement":"return self.filter(\n filter,\n recipient=user,\n moderation_status=STATUS_ACCEPTED,\n read_at__isnull=True,\n ).update(read_at=now())","docstring":"Set messages as read.","docstring_summary":"Set messages as read.","docstring_tokens":["Set","messages","as","read","."],"function":"def set_read(self, user, filter):\n \"\"\"\n Set messages as read.\n \"\"\"\n return self.filter(\n filter,\n recipient=user,\n moderation_status=STATUS_ACCEPTED,\n read_at__isnull=True,\n ).update(read_at=now())","function_tokens":["def","set_read","(","self",",","user",",","filter",")",":","return","self",".","filter","(","filter",",","recipient","=","user",",","moderation_status","=","STATUS_ACCEPTED",",","read_at__isnull","=","True",",",")",".","update","(","read_at","=","now","(",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L228-L237"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"PendingMessageManager.get_queryset","parameters":"(self)","argument_list":"","return_statement":"return super(PendingMessageManager, self).get_queryset().filter(moderation_status=STATUS_PENDING)","docstring":"Filter to get only pending objects.","docstring_summary":"Filter to get only pending objects.","docstring_tokens":["Filter","to","get","only","pending","objects","."],"function":"def get_queryset(self): # changed in Django 1.6: \"The get_queryset method was previously named get_query_set.\"\n \"\"\"Filter to get only pending objects.\"\"\"\n return super(PendingMessageManager, self).get_queryset().filter(moderation_status=STATUS_PENDING)","function_tokens":["def","get_queryset","(","self",")",":","# changed in Django 1.6: \"The get_queryset method was previously named get_query_set.\"","return","super","(","PendingMessageManager",",","self",")",".","get_queryset","(",")",".","filter","(","moderation_status","=","STATUS_PENDING",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L519-L521"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"PendingMessage.set_accepted","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set the message as accepted.","docstring_summary":"Set the message as accepted.","docstring_tokens":["Set","the","message","as","accepted","."],"function":"def set_accepted(self):\n \"\"\"Set the message as accepted.\"\"\"\n self.moderation_status = STATUS_ACCEPTED","function_tokens":["def","set_accepted","(","self",")",":","self",".","moderation_status","=","STATUS_ACCEPTED"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L536-L538"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/models.py","language":"python","identifier":"PendingMessage.set_rejected","parameters":"(self)","argument_list":"","return_statement":"","docstring":"Set the message as rejected.","docstring_summary":"Set the message as rejected.","docstring_tokens":["Set","the","message","as","rejected","."],"function":"def set_rejected(self):\n \"\"\"Set the message as rejected.\"\"\"\n self.moderation_status = STATUS_REJECTED","function_tokens":["def","set_rejected","(","self",")",":","self",".","moderation_status","=","STATUS_REJECTED"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/models.py#L540-L542"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/templatetags\/postman_tags.py","language":"python","identifier":"sub","parameters":"(value, arg)","argument_list":"","return_statement":"","docstring":"Subtract the arg from the value.","docstring_summary":"Subtract the arg from the value.","docstring_tokens":["Subtract","the","arg","from","the","value","."],"function":"def sub(value, arg):\n \"\"\"Subtract the arg from the value.\"\"\"\n try:\n return int(value) - int(arg)\n except (ValueError, TypeError):\n return value","function_tokens":["def","sub","(","value",",","arg",")",":","try",":","return","int","(","value",")","-","int","(","arg",")","except","(","ValueError",",","TypeError",")",":","return","value"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/templatetags\/postman_tags.py#L28-L33"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/templatetags\/postman_tags.py","language":"python","identifier":"or_me","parameters":"(value, arg)","argument_list":"","return_statement":"return _('') if value == arg else value","docstring":"Replace the value by a fixed pattern, if it equals the argument.\n\n Typical usage: message.obfuscated_sender|or_me:user","docstring_summary":"Replace the value by a fixed pattern, if it equals the argument.","docstring_tokens":["Replace","the","value","by","a","fixed","pattern","if","it","equals","the","argument","."],"function":"def or_me(value, arg):\n \"\"\"\n Replace the value by a fixed pattern, if it equals the argument.\n\n Typical usage: message.obfuscated_sender|or_me:user\n\n \"\"\"\n user_model = get_user_model()\n if not isinstance(value, six.string_types):\n value = (get_user_representation if isinstance(value, user_model) else force_text)(value)\n if not isinstance(arg, six.string_types):\n arg = (get_user_representation if isinstance(arg, user_model) else force_text)(arg)\n return _('') if value == arg else value","function_tokens":["def","or_me","(","value",",","arg",")",":","user_model","=","get_user_model","(",")","if","not","isinstance","(","value",",","six",".","string_types",")",":","value","=","(","get_user_representation","if","isinstance","(","value",",","user_model",")","else","force_text",")","(","value",")","if","not","isinstance","(","arg",",","six",".","string_types",")",":","arg","=","(","get_user_representation","if","isinstance","(","arg",",","user_model",")","else","force_text",")","(","arg",")","return","_","(","''",")","if","value","==","arg","else","value"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/templatetags\/postman_tags.py#L38-L50"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/templatetags\/postman_tags.py","language":"python","identifier":"compact_date","parameters":"(value, arg)","argument_list":"","return_statement":"return date(value, bits[0] if value.date() == today else bits[1] if value.year == today.year else bits[2])","docstring":"Output a date as short as possible.\n\n The argument must provide 3 patterns: for same day, for same year, otherwise\n Typical usage: |compact_date:_(\"G:i,j b,j\/n\/y\")","docstring_summary":"Output a date as short as possible.","docstring_tokens":["Output","a","date","as","short","as","possible","."],"function":"def compact_date(value, arg):\n \"\"\"\n Output a date as short as possible.\n\n The argument must provide 3 patterns: for same day, for same year, otherwise\n Typical usage: |compact_date:_(\"G:i,j b,j\/n\/y\")\n\n \"\"\"\n bits = arg.split(',')\n if len(bits) < 3:\n return value # Invalid arg.\n today = datetime.date.today()\n return date(value, bits[0] if value.date() == today else bits[1] if value.year == today.year else bits[2])","function_tokens":["def","compact_date","(","value",",","arg",")",":","bits","=","arg",".","split","(","','",")","if","len","(","bits",")","<","3",":","return","value","# Invalid arg.","today","=","datetime",".","date",".","today","(",")","return","date","(","value",",","bits","[","0","]","if","value",".","date","(",")","==","today","else","bits","[","1","]","if","value",".","year","==","today",".","year","else","bits","[","2","]",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/templatetags\/postman_tags.py#L54-L66"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/templatetags\/postman_tags.py","language":"python","identifier":"postman_order_by","parameters":"(parser, token)","argument_list":"","return_statement":"return OrderByNode(field_code)","docstring":"Compose a query string to ask for a specific ordering in messages list.\n\n The unique argument must be one of the keywords of a set defined in the model.\n Example::\n\n ...<\/a>","docstring_summary":"Compose a query string to ask for a specific ordering in messages list.","docstring_tokens":["Compose","a","query","string","to","ask","for","a","specific","ordering","in","messages","list","."],"function":"def postman_order_by(parser, token):\n \"\"\"\n Compose a query string to ask for a specific ordering in messages list.\n\n The unique argument must be one of the keywords of a set defined in the model.\n Example::\n\n ...<\/a>\n \"\"\"\n try:\n tag_name, field_name = token.split_contents()\n field_code = ORDER_BY_MAPPER[field_name.lower()]\n except ValueError:\n raise TemplateSyntaxError(\"'{0}' tag requires a single argument\".format(token.contents.split()[0]))\n except KeyError:\n raise TemplateSyntaxError(\n \"'{0}' is not a valid argument to '{1}' tag.\"\n \" Must be one of: {2}\".format(field_name, tag_name, ORDER_BY_MAPPER.keys()))\n return OrderByNode(field_code)","function_tokens":["def","postman_order_by","(","parser",",","token",")",":","try",":","tag_name",",","field_name","=","token",".","split_contents","(",")","field_code","=","ORDER_BY_MAPPER","[","field_name",".","lower","(",")","]","except","ValueError",":","raise","TemplateSyntaxError","(","\"'{0}' tag requires a single argument\"",".","format","(","token",".","contents",".","split","(",")","[","0","]",")",")","except","KeyError",":","raise","TemplateSyntaxError","(","\"'{0}' is not a valid argument to '{1}' tag.\"","\" Must be one of: {2}\"",".","format","(","field_name",",","tag_name",",","ORDER_BY_MAPPER",".","keys","(",")",")",")","return","OrderByNode","(","field_code",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/templatetags\/postman_tags.py#L123-L141"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/templatetags\/postman_tags.py","language":"python","identifier":"postman_unread","parameters":"(parser, token)","argument_list":"","return_statement":"","docstring":"Give the number of unread messages for a user,\n or nothing (an empty string) for an anonymous user.\n\n Storing the count in a variable for further processing is advised, such as::\n\n {% postman_unread as unread_count %}\n ...\n {% if unread_count %}\n You have {{ unread_count }}<\/strong> unread messages.\n {% endif %}","docstring_summary":"Give the number of unread messages for a user,\n or nothing (an empty string) for an anonymous user.","docstring_tokens":["Give","the","number","of","unread","messages","for","a","user","or","nothing","(","an","empty","string",")","for","an","anonymous","user","."],"function":"def postman_unread(parser, token):\n \"\"\"\n Give the number of unread messages for a user,\n or nothing (an empty string) for an anonymous user.\n\n Storing the count in a variable for further processing is advised, such as::\n\n {% postman_unread as unread_count %}\n ...\n {% if unread_count %}\n You have {{ unread_count }}<\/strong> unread messages.\n {% endif %}\n \"\"\"\n bits = token.split_contents()\n if len(bits) > 1:\n if len(bits) != 3:\n raise TemplateSyntaxError(\"'{0}' tag takes no argument or exactly two arguments\".format(bits[0]))\n if bits[1] != 'as':\n raise TemplateSyntaxError(\"First argument to '{0}' tag must be 'as'\".format(bits[0]))\n return InboxCountNode(bits[2])\n else:\n return InboxCountNode()","function_tokens":["def","postman_unread","(","parser",",","token",")",":","bits","=","token",".","split_contents","(",")","if","len","(","bits",")",">","1",":","if","len","(","bits",")","!=","3",":","raise","TemplateSyntaxError","(","\"'{0}' tag takes no argument or exactly two arguments\"",".","format","(","bits","[","0","]",")",")","if","bits","[","1","]","!=","'as'",":","raise","TemplateSyntaxError","(","\"First argument to '{0}' tag must be 'as'\"",".","format","(","bits","[","0","]",")",")","return","InboxCountNode","(","bits","[","2","]",")","else",":","return","InboxCountNode","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/templatetags\/postman_tags.py#L145-L166"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/templatetags\/postman_tags.py","language":"python","identifier":"OrderByNode.render","parameters":"(self, context)","argument_list":"","return_statement":"return '?'+gets.urlencode() if gets else ''","docstring":"Return a formatted GET query string, as \"?order_key=order_val\".\n\n Preserves existing GET's keys, if any, such as a page number.\n For that, the view has to provide request.GET in a 'gets' entry of the context.","docstring_summary":"Return a formatted GET query string, as \"?order_key=order_val\".","docstring_tokens":["Return","a","formatted","GET","query","string","as","?order_key","=","order_val","."],"function":"def render(self, context):\n \"\"\"\n Return a formatted GET query string, as \"?order_key=order_val\".\n\n Preserves existing GET's keys, if any, such as a page number.\n For that, the view has to provide request.GET in a 'gets' entry of the context.\n\n \"\"\"\n if 'gets' in context:\n gets = context['gets'].copy()\n else:\n gets = QueryDict('').copy()\n if ORDER_BY_KEY in gets:\n code = gets.pop(ORDER_BY_KEY)[0]\n else:\n code = None\n if self.code:\n gets[ORDER_BY_KEY] = self.code if self.code != code else self.code.upper()\n return '?'+gets.urlencode() if gets else ''","function_tokens":["def","render","(","self",",","context",")",":","if","'gets'","in","context",":","gets","=","context","[","'gets'","]",".","copy","(",")","else",":","gets","=","QueryDict","(","''",")",".","copy","(",")","if","ORDER_BY_KEY","in","gets",":","code","=","gets",".","pop","(","ORDER_BY_KEY",")","[","0","]","else",":","code","=","None","if","self",".","code",":","gets","[","ORDER_BY_KEY","]","=","self",".","code","if","self",".","code","!=","code","else","self",".","code",".","upper","(",")","return","'?'","+","gets",".","urlencode","(",")","if","gets","else","''"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/templatetags\/postman_tags.py#L77-L95"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"postman\/templatetags\/postman_tags.py","language":"python","identifier":"InboxCountNode.render","parameters":"(self, context)","argument_list":"","return_statement":"return count","docstring":"Return the count of unread messages for the user found in context,\n (may be 0) or an empty string.","docstring_summary":"Return the count of unread messages for the user found in context,\n (may be 0) or an empty string.","docstring_tokens":["Return","the","count","of","unread","messages","for","the","user","found","in","context","(","may","be","0",")","or","an","empty","string","."],"function":"def render(self, context):\n \"\"\"\n Return the count of unread messages for the user found in context,\n (may be 0) or an empty string.\n \"\"\"\n try:\n user = context['user']\n if user.is_anonymous():\n count = ''\n else:\n count = Message.objects.inbox_unread_count(user)\n except (KeyError, AttributeError):\n count = ''\n if self.asvar:\n context[self.asvar] = count\n return ''\n return count","function_tokens":["def","render","(","self",",","context",")",":","try",":","user","=","context","[","'user'","]","if","user",".","is_anonymous","(",")",":","count","=","''","else",":","count","=","Message",".","objects",".","inbox_unread_count","(","user",")","except","(","KeyError",",","AttributeError",")",":","count","=","''","if","self",".","asvar",":","context","[","self",".","asvar","]","=","count","return","''","return","count"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/postman\/templatetags\/postman_tags.py#L103-L119"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"topics\/views.py","language":"python","identifier":"delete_topic","parameters":"(request)","argument_list":"","return_statement":"","docstring":"Delete topic from discussion list via AJAX request.","docstring_summary":"Delete topic from discussion list via AJAX request.","docstring_tokens":["Delete","topic","from","discussion","list","via","AJAX","request","."],"function":"def delete_topic(request):\n \"\"\" Delete topic from discussion list via AJAX request. \"\"\"\n pk = request.POST.get('object_pk')\n\n if not pk:\n return HttpResponse(json.dumps({\n 'success': False,\n 'message': _(\"No entry ID provided\"),\n 'level': 'danger',\n }))\n\n try:\n topic = Discussion.objects.get(pk=pk)\n except Discussion.DoesNotExist as ex:\n return HttpResponse(json.dumps({\n 'success': False,\n 'message': str(ex),\n 'level': 'danger',\n }))\n\n moderator = is_moderator(request.user, topic.location)\n if request.user != topic.creator and not moderator:\n return HttpResponse(json.dumps({\n 'success': False,\n 'message': _(\"Permission required!\"),\n 'level': 'danger',\n }))\n\n try:\n with transaction.commit_on_success(): topic.delete()\n return HttpResponse(json.dumps({\n 'success': True,\n 'message': _(\"Entry deleted\"),\n 'level': 'success',\n }))\n except Exception as ex:\n return HttpResponse(json.dumps({\n 'success': False,\n 'message': str(ex),\n 'level': 'danger',\n }))","function_tokens":["def","delete_topic","(","request",")",":","pk","=","request",".","POST",".","get","(","'object_pk'",")","if","not","pk",":","return","HttpResponse","(","json",".","dumps","(","{","'success'",":","False",",","'message'",":","_","(","\"No entry ID provided\"",")",",","'level'",":","'danger'",",","}",")",")","try",":","topic","=","Discussion",".","objects",".","get","(","pk","=","pk",")","except","Discussion",".","DoesNotExist","as","ex",":","return","HttpResponse","(","json",".","dumps","(","{","'success'",":","False",",","'message'",":","str","(","ex",")",",","'level'",":","'danger'",",","}",")",")","moderator","=","is_moderator","(","request",".","user",",","topic",".","location",")","if","request",".","user","!=","topic",".","creator","and","not","moderator",":","return","HttpResponse","(","json",".","dumps","(","{","'success'",":","False",",","'message'",":","_","(","\"Permission required!\"",")",",","'level'",":","'danger'",",","}",")",")","try",":","with","transaction",".","commit_on_success","(",")",":","topic",".","delete","(",")","return","HttpResponse","(","json",".","dumps","(","{","'success'",":","True",",","'message'",":","_","(","\"Entry deleted\"",")",",","'level'",":","'success'",",","}",")",")","except","Exception","as","ex",":","return","HttpResponse","(","json",".","dumps","(","{","'success'",":","False",",","'message'",":","str","(","ex",")",",","'level'",":","'danger'",",","}",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/topics\/views.py#L162-L202"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"topics\/views.py","language":"python","identifier":"reply","parameters":"(request, slug)","argument_list":"","return_statement":"return HttpResponseRedirect(request.META['HTTP_REFERER'] + '#reply-' + str(entry.pk))","docstring":"Create forum reply.","docstring_summary":"Create forum reply.","docstring_tokens":["Create","forum","reply","."],"function":"def reply(request, slug):\n \"\"\" Create forum reply. \"\"\"\n if request.method == 'POST' and request.POST:\n post = request.POST\n topic = Discussion.objects.get(slug=post['discussion'])\n if not topic.status:\n return HttpResponse(_('This discussion is closed.'))\n entry = Entry(\n content = post['content'],\n creator = request.user,\n discussion = topic,\n )\n \n entry.save()\n action.send(\n request.user,\n action_object=entry,\n target = topic,\n verb= _('posted')\n )\n \n return HttpResponseRedirect(request.META['HTTP_REFERER'] + '#reply-' + str(entry.pk))","function_tokens":["def","reply","(","request",",","slug",")",":","if","request",".","method","==","'POST'","and","request",".","POST",":","post","=","request",".","POST","topic","=","Discussion",".","objects",".","get","(","slug","=","post","[","'discussion'","]",")","if","not","topic",".","status",":","return","HttpResponse","(","_","(","'This discussion is closed.'",")",")","entry","=","Entry","(","content","=","post","[","'content'","]",",","creator","=","request",".","user",",","discussion","=","topic",",",")","entry",".","save","(",")","action",".","send","(","request",".","user",",","action_object","=","entry",",","target","=","topic",",","verb","=","_","(","'posted'",")",")","return","HttpResponseRedirect","(","request",".","META","[","'HTTP_REFERER'","]","+","'#reply-'","+","str","(","entry",".","pk",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/topics\/views.py#L205-L226"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"topics\/views.py","language":"python","identifier":"vote","parameters":"(request, pk)","argument_list":"","return_statement":"return HttpResponse(json.dumps(context))","docstring":"Vote for reply.","docstring_summary":"Vote for reply.","docstring_tokens":["Vote","for","reply","."],"function":"def vote(request, pk):\n \"\"\" Vote for reply. \"\"\"\n entry = Entry.objects.get(pk=pk)\n vote = False if request.POST.get('vote') == 'false' else True\n user = request.user\n check = EntryVote.objects.filter(entry=entry).filter(user=user)\n if not len(check):\n entry_vote = EntryVote.objects.create(\n entry = entry,\n user = user,\n vote = vote)\n try:\n entry_vote.save()\n context = {\n 'success': True,\n 'message': _(\"Vote saved\"),\n 'votes' : Entry.objects.get(pk=pk).calculate_votes(),\n 'level' : \"success\",\n }\n except Exception as ex:\n context = {\n 'success': False,\n 'message': str(ex),\n 'level' : \"danger\",\n }\n else:\n context = {\n 'success': False,\n 'message': _(\"You already voted on this entry.\"),\n 'level' : \"warning\",\n }\n return HttpResponse(json.dumps(context))","function_tokens":["def","vote","(","request",",","pk",")",":","entry","=","Entry",".","objects",".","get","(","pk","=","pk",")","vote","=","False","if","request",".","POST",".","get","(","'vote'",")","==","'false'","else","True","user","=","request",".","user","check","=","EntryVote",".","objects",".","filter","(","entry","=","entry",")",".","filter","(","user","=","user",")","if","not","len","(","check",")",":","entry_vote","=","EntryVote",".","objects",".","create","(","entry","=","entry",",","user","=","user",",","vote","=","vote",")","try",":","entry_vote",".","save","(",")","context","=","{","'success'",":","True",",","'message'",":","_","(","\"Vote saved\"",")",",","'votes'",":","Entry",".","objects",".","get","(","pk","=","pk",")",".","calculate_votes","(",")",",","'level'",":","\"success\"",",","}","except","Exception","as","ex",":","context","=","{","'success'",":","False",",","'message'",":","str","(","ex",")",",","'level'",":","\"danger\"",",","}","else",":","context","=","{","'success'",":","False",",","'message'",":","_","(","\"You already voted on this entry.\"",")",",","'level'",":","\"warning\"",",","}","return","HttpResponse","(","json",".","dumps","(","context",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/topics\/views.py#L233-L264"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"topics\/models.py","language":"python","identifier":"response_notification","parameters":"(sender, instance, created, **kwargs)","argument_list":"","return_statement":"","docstring":"Notify discussion creator about every new answer.","docstring_summary":"Notify discussion creator about every new answer.","docstring_tokens":["Notify","discussion","creator","about","every","new","answer","."],"function":"def response_notification(sender, instance, created, **kwargs):\n \"\"\" Notify discussion creator about every new answer. \"\"\"\n if not created or instance.creator == instance.discussion.creator:\n return True\n notify(instance.creator, instance.discussion.creator,\n key=\"answer\",\n verb=_(u\"answered for your discussion\"),\n action_object=instance,\n action_target=instance.discussion\n )","function_tokens":["def","response_notification","(","sender",",","instance",",","created",",","*","*","kwargs",")",":","if","not","created","or","instance",".","creator","==","instance",".","discussion",".","creator",":","return","True","notify","(","instance",".","creator",",","instance",".","discussion",".","creator",",","key","=","\"answer\"",",","verb","=","_","(","u\"answered for your discussion\"",")",",","action_object","=","instance",",","action_target","=","instance",".","discussion",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/topics\/models.py#L157-L166"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"topics\/models.py","language":"python","identifier":"vote_notification","parameters":"(sender, instance, created, **kwargs)","argument_list":"","return_statement":"","docstring":"Notify entry author about votes for his\/her entry.","docstring_summary":"Notify entry author about votes for his\/her entry.","docstring_tokens":["Notify","entry","author","about","votes","for","his","\/","her","entry","."],"function":"def vote_notification(sender, instance, created, **kwargs):\n \"\"\" Notify entry author about votes for his\/her entry. \"\"\"\n if not created:\n return True\n suff = \"up\" if instance.vote else \"down\"\n notify(instance.user, instance.entry.creator,\n key=\"vote\",\n verb=_(u\"voted for %s your entry\" % suff),\n action_object=instance,\n action_target=instance.entry\n )","function_tokens":["def","vote_notification","(","sender",",","instance",",","created",",","*","*","kwargs",")",":","if","not","created",":","return","True","suff","=","\"up\"","if","instance",".","vote","else","\"down\"","notify","(","instance",".","user",",","instance",".","entry",".","creator",",","key","=","\"vote\"",",","verb","=","_","(","u\"voted for %s your entry\"","%","suff",")",",","action_object","=","instance",",","action_target","=","instance",".","entry",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/topics\/models.py#L170-L180"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/actions.py","language":"python","identifier":"task_action","parameters":"(user, task, verb)","argument_list":"","return_statement":"","docstring":"A general action that contains tasks. Here we form whole send orders\n of a given action. A django.contrib.auth.models.User, projects.models.Task\n and verb instance needs to be passed to the function.","docstring_summary":"A general action that contains tasks. Here we form whole send orders\n of a given action. A django.contrib.auth.models.User, projects.models.Task\n and verb instance needs to be passed to the function.","docstring_tokens":["A","general","action","that","contains","tasks",".","Here","we","form","whole","send","orders","of","a","given","action",".","A","django",".","contrib",".","auth",".","models",".","User","projects",".","models",".","Task","and","verb","instance","needs","to","be","passed","to","the","function","."],"function":"def task_action(user, task, verb):\n \"\"\"\n A general action that contains tasks. Here we form whole send orders\n of a given action. A django.contrib.auth.models.User, projects.models.Task\n and verb instance needs to be passed to the function.\n \"\"\"\n action.send(user, verb=verb, action_object=task, target=task.group.project)","function_tokens":["def","task_action","(","user",",","task",",","verb",")",":","action",".","send","(","user",",","verb","=","verb",",","action_object","=","task",",","target","=","task",".","group",".","project",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/actions.py#L9-L15"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/actions.py","language":"python","identifier":"finished_task","parameters":"(user, task)","argument_list":"","return_statement":"","docstring":"The user has finished the task.","docstring_summary":"The user has finished the task.","docstring_tokens":["The","user","has","finished","the","task","."],"function":"def finished_task(user, task):\n \"\"\"\n The user has finished the task.\n \"\"\"\n task_action(user, task, _(u\"finished task\"))\n for participant in task.participants.all():\n notify(user, participant,\n verb=_(u\"finished task\"),\n key=\"project\",\n action_tartget=task\n )","function_tokens":["def","finished_task","(","user",",","task",")",":","task_action","(","user",",","task",",","_","(","u\"finished task\"",")",")","for","participant","in","task",".","participants",".","all","(",")",":","notify","(","user",",","participant",",","verb","=","_","(","u\"finished task\"",")",",","key","=","\"project\"",",","action_tartget","=","task",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/actions.py#L18-L28"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/actions.py","language":"python","identifier":"joined_to_task","parameters":"(user, task)","argument_list":"","return_statement":"","docstring":"The user has joined the task.","docstring_summary":"The user has joined the task.","docstring_tokens":["The","user","has","joined","the","task","."],"function":"def joined_to_task(user, task):\n \"\"\"\n The user has joined the task.\n \"\"\"\n if user != task.creator:\n task_action(user, task, _(u\"joined to task\"))\n notify(user, task.creator,\n verb=_(u\"joined to your task\"),\n key=\"follower\",\n action_target=task\n )","function_tokens":["def","joined_to_task","(","user",",","task",")",":","if","user","!=","task",".","creator",":","task_action","(","user",",","task",",","_","(","u\"joined to task\"",")",")","notify","(","user",",","task",".","creator",",","verb","=","_","(","u\"joined to your task\"",")",",","key","=","\"follower\"",",","action_target","=","task",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/actions.py#L31-L41"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/actions.py","language":"python","identifier":"joined_to_project","parameters":"(user, project)","argument_list":"","return_statement":"","docstring":"To this function we pass django user instance and project.","docstring_summary":"To this function we pass django user instance and project.","docstring_tokens":["To","this","function","we","pass","django","user","instance","and","project","."],"function":"def joined_to_project(user, project):\n \"\"\"\n To this function we pass django user instance and project.\n \"\"\"\n if user != project.creator:\n action.send(user, verb=_(u\"joined to project\"), target=project)\n notify(user, project.creator,\n verb=_(u\"joined to your project\"),\n key=\"follower\",\n action_target=project\n )","function_tokens":["def","joined_to_project","(","user",",","project",")",":","if","user","!=","project",".","creator",":","action",".","send","(","user",",","verb","=","_","(","u\"joined to project\"",")",",","target","=","project",")","notify","(","user",",","project",".","creator",",","verb","=","_","(","u\"joined to your project\"",")",",","key","=","\"follower\"",",","action_target","=","project",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/actions.py#L44-L54"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/actions.py","language":"python","identifier":"leaved_project","parameters":"(user, project)","argument_list":"","return_statement":"","docstring":"Same as above but here we inform other poeple that the user has left the project.","docstring_summary":"Same as above but here we inform other poeple that the user has left the project.","docstring_tokens":["Same","as","above","but","here","we","inform","other","poeple","that","the","user","has","left","the","project","."],"function":"def leaved_project(user, project):\n \"\"\"\n Same as above but here we inform other poeple that the user has left the project.\n \"\"\"\n action.send(user, verb=_(u\"left project\"), target=project)","function_tokens":["def","leaved_project","(","user",",","project",")",":","action",".","send","(","user",",","verb","=","_","(","u\"left project\"",")",",","target","=","project",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/actions.py#L57-L61"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/signals.py","language":"python","identifier":"project_created_action","parameters":"(sender, instance, created, **kwargs)","argument_list":"","return_statement":"","docstring":"The creation of a project should be visible to the followers of the location.","docstring_summary":"The creation of a project should be visible to the followers of the location.","docstring_tokens":["The","creation","of","a","project","should","be","visible","to","the","followers","of","the","location","."],"function":"def project_created_action(sender, instance, created, **kwargs):\n \"\"\" The creation of a project should be visible to the followers of the location. \"\"\"\n if created:\n action.send(instance.creator, verb=_(u\"created\"),\n action_object=instance, target=instance.location)","function_tokens":["def","project_created_action","(","sender",",","instance",",","created",",","*","*","kwargs",")",":","if","created",":","action",".","send","(","instance",".","creator",",","verb","=","_","(","u\"created\"",")",",","action_object","=","instance",",","target","=","instance",".","location",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/signals.py#L7-L11"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/signals.py","language":"python","identifier":"project_task_action","parameters":"(sender, instance, created, **kwargs)","argument_list":"","return_statement":"","docstring":"The creation of groups and tasks should be visible only for participants of the \n given project. Here we also manage topic creation and answers on the forum.","docstring_summary":"The creation of groups and tasks should be visible only for participants of the \n given project. Here we also manage topic creation and answers on the forum.","docstring_tokens":["The","creation","of","groups","and","tasks","should","be","visible","only","for","participants","of","the","given","project",".","Here","we","also","manage","topic","creation","and","answers","on","the","forum","."],"function":"def project_task_action(sender, instance, created, **kwargs):\n \"\"\"\n The creation of groups and tasks should be visible only for participants of the \n given project. Here we also manage topic creation and answers on the forum. \n \"\"\"\n if created:\n if hasattr(instance, 'project'):\n # A group of tasks or a discussion was created\n action_target = instance.project\n elif hasattr(instance, 'group'):\n # A task was created\n action_target = instance.group.project\n else:\n # A reply to a discussion was created\n action_target = instance.topic.project\n action.send(instance.creator, verb=_(u\"created\"),\n action_object=instance, target=action_target)","function_tokens":["def","project_task_action","(","sender",",","instance",",","created",",","*","*","kwargs",")",":","if","created",":","if","hasattr","(","instance",",","'project'",")",":","# A group of tasks or a discussion was created","action_target","=","instance",".","project","elif","hasattr","(","instance",",","'group'",")",":","# A task was created","action_target","=","instance",".","group",".","project","else",":","# A reply to a discussion was created","action_target","=","instance",".","topic",".","project","action",".","send","(","instance",".","creator",",","verb","=","_","(","u\"created\"",")",",","action_object","=","instance",",","target","=","action_target",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/signals.py#L14-L30"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/permissions.py","language":"python","identifier":"check_access","parameters":"(obj, user)","argument_list":"","return_statement":"return access","docstring":"This function checkes whether the user is allowed to delete or modify the\n object passed in as an argument. Such an object must be a model instance\n of this application. i.e. project, group of tasks or a task. Returns\n True\/False.","docstring_summary":"This function checkes whether the user is allowed to delete or modify the\n object passed in as an argument. Such an object must be a model instance\n of this application. i.e. project, group of tasks or a task. Returns\n True\/False.","docstring_tokens":["This","function","checkes","whether","the","user","is","allowed","to","delete","or","modify","the","object","passed","in","as","an","argument",".","Such","an","object","must","be","a","model","instance","of","this","application",".","i",".","e",".","project","group","of","tasks","or","a","task",".","Returns","True","\/","False","."],"function":"def check_access(obj, user):\n \"\"\"\n This function checkes whether the user is allowed to delete or modify the\n object passed in as an argument. Such an object must be a model instance\n of this application. i.e. project, group of tasks or a task. Returns\n True\/False.\n \"\"\"\n if user.is_anonymous():\n return False\n # The \"creator\" can always delete his\/her \"work\"\n access = user == obj.creator\n # The Superadmin is omnipotent\n if not access and user.is_superuser:\n access = True\n # We check the mods rights\n if not access:\n location = None\n if hasattr(obj, 'location'):\n # Project\n location = obj.location\n elif hasattr(obj, 'project'):\n # A Group of taks or a topic in the forum\n location = obj.project.location\n elif hasattr(obj, 'group'):\n # Task\n location = obj.group.project.location\n else:\n # Entry in the forum\n location = obj.discussion.project.location\n if is_moderator(user, location):\n access = True\n return access","function_tokens":["def","check_access","(","obj",",","user",")",":","if","user",".","is_anonymous","(",")",":","return","False","# The \"creator\" can always delete his\/her \"work\"","access","=","user","==","obj",".","creator","# The Superadmin is omnipotent","if","not","access","and","user",".","is_superuser",":","access","=","True","# We check the mods rights","if","not","access",":","location","=","None","if","hasattr","(","obj",",","'location'",")",":","# Project","location","=","obj",".","location","elif","hasattr","(","obj",",","'project'",")",":","# A Group of taks or a topic in the forum","location","=","obj",".","project",".","location","elif","hasattr","(","obj",",","'group'",")",":","# Task","location","=","obj",".","group",".","project",".","location","else",":","# Entry in the forum","location","=","obj",".","discussion",".","project",".","location","if","is_moderator","(","user",",","location",")",":","access","=","True","return","access"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/permissions.py#L4-L35"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/models.py","language":"python","identifier":"get_upload_path","parameters":"(instance, filename)","argument_list":"","return_statement":"return 'img\/projects\/' + uuid4().hex + os.path.splitext(filename)[1]","docstring":"I set a path and a random name for the background image of the project.","docstring_summary":"I set a path and a random name for the background image of the project.","docstring_tokens":["I","set","a","path","and","a","random","name","for","the","background","image","of","the","project","."],"function":"def get_upload_path(instance, filename):\n \"\"\" I set a path and a random name for the background image of the project. \"\"\"\n return 'img\/projects\/' + uuid4().hex + os.path.splitext(filename)[1]","function_tokens":["def","get_upload_path","(","instance",",","filename",")",":","return","'img\/projects\/'","+","uuid4","(",")",".","hex","+","os",".","path",".","splitext","(","filename",")","[","1","]"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/models.py#L30-L32"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/models.py","language":"python","identifier":"get_attachment_path","parameters":"(instance, filename)","argument_list":"","return_statement":"return 'attachments\/' + uuid4().hex + os.path.splitext(filename)[1]","docstring":"Same as above, but for attachment files.","docstring_summary":"Same as above, but for attachment files.","docstring_tokens":["Same","as","above","but","for","attachment","files","."],"function":"def get_attachment_path(instance, filename):\n \"\"\" Same as above, but for attachment files.\n \"\"\"\n return 'attachments\/' + uuid4().hex + os.path.splitext(filename)[1]","function_tokens":["def","get_attachment_path","(","instance",",","filename",")",":","return","'attachments\/'","+","uuid4","(",")",".","hex","+","os",".","path",".","splitext","(","filename",")","[","1","]"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/models.py#L35-L38"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/models.py","language":"python","identifier":"cleanup","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"Make sure that etherpad groups will be deleted along with project.","docstring_summary":"Make sure that etherpad groups will be deleted along with project.","docstring_tokens":["Make","sure","that","etherpad","groups","will","be","deleted","along","with","project","."],"function":"def cleanup(sender, instance, **kwargs):\n \"\"\" Make sure that etherpad groups will be deleted along with project. \"\"\"\n instance.destroy()","function_tokens":["def","cleanup","(","sender",",","instance",",","*","*","kwargs",")",":","instance",".","destroy","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/models.py#L278-L280"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/models.py","language":"python","identifier":"cleanup_attachment","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"Make sure that files will be deleted along with attachments.","docstring_summary":"Make sure that files will be deleted along with attachments.","docstring_tokens":["Make","sure","that","files","will","be","deleted","along","with","attachments","."],"function":"def cleanup_attachment(sender, instance, **kwargs):\n \"\"\" Make sure that files will be deleted along with attachments.\n \"\"\"\n instance.attachment.delete(save=False)","function_tokens":["def","cleanup_attachment","(","sender",",","instance",",","*","*","kwargs",")",":","instance",".","attachment",".","delete","(","save","=","False",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/models.py#L313-L316"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/views\/attachments.py","language":"python","identifier":"get_attachment","parameters":"(request, pk)","argument_list":"","return_statement":"return response","docstring":"We assume that everyone may download file.","docstring_summary":"We assume that everyone may download file.","docstring_tokens":["We","assume","that","everyone","may","download","file","."],"function":"def get_attachment(request, pk):\n \"\"\" We assume that everyone may download file.\n \"\"\"\n attachment = get_object_or_404(Attachment, pk=pk)\n types_to_open = ('application\/pdf', 'application\/msword', )\n if attachment.mime_type in types_to_open:\n with open(attachment.attachment.path) as pdf:\n response = HttpResponse(pdf.read(), content_type=attachment.mime_type)\n response['Content-Disposition'] = 'inline;filename={}'.format(\n attachment.attachment.name.split('\/')[-1])\n return response\n pdf.closed\n else:\n response = HttpResponse(attachment.attachment.open(),\n content_type=attachment.mime_type)\n response['Content-Disposition'] = 'attachment; filename=%s' % attachment\n return response","function_tokens":["def","get_attachment","(","request",",","pk",")",":","attachment","=","get_object_or_404","(","Attachment",",","pk","=","pk",")","types_to_open","=","(","'application\/pdf'",",","'application\/msword'",",",")","if","attachment",".","mime_type","in","types_to_open",":","with","open","(","attachment",".","attachment",".","path",")","as","pdf",":","response","=","HttpResponse","(","pdf",".","read","(",")",",","content_type","=","attachment",".","mime_type",")","response","[","'Content-Disposition'","]","=","'inline;filename={}'",".","format","(","attachment",".","attachment",".","name",".","split","(","'\/'",")","[","-","1","]",")","return","response","pdf",".","closed","else",":","response","=","HttpResponse","(","attachment",".","attachment",".","open","(",")",",","content_type","=","attachment",".","mime_type",")","response","[","'Content-Disposition'","]","=","'attachment; filename=%s'","%","attachment","return","response"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/views\/attachments.py#L20-L36"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/views\/base.py","language":"python","identifier":"set_element_order","parameters":"(request, content_type, object_id, direction)","argument_list":"","return_statement":"return redirect(redirect_url)","docstring":"We set an order for groups or tasks. The ID type of the content,\n the ID of the object and the direction ('UP' or 'DOWN') need to\n be passed to the function.","docstring_summary":"We set an order for groups or tasks. The ID type of the content,\n the ID of the object and the direction ('UP' or 'DOWN') need to\n be passed to the function.","docstring_tokens":["We","set","an","order","for","groups","or","tasks",".","The","ID","type","of","the","content","the","ID","of","the","object","and","the","direction","(","UP","or","DOWN",")","need","to","be","passed","to","the","function","."],"function":"def set_element_order(request, content_type, object_id, direction):\n \"\"\" We set an order for groups or tasks. The ID type of the content,\n the ID of the object and the direction ('UP' or 'DOWN') need to\n be passed to the function.\n \"\"\"\n model = ContentType.objects.get(pk=content_type).model_class()\n obj = model.objects.get(pk=object_id)\n if direction == 'UP':\n obj.up()\n else:\n obj.down()\n if hasattr(obj, 'get_absolute_url'):\n # Task\n redirect_url = obj.get_absolute_url()\n else:\n # Group of tasks\n redirect_url = obj.project.get_absolute_url()\n return redirect(redirect_url)","function_tokens":["def","set_element_order","(","request",",","content_type",",","object_id",",","direction",")",":","model","=","ContentType",".","objects",".","get","(","pk","=","content_type",")",".","model_class","(",")","obj","=","model",".","objects",".","get","(","pk","=","object_id",")","if","direction","==","'UP'",":","obj",".","up","(",")","else",":","obj",".","down","(",")","if","hasattr","(","obj",",","'get_absolute_url'",")",":","# Task","redirect_url","=","obj",".","get_absolute_url","(",")","else",":","# Group of tasks","redirect_url","=","obj",".","project",".","get_absolute_url","(",")","return","redirect","(","redirect_url",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/views\/base.py#L41-L58"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/views\/base.py","language":"python","identifier":"toggle_task_state","parameters":"(request, pk)","argument_list":"","return_statement":"return redirect(task.get_absolute_url())","docstring":"We change the status of the task to finished\/unfinished","docstring_summary":"We change the status of the task to finished\/unfinished","docstring_tokens":["We","change","the","status","of","the","task","to","finished","\/","unfinished"],"function":"def toggle_task_state(request, pk):\n \"\"\" We change the status of the task to finished\/unfinished \"\"\"\n task = get_object_or_404(Task, pk=pk)\n if task.is_done:\n task.is_done = False\n message = _(u\"Task marked as undone\")\n else:\n task.is_done = True\n message = _(u\"Task marked as finished\")\n task.save()\n finished_task(request.user, task)\n if request.is_ajax():\n context = json.dumps(\n {'success': True,\n 'is_done': task.is_done,\n 'message': message, })\n return HttpResponse(context, content_type=\"application\/json\")\n return redirect(task.get_absolute_url())","function_tokens":["def","toggle_task_state","(","request",",","pk",")",":","task","=","get_object_or_404","(","Task",",","pk","=","pk",")","if","task",".","is_done",":","task",".","is_done","=","False","message","=","_","(","u\"Task marked as undone\"",")","else",":","task",".","is_done","=","True","message","=","_","(","u\"Task marked as finished\"",")","task",".","save","(",")","finished_task","(","request",".","user",",","task",")","if","request",".","is_ajax","(",")",":","context","=","json",".","dumps","(","{","'success'",":","True",",","'is_done'",":","task",".","is_done",",","'message'",":","message",",","}",")","return","HttpResponse","(","context",",","content_type","=","\"application\/json\"",")","return","redirect","(","task",".","get_absolute_url","(",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/views\/base.py#L63-L80"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/views\/galleries.py","language":"python","identifier":"get_gallery","parameters":"(project, gallery_id)","argument_list":"","return_statement":"","docstring":"Handy shortcut to get gallery object and validate id input.","docstring_summary":"Handy shortcut to get gallery object and validate id input.","docstring_tokens":["Handy","shortcut","to","get","gallery","object","and","validate","id","input","."],"function":"def get_gallery(project, gallery_id):\n \"\"\" Handy shortcut to get gallery object and validate id input.\n \"\"\"\n try:\n gallery_id = int(gallery_id)\n except (TypeError, ValueError):\n raise Http404\n try:\n return ContentObjectGallery.objects.for_object(project).get(pk=gallery_id)\n except ContentObjectGallery.DoesNotExist:\n raise Http404","function_tokens":["def","get_gallery","(","project",",","gallery_id",")",":","try",":","gallery_id","=","int","(","gallery_id",")","except","(","TypeError",",","ValueError",")",":","raise","Http404","try",":","return","ContentObjectGallery",".","objects",".","for_object","(","project",")",".","get","(","pk","=","gallery_id",")","except","ContentObjectGallery",".","DoesNotExist",":","raise","Http404"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/views\/galleries.py#L24-L34"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"projects\/views\/votings.py","language":"python","identifier":"VotingMapMixin.get_context_data","parameters":"(self, **kwargs)","argument_list":"","return_statement":"return context","docstring":"Serializes values for scripts.","docstring_summary":"Serializes values for scripts.","docstring_tokens":["Serializes","values","for","scripts","."],"function":"def get_context_data(self, **kwargs):\n \"\"\" Serializes values for scripts. \"\"\"\n serializer = MarkerSerializer(self.object.markers.all(), many=True,\n context={'request': self.request})\n context = super(VotingMapMixin, self).get_context_data(**kwargs)\n context.update({'markers': JSONRenderer().render(serializer.data)})\n return context","function_tokens":["def","get_context_data","(","self",",","*","*","kwargs",")",":","serializer","=","MarkerSerializer","(","self",".","object",".","markers",".","all","(",")",",","many","=","True",",","context","=","{","'request'",":","self",".","request","}",")","context","=","super","(","VotingMapMixin",",","self",")",".","get_context_data","(","*","*","kwargs",")","context",".","update","(","{","'markers'",":","JSONRenderer","(",")",".","render","(","serializer",".","data",")","}",")","return","context"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/projects\/views\/votings.py#L140-L146"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"etherpad\/views.py","language":"python","identifier":"ServePadView.form_valid","parameters":"(self, form)","argument_list":"","return_statement":"return response","docstring":"TODO: for now we serve only .txt files. More formats required!","docstring_summary":"TODO: for now we serve only .txt files. More formats required!","docstring_tokens":["TODO",":","for","now","we","serve","only",".","txt","files",".","More","formats","required!"],"function":"def form_valid(self, form):\n \"\"\" TODO: for now we serve only .txt files. More formats required! \"\"\"\n pad = form.cleaned_data['pad']\n response = HttpResponse(pad.text, content_type='text\/plain')\n response['Content-Disposition'] = \"attachment; filename=%s.txt\" % pad.pad_id\n return response","function_tokens":["def","form_valid","(","self",",","form",")",":","pad","=","form",".","cleaned_data","[","'pad'","]","response","=","HttpResponse","(","pad",".","text",",","content_type","=","'text\/plain'",")","response","[","'Content-Disposition'","]","=","\"attachment; filename=%s.txt\"","%","pad",".","pad_id","return","response"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/etherpad\/views.py#L118-L123"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"etherpad\/forms.py","language":"python","identifier":"PadCreationForm.clean","parameters":"(self)","argument_list":"","return_statement":"return cleaned_data","docstring":"We have to be sure that pad name does not exist yet.","docstring_summary":"We have to be sure that pad name does not exist yet.","docstring_tokens":["We","have","to","be","sure","that","pad","name","does","not","exist","yet","."],"function":"def clean(self):\n \"\"\" We have to be sure that pad name does not exist yet. \"\"\"\n cleaned_data = super(PadCreationForm, self).clean()\n group = cleaned_data.get('group')\n pad_id = u\"{}${}\".format(group.etherpad_id,\n cleaned_data.get('name').replace(' ', '_'))\n client = EtherpadLiteClient(\n base_params={'apikey': settings.ETHERPAD_API_KEY},\n base_url=settings.ETHERPAD_INTERNAL_URL)\n response = client.listPads(groupID=group.etherpad_id)\n if pad_id in response['padIDs']:\n self.add_error('name', _(u\"Name already exists\"))\n return cleaned_data","function_tokens":["def","clean","(","self",")",":","cleaned_data","=","super","(","PadCreationForm",",","self",")",".","clean","(",")","group","=","cleaned_data",".","get","(","'group'",")","pad_id","=","u\"{}${}\"",".","format","(","group",".","etherpad_id",",","cleaned_data",".","get","(","'name'",")",".","replace","(","' '",",","'_'",")",")","client","=","EtherpadLiteClient","(","base_params","=","{","'apikey'",":","settings",".","ETHERPAD_API_KEY","}",",","base_url","=","settings",".","ETHERPAD_INTERNAL_URL",")","response","=","client",".","listPads","(","groupID","=","group",".","etherpad_id",")","if","pad_id","in","response","[","'padIDs'","]",":","self",".","add_error","(","'name'",",","_","(","u\"Name already exists\"",")",")","return","cleaned_data"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/etherpad\/forms.py#L29-L41"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"etherpad\/models.py","language":"python","identifier":"cleanup_etherpad","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"","docstring":"Make sure that groups and pads will be deleted in etherpad-lite db.","docstring_summary":"Make sure that groups and pads will be deleted in etherpad-lite db.","docstring_tokens":["Make","sure","that","groups","and","pads","will","be","deleted","in","etherpad","-","lite","db","."],"function":"def cleanup_etherpad(sender, instance, **kwargs):\n \"\"\" Make sure that groups and pads will be deleted in etherpad-lite db. \"\"\"\n try:\n instance.destroy()\n except EtherpadException:\n pass","function_tokens":["def","cleanup_etherpad","(","sender",",","instance",",","*","*","kwargs",")",":","try",":","instance",".","destroy","(",")","except","EtherpadException",":","pass"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/etherpad\/models.py#L153-L158"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"etherpad\/models.py","language":"python","identifier":"activate_user_author","parameters":"(sender, instance, **kwargs)","argument_list":"","return_statement":"return author","docstring":"Creates new ehterpad author instnce when user register.","docstring_summary":"Creates new ehterpad author instnce when user register.","docstring_tokens":["Creates","new","ehterpad","author","instnce","when","user","register","."],"function":"def activate_user_author(sender, instance, **kwargs):\n \"\"\" Creates new ehterpad author instnce when user register. \"\"\"\n try:\n author = EtherpadAuthor.objects.get(user=instance)\n except EtherpadAuthor.DoesNotExist:\n author = EtherpadAuthor.objects.create(user=instance)\n return author","function_tokens":["def","activate_user_author","(","sender",",","instance",",","*","*","kwargs",")",":","try",":","author","=","EtherpadAuthor",".","objects",".","get","(","user","=","instance",")","except","EtherpadAuthor",".","DoesNotExist",":","author","=","EtherpadAuthor",".","objects",".","create","(","user","=","instance",")","return","author"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/etherpad\/models.py#L163-L169"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/tasks.py","language":"python","identifier":"send_test_email","parameters":"(receiver, subject, title, msg)","argument_list":"","return_statement":"return email.send(receiver, {\n 'subject': subject,\n 'title': title,\n 'msg': msg,\n })","docstring":"Send test email to check if celery beat works.","docstring_summary":"Send test email to check if celery beat works.","docstring_tokens":["Send","test","email","to","check","if","celery","beat","works","."],"function":"def send_test_email(receiver, subject, title, msg):\n \"\"\" Send test email to check if celery beat works. \"\"\"\n email = TestTemplateEmail()\n return email.send(receiver, {\n 'subject': subject,\n 'title': title,\n 'msg': msg,\n })","function_tokens":["def","send_test_email","(","receiver",",","subject",",","title",",","msg",")",":","email","=","TestTemplateEmail","(",")","return","email",".","send","(","receiver",",","{","'subject'",":","subject",",","'title'",":","title",",","'msg'",":","msg",",","}",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/tasks.py#L32-L39"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/tasks.py","language":"python","identifier":"cleanup_register_demands","parameters":"(forced=False)","argument_list":"","return_statement":"","docstring":"Run this task once a day to find not finished registrations and delete\n register demand objects along with user objects created during process.","docstring_summary":"Run this task once a day to find not finished registrations and delete\n register demand objects along with user objects created during process.","docstring_tokens":["Run","this","task","once","a","day","to","find","not","finished","registrations","and","delete","register","demand","objects","along","with","user","objects","created","during","process","."],"function":"def cleanup_register_demands(forced=False):\n \"\"\"\n Run this task once a day to find not finished registrations and delete\n register demand objects along with user objects created during process.\n \"\"\"\n logger.info(u\"[{}]: Started register cleanup\".format(timezone.now()))\n now = timezone.now()\n for demand in RegisterDemand.objects.all():\n delta_t = now - demand.date\n if delta_t > datetime.timedelta(days=1) or forced:\n logger.info(u\"Deleting user {} and register demand {}\"\\\n .format(demand.user.email, demand.pk))\n demand.user.delete()\n demand.delete()\n logger.info(u\"[{}]: Finished register cleanup\".format(timezone.now()))","function_tokens":["def","cleanup_register_demands","(","forced","=","False",")",":","logger",".","info","(","u\"[{}]: Started register cleanup\"",".","format","(","timezone",".","now","(",")",")",")","now","=","timezone",".","now","(",")","for","demand","in","RegisterDemand",".","objects",".","all","(",")",":","delta_t","=","now","-","demand",".","date","if","delta_t",">","datetime",".","timedelta","(","days","=","1",")","or","forced",":","logger",".","info","(","u\"Deleting user {} and register demand {}\"",".","format","(","demand",".","user",".","email",",","demand",".","pk",")",")","demand",".","user",".","delete","(",")","demand",".","delete","(",")","logger",".","info","(","u\"[{}]: Finished register cleanup\"",".","format","(","timezone",".","now","(",")",")",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/tasks.py#L61-L75"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/tasks.py","language":"python","identifier":"update_indexes","parameters":"()","argument_list":"","return_statement":"return subprocess.call(['python', filename, 'update_index'])","docstring":"Update haystack indexes.","docstring_summary":"Update haystack indexes.","docstring_tokens":["Update","haystack","indexes","."],"function":"def update_indexes():\n \"\"\" Update haystack indexes. \"\"\"\n logger.info(u\"[{}]: Started update indexes\".format(timezone.now()))\n filename = os.path.join(settings.BASE_DIR, 'manage.py')\n logger.info(u\"[{}]: Finished update indexes\".format(timezone.now()))\n return subprocess.call(['python', filename, 'update_index'])","function_tokens":["def","update_indexes","(",")",":","logger",".","info","(","u\"[{}]: Started update indexes\"",".","format","(","timezone",".","now","(",")",")",")","filename","=","os",".","path",".","join","(","settings",".","BASE_DIR",",","'manage.py'",")","logger",".","info","(","u\"[{}]: Finished update indexes\"",".","format","(","timezone",".","now","(",")",")",")","return","subprocess",".","call","(","[","'python'",",","filename",",","'update_index'","]",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/tasks.py#L79-L84"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/views.py","language":"python","identifier":"flush_page_cache","parameters":"()","argument_list":"","return_statement":"","docstring":"This function clears the cache saved in the template\n when we change the language of the site.","docstring_summary":"This function clears the cache saved in the template\n when we change the language of the site.","docstring_tokens":["This","function","clears","the","cache","saved","in","the","template","when","we","change","the","language","of","the","site","."],"function":"def flush_page_cache():\n \"\"\"\n This function clears the cache saved in the template\n when we change the language of the site.\n \"\"\"\n langs = [x[0] for x in settings.LANGUAGES]\n sections = ['home',]\n for l in langs:\n for s in sections:\n key = '_'.join([s, l])\n cache.delete(key)","function_tokens":["def","flush_page_cache","(",")",":","langs","=","[","x","[","0","]","for","x","in","settings",".","LANGUAGES","]","sections","=","[","'home'",",","]","for","l","in","langs",":","for","s","in","sections",":","key","=","'_'",".","join","(","[","s",",","l","]",")","cache",".","delete","(","key",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/views.py#L38-L48"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/utils.py","language":"python","identifier":"get_current_version","parameters":"()","argument_list":"","return_statement":"return version","docstring":"Returns current PROJECT version. This is useful for static files builds,\n e.g. scripts and styles. This way we can append common suffx for all files\n as well as for HTML tags later.","docstring_summary":"Returns current PROJECT version. This is useful for static files builds,\n e.g. scripts and styles. This way we can append common suffx for all files\n as well as for HTML tags later.","docstring_tokens":["Returns","current","PROJECT","version",".","This","is","useful","for","static","files","builds","e",".","g",".","scripts","and","styles",".","This","way","we","can","append","common","suffx","for","all","files","as","well","as","for","HTML","tags","later","."],"function":"def get_current_version():\n \"\"\" Returns current PROJECT version. This is useful for static files builds,\n e.g. scripts and styles. This way we can append common suffx for all files\n as well as for HTML tags later.\n \"\"\"\n try:\n v_file = open(os.path.join(settings.BASE_DIR, 'VERSION'))\n except IOError:\n return '0.0.0'\n version = v_file.read().strip()\n v_file.close()\n return version","function_tokens":["def","get_current_version","(",")",":","try",":","v_file","=","open","(","os",".","path",".","join","(","settings",".","BASE_DIR",",","'VERSION'",")",")","except","IOError",":","return","'0.0.0'","version","=","v_file",".","read","(",")",".","strip","(",")","v_file",".","close","(",")","return","version"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/utils.py#L9-L20"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/utils.py","language":"python","identifier":"serialize_item","parameters":"(model)","argument_list":"","return_statement":"return model_dict","docstring":"Changes the values of model fields on a serialized value. It takes\n a concrete instance of the model as an argument and returns a dictionary.","docstring_summary":"Changes the values of model fields on a serialized value. It takes\n a concrete instance of the model as an argument and returns a dictionary.","docstring_tokens":["Changes","the","values","of","model","fields","on","a","serialized","value",".","It","takes","a","concrete","instance","of","the","model","as","an","argument","and","returns","a","dictionary","."],"function":"def serialize_item(model):\n \"\"\" Changes the values of model fields on a serialized value. It takes\n a concrete instance of the model as an argument and returns a dictionary. \"\"\"\n model_dict = {}\n for key, val in model.__dict__.iteritems():\n if key.startswith('_'):\n continue\n elif type(model.__dict__[key]).__name__ == 'ImageFieldFile':\n model_dict.update({key: model.__dict__[key].path})\n elif type(model.__dict__[key]).__name__ == 'datetime':\n model_dict.update({key: model.__dict__[key].isoformat()})\n else:\n model_dict.update({key: model.serializable_value(key)})\n return model_dict","function_tokens":["def","serialize_item","(","model",")",":","model_dict","=","{","}","for","key",",","val","in","model",".","__dict__",".","iteritems","(",")",":","if","key",".","startswith","(","'_'",")",":","continue","elif","type","(","model",".","__dict__","[","key","]",")",".","__name__","==","'ImageFieldFile'",":","model_dict",".","update","(","{","key",":","model",".","__dict__","[","key","]",".","path","}",")","elif","type","(","model",".","__dict__","[","key","]",")",".","__name__","==","'datetime'",":","model_dict",".","update","(","{","key",":","model",".","__dict__","[","key","]",".","isoformat","(",")","}",")","else",":","model_dict",".","update","(","{","key",":","model",".","serializable_value","(","key",")","}",")","return","model_dict"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/utils.py#L23-L36"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/utils.py","language":"python","identifier":"serialize_models","parameters":"(model_class)","argument_list":"","return_statement":"return json.dumps(model_data)","docstring":"Serializes all objects from a given model and returns the data in json format.","docstring_summary":"Serializes all objects from a given model and returns the data in json format.","docstring_tokens":["Serializes","all","objects","from","a","given","model","and","returns","the","data","in","json","format","."],"function":"def serialize_models(model_class):\n \"\"\"\n Serializes all objects from a given model and returns the data in json format.\n \"\"\"\n model_data = []\n for item in model_class.objects.all():\n model_data.append(serialize_item(item))\n return json.dumps(model_data)","function_tokens":["def","serialize_models","(","model_class",")",":","model_data","=","[","]","for","item","in","model_class",".","objects",".","all","(",")",":","model_data",".","append","(","serialize_item","(","item",")",")","return","json",".","dumps","(","model_data",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/utils.py#L39-L46"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/utils.py","language":"python","identifier":"export_items","parameters":"(model_class)","argument_list":"","return_statement":"","docstring":"Exports all objects connected with a given model (class objects need\n to be passed as a function parameter) to a universal JSON format and\n saves the results in a file in a proper folder.","docstring_summary":"Exports all objects connected with a given model (class objects need\n to be passed as a function parameter) to a universal JSON format and\n saves the results in a file in a proper folder.","docstring_tokens":["Exports","all","objects","connected","with","a","given","model","(","class","objects","need","to","be","passed","as","a","function","parameter",")","to","a","universal","JSON","format","and","saves","the","results","in","a","file","in","a","proper","folder","."],"function":"def export_items(model_class):\n \"\"\" Exports all objects connected with a given model (class objects need\n to be passed as a function parameter) to a universal JSON format and\n saves the results in a file in a proper folder. \"\"\"\n dirname = os.path.join(DIR, model_class.__module__.split('.')[0].lower())\n if not os.path.isdir(dirname):\n os.mkdir(dirname)\n filename = os.path.join(dirname, model_class.__name__.lower() + '.json')\n f = codecs.open(filename, 'w+', 'utf-8')\n f.write(serialize_models(model_class))\n f.close()","function_tokens":["def","export_items","(","model_class",")",":","dirname","=","os",".","path",".","join","(","DIR",",","model_class",".","__module__",".","split","(","'.'",")","[","0","]",".","lower","(",")",")","if","not","os",".","path",".","isdir","(","dirname",")",":","os",".","mkdir","(","dirname",")","filename","=","os",".","path",".","join","(","dirname",",","model_class",".","__name__",".","lower","(",")","+","'.json'",")","f","=","codecs",".","open","(","filename",",","'w+'",",","'utf-8'",")","f",".","write","(","serialize_models","(","model_class",")",")","f",".","close","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/utils.py#L49-L59"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/utils.py","language":"python","identifier":"load_ideas","parameters":"()","argument_list":"","return_statement":"","docstring":"An example of a how the above function can be used in an idea. This\n function is written 'as once', therefore it will not work without\n corrections.","docstring_summary":"An example of a how the above function can be used in an idea. This\n function is written 'as once', therefore it will not work without\n corrections.","docstring_tokens":["An","example","of","a","how","the","above","function","can","be","used","in","an","idea",".","This","function","is","written","as","once","therefore","it","will","not","work","without","corrections","."],"function":"def load_ideas():\n \"\"\" An example of a how the above function can be used in an idea. This\n function is written 'as once', therefore it will not work without\n corrections.\n \"\"\"\n from django.contrib.auth.models import User\n from locations.models import Location\n from ideas.models import Idea\n from .helpers import date_from_iso\n f = codecs.open(os.path.join(DIR, 'ideas' ,'idea.json'), 'r', 'utf-8')\n data = json.loads(f.read())\n for l in data:\n try:\n idea = Idea.objects.create(\n creator = User.objects.get(pk=l['creator_id']),\n location = Location.objects.get(pk=l['location_id']),\n name = l['name'],\n description = l['description'],\n status = l['status'],\n date_created = date_from_iso(l['date_created']),\n date_edited = date_from_iso(l['date_edited'])\n )\n except Exception as ex:\n print ex.message","function_tokens":["def","load_ideas","(",")",":","from","django",".","contrib",".","auth",".","models","import","User","from","locations",".","models","import","Location","from","ideas",".","models","import","Idea","from",".","helpers","import","date_from_iso","f","=","codecs",".","open","(","os",".","path",".","join","(","DIR",",","'ideas'",",","'idea.json'",")",",","'r'",",","'utf-8'",")","data","=","json",".","loads","(","f",".","read","(",")",")","for","l","in","data",":","try",":","idea","=","Idea",".","objects",".","create","(","creator","=","User",".","objects",".","get","(","pk","=","l","[","'creator_id'","]",")",",","location","=","Location",".","objects",".","get","(","pk","=","l","[","'location_id'","]",")",",","name","=","l","[","'name'","]",",","description","=","l","[","'description'","]",",","status","=","l","[","'status'","]",",","date_created","=","date_from_iso","(","l","[","'date_created'","]",")",",","date_edited","=","date_from_iso","(","l","[","'date_edited'","]",")",")","except","Exception","as","ex",":","print","ex",".","message"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/utils.py#L62-L85"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/search_indexes.py","language":"python","identifier":"LocationIndex.index_queryset","parameters":"(self, using=None)","argument_list":"","return_statement":"return self.get_model().objects.all()","docstring":"Used when the entire index for model is updated.","docstring_summary":"Used when the entire index for model is updated.","docstring_tokens":["Used","when","the","entire","index","for","model","is","updated","."],"function":"def index_queryset(self, using=None):\n \"\"\"Used when the entire index for model is updated.\"\"\"\n return self.get_model().objects.all()","function_tokens":["def","index_queryset","(","self",",","using","=","None",")",":","return","self",".","get_model","(",")",".","objects",".","all","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/search_indexes.py#L24-L26"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/search_indexes.py","language":"python","identifier":"DiscussionIndex.index_queryset","parameters":"(self, using=None)","argument_list":"","return_statement":"return self.get_model().objects.all()","docstring":"Used when the entire index for model is updated.","docstring_summary":"Used when the entire index for model is updated.","docstring_tokens":["Used","when","the","entire","index","for","model","is","updated","."],"function":"def index_queryset(self, using=None):\n \"\"\"Used when the entire index for model is updated.\"\"\"\n return self.get_model().objects.all()","function_tokens":["def","index_queryset","(","self",",","using","=","None",")",":","return","self",".","get_model","(",")",".","objects",".","all","(",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/search_indexes.py#L41-L43"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/signals.py","language":"python","identifier":"update_cached_items","parameters":"(sender, instance, created, **kwargs)","argument_list":"","return_statement":"","docstring":"Update cached items for location set so there will be no delay between\n creating content object and displaying it.","docstring_summary":"Update cached items for location set so there will be no delay between\n creating content object and displaying it.","docstring_tokens":["Update","cached","items","for","location","set","so","there","will","be","no","delay","between","creating","content","object","and","displaying","it","."],"function":"def update_cached_items(sender, instance, created, **kwargs):\n \"\"\" \n Update cached items for location set so there will be no delay between\n creating content object and displaying it.\n \"\"\"\n postfix = None\n\n if isinstance(instance, News):\n postfix = 'news'\n elif isinstance(instance, Idea):\n postfix = 'ideas'\n elif isinstance(instance, Discussion):\n postfix = 'forum'\n elif isinstance(instance, Poll):\n postfix = 'polls'\n\n if postfix is None or not hasattr(instance, 'location'):\n return False\n\n key = \"{}_{}_{}\".format(instance.location.slug, get_language(), postfix)\n ct = ContentType.objects.get_for_model(instance)\n qs = ct.get_all_objects_for_this_type() \\\n .filter(location__pk__in=instance.location.get_children_id_list())\n qs = ct.get_all_objects_for_this_type().filter(location=instance.location)\n\n redis_cache.set(key, qs)","function_tokens":["def","update_cached_items","(","sender",",","instance",",","created",",","*","*","kwargs",")",":","postfix","=","None","if","isinstance","(","instance",",","News",")",":","postfix","=","'news'","elif","isinstance","(","instance",",","Idea",")",":","postfix","=","'ideas'","elif","isinstance","(","instance",",","Discussion",")",":","postfix","=","'forum'","elif","isinstance","(","instance",",","Poll",")",":","postfix","=","'polls'","if","postfix","is","None","or","not","hasattr","(","instance",",","'location'",")",":","return","False","key","=","\"{}_{}_{}\"",".","format","(","instance",".","location",".","slug",",","get_language","(",")",",","postfix",")","ct","=","ContentType",".","objects",".","get_for_model","(","instance",")","qs","=","ct",".","get_all_objects_for_this_type","(",")",".","filter","(","location__pk__in","=","instance",".","location",".","get_children_id_list","(",")",")","qs","=","ct",".","get_all_objects_for_this_type","(",")",".","filter","(","location","=","instance",".","location",")","redis_cache",".","set","(","key",",","qs",")"],"url":"https:\/\/github.com\/CivilHub\/CivilHub\/blob\/97c3ebe6031e6a3600c09d0fd99b764448ca592d\/places_core\/signals.py#L15-L40"} {"nwo":"CivilHub\/CivilHub","sha":"97c3ebe6031e6a3600c09d0fd99b764448ca592d","path":"places_core\/forms.py","language":"python","identifier":"BootstrapBaseForm.as_p","parameters":"(self)","argument_list":"","return_statement":"return self._html_output(\n normal_row = \"\"\"
\n