repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
nephila/djangocms-blog
djangocms_blog/cms_menus.py
BlogNavModifier.modify
python
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): app = None config = None if getattr(request, 'current_page', None) and request.current_page.application_urls: app = apphook_pool.get_apphook(request.current_page.application_urls) if app and app.app_...
Actual modifier function :param request: request :param nodes: complete list of nodes :param namespace: Menu namespace :param root_id: eventual root_id :param post_cut: flag for modifier stage :param breadcrumb: flag for modifier stage :return: nodeslist
train
https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/cms_menus.py#L133-L175
[ "def get_setting(name):\n from django.conf import settings\n from django.utils.translation import ugettext_lazy as _\n from meta import settings as meta_settings\n\n PERMALINKS = (\n ('full_date', _('Full date')),\n ('short_date', _('Year / Month')),\n ('category', _('Category')),\...
class BlogNavModifier(Modifier): """ This navigation modifier makes sure that when a particular blog post is viewed, a corresponding category is selected in menu """ _config = {}
nephila/djangocms-blog
djangocms_blog/managers.py
TaggedFilterItem.tagged
python
def tagged(self, other_model=None, queryset=None): tags = self._taglist(other_model, queryset) return self.get_queryset().filter(tags__in=tags).distinct()
Restituisce una queryset di elementi del model taggati, o con gli stessi tag di un model o un queryset
train
https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/managers.py#L16-L22
[ "def _taglist(self, other_model=None, queryset=None):\n \"\"\"\n Restituisce una lista di id di tag comuni al model corrente e al model\n o queryset passati come argomento\n \"\"\"\n from taggit.models import TaggedItem\n filter = None\n if queryset is not None:\n filter = set()\n ...
class TaggedFilterItem(object): def _taglist(self, other_model=None, queryset=None): """ Restituisce una lista di id di tag comuni al model corrente e al model o queryset passati come argomento """ from taggit.models import TaggedItem filter = None if querys...
nephila/djangocms-blog
djangocms_blog/managers.py
TaggedFilterItem._taglist
python
def _taglist(self, other_model=None, queryset=None): from taggit.models import TaggedItem filter = None if queryset is not None: filter = set() for item in queryset.all(): filter.update(item.tags.all()) filter = set([tag.id for tag in filter]) ...
Restituisce una lista di id di tag comuni al model corrente e al model o queryset passati come argomento
train
https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/managers.py#L24-L45
null
class TaggedFilterItem(object): def tagged(self, other_model=None, queryset=None): """ Restituisce una queryset di elementi del model taggati, o con gli stessi tag di un model o un queryset """ tags = self._taglist(other_model, queryset) return self.get_queryset().fi...
nephila/djangocms-blog
djangocms_blog/managers.py
TaggedFilterItem.tag_list
python
def tag_list(self, other_model=None, queryset=None): from taggit.models import Tag return Tag.objects.filter(id__in=self._taglist(other_model, queryset))
Restituisce un queryset di tag comuni al model corrente e al model o queryset passati come argomento
train
https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/managers.py#L47-L53
[ "def _taglist(self, other_model=None, queryset=None):\n \"\"\"\n Restituisce una lista di id di tag comuni al model corrente e al model\n o queryset passati come argomento\n \"\"\"\n from taggit.models import TaggedItem\n filter = None\n if queryset is not None:\n filter = set()\n ...
class TaggedFilterItem(object): def tagged(self, other_model=None, queryset=None): """ Restituisce una queryset di elementi del model taggati, o con gli stessi tag di un model o un queryset """ tags = self._taglist(other_model, queryset) return self.get_queryset().fi...
nephila/djangocms-blog
djangocms_blog/managers.py
GenericDateTaggedManager.get_months
python
def get_months(self, queryset=None, current_site=True): if queryset is None: queryset = self.get_queryset() if current_site: queryset = queryset.on_site() dates_qs = queryset.values_list(queryset.start_date_field, queryset.fallback_date_field) dates = [] f...
Get months with aggregate count (how much posts is in the month). Results are ordered by date.
train
https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/managers.py#L163-L184
null
class GenericDateTaggedManager(TaggedFilterItem, AppHookConfigTranslatableManager): use_for_related_fields = True queryset_class = GenericDateQuerySet def get_queryset(self, *args, **kwargs): return super(GenericDateTaggedManager, self).get_queryset(*args, **kwargs) def published(self, curren...
nephila/djangocms-blog
djangocms_blog/liveblog/consumers.py
liveblog_connect
python
def liveblog_connect(message, apphook, lang, post): try: post = Post.objects.namespace(apphook).language(lang).active_translations(slug=post).get() except Post.DoesNotExist: message.reply_channel.send({ 'text': json.dumps({'error': 'no_post'}), }) return Group(pos...
Connect users to the group of the given post according to the given language Return with an error message if a post cannot be found :param message: channel connect message :param apphook: apphook config namespace :param lang: language :param post: post slug
train
https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/liveblog/consumers.py#L11-L30
null
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import json from channels import Group from djangocms_blog.models import Post def liveblog_disconnect(message, apphook, lang, post): """ Disconnect users to the group of the given post according to the given l...
nephila/djangocms-blog
djangocms_blog/liveblog/consumers.py
liveblog_disconnect
python
def liveblog_disconnect(message, apphook, lang, post): try: post = Post.objects.namespace(apphook).language(lang).active_translations(slug=post).get() except Post.DoesNotExist: message.reply_channel.send({ 'text': json.dumps({'error': 'no_post'}), }) return Group(...
Disconnect users to the group of the given post according to the given language Return with an error message if a post cannot be found :param message: channel connect message :param apphook: apphook config namespace :param lang: language :param post: post slug
train
https://github.com/nephila/djangocms-blog/blob/3fdfbd4ba48947df0ee4c6d42e3a1c812b6dd95d/djangocms_blog/liveblog/consumers.py#L33-L51
null
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import json from channels import Group from djangocms_blog.models import Post def liveblog_connect(message, apphook, lang, post): """ Connect users to the group of the given post according to the given language...
xiyouMc/ncmbot
ncmbot/core.py
login
python
def login(password, phone=None, email=None, rememberLogin=True): if (phone is None) and (email is None): raise ParamsError() if password is None: raise ParamsError() r = NCloudBot() # r.username = phone or email md5 = hashlib.md5() md5.update(password) password = md5.hexdige...
登录接口,返回 :class:'Response' 对象 :param password: 网易云音乐的密码 :param phone: (optional) 手机登录 :param email: (optional) 邮箱登录 :param rememberLogin: (optional) 是否记住密码,默认 True
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L218-L245
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
user_play_list
python
def user_play_list(uid, offset=0, limit=1000): if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_PLAY_LIST' r.data = {'offset': offset, 'uid': uid, 'limit': limit, 'csrf_token': ''} r.send() return r.response
获取用户歌单,包含收藏的歌单 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 1000
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L248-L261
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
user_dj
python
def user_dj(uid, offset=0, limit=30): if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_DJ' r.data = {'offset': offset, 'limit': limit, "csrf_token": ""} r.params = {'uid': uid} r.send() return r.response
获取用户电台数据 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L264-L279
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
search
python
def search(keyword, type=1, offset=0, limit=30): if keyword is None: raise ParamsError() r = NCloudBot() r.method = 'SEARCH' r.data = { 's': keyword, 'limit': str(limit), 'type': str(type), 'offset': str(offset) } r.send() return r.response
搜索歌曲,支持搜索歌曲、歌手、专辑等 :param keyword: 关键词 :param type: (optional) 搜索类型,1: 单曲, 100: 歌手, 1000: 歌单, 1002: 用户 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L282-L302
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
user_follows
python
def user_follows(uid, offset='0', limit=30): if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_FOLLOWS' r.params = {'uid': uid} r.data = {'offset': offset, 'limit': limit, 'order': True} r.send() return r.response
获取用户关注列表 :param uid: 用户的ID,可通过登录或者其他接口获取 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 30
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L305-L320
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
user_event
python
def user_event(uid): if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_EVENT' r.params = {'uid': uid} r.data = {'time': -1, 'getcounts': True, "csrf_token": ""} r.send() return r.response
获取用户动态 :param uid: 用户的ID,可通过登录或者其他接口获取
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L345-L358
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
user_record
python
def user_record(uid, type=0): if uid is None: raise ParamsError() r = NCloudBot() r.method = 'USER_RECORD' r.data = {'type': type, 'uid': uid, "csrf_token": ""} r.send() return r.response
获取用户的播放列表,必须登录 :param uid: 用户的ID,可通过登录或者其他接口获取 :param type: (optional) 数据类型,0:获取所有记录,1:获取 weekData
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L361-L374
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
event
python
def event(): r = NCloudBot() r.method = 'EVENT' r.data = {"csrf_token": ""} r.send() return r.response
获取好友的动态,包括分享视频、音乐、动态等
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L377-L386
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
top_playlist_highquality
python
def top_playlist_highquality(cat='全部', offset=0, limit=20): r = NCloudBot() r.method = 'TOP_PLAYLIST_HIGHQUALITY' r.data = {'cat': cat, 'offset': offset, 'limit': limit} r.send() return r.response
获取网易云音乐的精品歌单 :param cat: (optional) 歌单类型,默认 ‘全部’,比如 华语、欧美等 :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 20
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L390-L402
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
play_list_detail
python
def play_list_detail(id, limit=20): if id is None: raise ParamsError() r = NCloudBot() r.method = 'PLAY_LIST_DETAIL' r.data = {'id': id, 'limit': limit, "csrf_token": ""} r.send() return r.response
获取歌单中的所有音乐。由于获取精品中,只能看到歌单名字和 ID 并没有歌单的音乐,因此增加该接口传入歌单 ID 获取歌单中的所有音乐. :param id: 歌单的ID :param limit: (optional) 数据上限多少行,默认 20
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L406-L420
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
music_url
python
def music_url(ids=[]): if not isinstance(ids, list): raise ParamsError() r = NCloudBot() r.method = 'MUSIC_URL' r.data = {'ids': ids, 'br': 999000, "csrf_token": ""} r.send() return r.response
通过歌曲 ID 获取歌曲下载地址 :param ids: 歌曲 ID 的 list
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L424-L436
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
lyric
python
def lyric(id): if id is None: raise ParamsError() r = NCloudBot() r.method = 'LYRIC' r.params = {'id': id} r.send() return r.response
通过歌曲 ID 获取歌曲歌词地址 :param id: 歌曲ID
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L440-L452
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
music_comment
python
def music_comment(id, offset=0, limit=20): if id is None: raise ParamsError() r = NCloudBot() r.method = 'MUSIC_COMMENT' r.params = {'id': id} r.data = {'offset': offset, 'limit': limit, 'rid': id, "csrf_token": ""} r.send() return r.response
获取歌曲的评论列表 :param id: 歌曲 ID :param offset: (optional) 分段起始位置,默认 0 :param limit: (optional) 数据上限多少行,默认 20
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L456-L471
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
song_detail
python
def song_detail(ids): if not isinstance(ids, list): raise ParamsError() c = [] for id in ids: c.append({'id': id}) r = NCloudBot() r.method = 'SONG_DETAIL' r.data = {'c': json.dumps(c), 'ids': c, "csrf_token": ""} r.send() return r.response
通过歌曲 ID 获取歌曲的详细信息 :param ids: 歌曲 ID 的 list
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L488-L503
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
personal_fm
python
def personal_fm(): r = NCloudBot() r.method = 'PERSONAL_FM' r.data = {"csrf_token": ""} r.send() return r.response
个人的 FM ,必须在登录之后调用,即 login 之后调用
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L507-L514
[ "def send(self):\n \"\"\"Sens the request.\"\"\"\n success = False\n if self.method is None:\n raise ParamsError()\n try:\n if self.method == 'SEARCH':\n req = self._get_requests()\n _url = self.__NETEAST_HOST + self._METHODS[self.method]\n resp = req.post(...
# coding:utf-8 """ NCloudBot.core ~~~~~~~~~~~~~~ This module implements the main NCloudBot system. :copyright: (c) 2017 by xiyouMc. :license: ISC, see LICENSE for more details. """ import hashlib import requests import json import cookielib import traceback from .util.encrypt import encrypted_reque...
xiyouMc/ncmbot
ncmbot/core.py
NCloudBot._get_webapi_requests
python
def _get_webapi_requests(self): headers = { 'Accept': '*/*', 'Accept-Language': 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded', 'Re...
Update headers of webapi for Requests.
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L104-L124
null
class NCloudBot(object): """ The :class:`NCloudBot` object. It carries out all functionality of NCloudBot Recommended interface is with the NCloudBot`s functions. """ req = requests.Session() username = None _METHODS = { # 登录模块 'LOGIN': '/weapi/login/cellphone?csrf_toke...
xiyouMc/ncmbot
ncmbot/core.py
NCloudBot._build_response
python
def _build_response(self, resp): # rememberLogin # if self.method is 'LOGIN' and resp.json().get('code') == 200: # cookiesJar.save_cookies(resp, NCloudBot.username) self.response.content = resp.content self.response.status_code = resp.status_code self.response.headers...
Build internal Response object from given response.
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L141-L148
null
class NCloudBot(object): """ The :class:`NCloudBot` object. It carries out all functionality of NCloudBot Recommended interface is with the NCloudBot`s functions. """ req = requests.Session() username = None _METHODS = { # 登录模块 'LOGIN': '/weapi/login/cellphone?csrf_toke...
xiyouMc/ncmbot
ncmbot/core.py
NCloudBot.send
python
def send(self): success = False if self.method is None: raise ParamsError() try: if self.method == 'SEARCH': req = self._get_requests() _url = self.__NETEAST_HOST + self._METHODS[self.method] resp = req.post(_url, data=self....
Sens the request.
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L150-L185
[ "def encrypted_request(text):\n text = json.dumps(text)\n secKey = createSecretKey(16)\n encText = aesEncrypt(aesEncrypt(text, nonce), secKey)\n encSecKey = rsaEncrypt(secKey, pubKey, modulus)\n data = {\n 'params': encText,\n 'encSecKey': encSecKey\n }\n return data", "def _get...
class NCloudBot(object): """ The :class:`NCloudBot` object. It carries out all functionality of NCloudBot Recommended interface is with the NCloudBot`s functions. """ req = requests.Session() username = None _METHODS = { # 登录模块 'LOGIN': '/weapi/login/cellphone?csrf_toke...
xiyouMc/ncmbot
ncmbot/core.py
Response.json
python
def json(self): if not self.headers and len(self.content) > 3: encoding = get_encoding_from_headers(self.headers) if encoding is not None: return json.loads(self.content.decode(encoding)) return json.loads(self.content)
Returns the json-encoded content of a response, if any.
train
https://github.com/xiyouMc/ncmbot/blob/c4832f3ee7630ba104a89559f09c1fc366d1547b/ncmbot/core.py#L208-L215
[ "def get_encoding_from_headers(headers):\n \"\"\"Returns encodings from given HTTP Header Dict.\n\n :param headers: dictionary to extract encoding from.\n \"\"\"\n\n content_type = headers.get('content-type')\n\n if not content_type:\n return None\n\n content_type, params = cgi.parse_header...
class Response(object): """ The :class:`Response` object. All :class:`NCloudBot` objects contain a :class:`NCloudBot.response <response>` attribute. """ def __init__(self): self.content = None self.headers = None self.status_code = None self.ok = False self....
mgedmin/findimports
findimports.py
adjust_lineno
python
def adjust_lineno(filename, lineno, name): line = linecache.getline(filename, lineno) # Hack warning: might be fooled by comments rx = re.compile(r'\b%s\b' % re.escape(name) if name != '*' else '[*]') while line and not rx.search(line): lineno += 1 line = linecache.getline(filename, line...
Adjust the line number of an import. Needed because import statements can span multiple lines, and our lineno is always the first line number.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L89-L101
null
#!/usr/bin/python """ FindImports is a script that processes Python module dependencies. Currently it can be used for finding unused imports and graphing module dependencies (with graphviz). Syntax: findimports.py [options] [filename|dirname ...] Options: -h, --help This help message -i, --imports Pr...
mgedmin/findimports
findimports.py
find_imports
python
def find_imports(filename): with open(filename) as f: root = ast.parse(f.read(), filename) visitor = ImportFinder(filename) visitor.visit(root) return visitor.imports
Find all imported names in a given file. Returns a list of ImportInfo objects.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L316-L325
null
#!/usr/bin/python """ FindImports is a script that processes Python module dependencies. Currently it can be used for finding unused imports and graphing module dependencies (with graphviz). Syntax: findimports.py [options] [filename|dirname ...] Options: -h, --help This help message -i, --imports Pr...
mgedmin/findimports
findimports.py
find_imports_and_track_names
python
def find_imports_and_track_names(filename, warn_about_duplicates=False, verbose=False): with open(filename) as f: root = ast.parse(f.read(), filename) visitor = ImportFinderAndNameTracker(filename) visitor.warn_about_duplicates = warn_about_duplicates visitor.ver...
Find all imported names in a given file. Returns ``(imports, unused)``. Both are lists of ImportInfo objects.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L328-L341
[ "def leaveAllScopes(self):\n # newScope()/leaveScope() calls are always balanced so scope_stack\n # should be empty at this point\n assert not self.scope_stack\n self.unused_names += self.scope.unused_names.values()\n self.unused_names.sort(key=attrgetter('lineno'))\n" ]
#!/usr/bin/python """ FindImports is a script that processes Python module dependencies. Currently it can be used for finding unused imports and graphing module dependencies (with graphviz). Syntax: findimports.py [options] [filename|dirname ...] Options: -h, --help This help message -i, --imports Pr...
mgedmin/findimports
findimports.py
ModuleGraph.parsePathname
python
def parsePathname(self, pathname): if os.path.isdir(pathname): for root, dirs, files in os.walk(pathname): dirs.sort() files.sort() for fn in files: # ignore emacsish junk if fn.endswith('.py') and not fn.startsw...
Parse one or more source files. ``pathname`` may be a file name or a directory name.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L417-L433
null
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.writeCache
python
def writeCache(self, filename): with open(filename, 'wb') as f: pickle.dump(self.modules, f)
Write the graph to a cache file.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L435-L438
null
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.readCache
python
def readCache(self, filename): with open(filename, 'rb') as f: self.modules = pickle.load(f)
Load the graph from a cache file.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L440-L443
null
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.parseFile
python
def parseFile(self, filename): modname = self.filenameToModname(filename) module = Module(modname, filename) self.modules[modname] = module if self.trackUnusedNames: module.imported_names, module.unused_names = \ find_imports_and_track_names(filename, ...
Parse a single file.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L445-L461
[ "def find_imports(filename):\n \"\"\"Find all imported names in a given file.\n\n Returns a list of ImportInfo objects.\n \"\"\"\n with open(filename) as f:\n root = ast.parse(f.read(), filename)\n visitor = ImportFinder(filename)\n visitor.visit(root)\n return visitor.imports\n", "def...
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.filenameToModname
python
def filenameToModname(self, filename): for ext in reversed(self._exts): if filename.endswith(ext): filename = filename[:-len(ext)] break else: self.warn(filename, '%s: unknown file name extension', filename) filename = os.path.abspath(filen...
Convert a filename to a module name.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L463-L481
[ "def warn(self, about, message, *args):\n if about in self._warned_about:\n return\n if args:\n message = message % args\n print(message, file=self._stderr)\n self._warned_about.add(about)\n" ]
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.findModuleOfName
python
def findModuleOfName(self, dotted_name, level, filename, extrapath=None): if dotted_name.endswith('.*'): return dotted_name[:-2] name = dotted_name # extrapath is None only in a couple of test cases; in real life it's # always present if level and level > 1 and extra...
Given a fully qualified name, find what module contains it.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L483-L511
null
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.isModule
python
def isModule(self, dotted_name, extrapath=None): try: return self._module_cache[(dotted_name, extrapath)] except KeyError: pass if dotted_name in sys.modules or dotted_name in self.builtin_modules: return dotted_name filename = dotted_name.replace('.',...
Is ``dotted_name`` the name of a module?
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L513-L560
[ "def filenameToModname(self, filename):\n \"\"\"Convert a filename to a module name.\"\"\"\n for ext in reversed(self._exts):\n if filename.endswith(ext):\n filename = filename[:-len(ext)]\n break\n else:\n self.warn(filename, '%s: unknown file name extension', filename)...
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.isPackage
python
def isPackage(self, dotted_name, extrapath=None): candidate = self.isModule(dotted_name + '.__init__', extrapath) if candidate: candidate = candidate[:-len(".__init__")] return candidate
Is ``dotted_name`` the name of a package?
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L562-L567
[ "def isModule(self, dotted_name, extrapath=None):\n \"\"\"Is ``dotted_name`` the name of a module?\"\"\"\n try:\n return self._module_cache[(dotted_name, extrapath)]\n except KeyError:\n pass\n if dotted_name in sys.modules or dotted_name in self.builtin_modules:\n return dotted_nam...
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.packageOf
python
def packageOf(self, dotted_name, packagelevel=None): if '.' not in dotted_name: return dotted_name if not self.isPackage(dotted_name): dotted_name = '.'.join(dotted_name.split('.')[:-1]) if packagelevel: dotted_name = '.'.join(dotted_name.split('.')[:packagele...
Determine the package that contains ``dotted_name``.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L569-L577
[ "def isPackage(self, dotted_name, extrapath=None):\n \"\"\"Is ``dotted_name`` the name of a package?\"\"\"\n candidate = self.isModule(dotted_name + '.__init__', extrapath)\n if candidate:\n candidate = candidate[:-len(\".__init__\")]\n return candidate\n" ]
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.listModules
python
def listModules(self): modules = list(self.modules.items()) modules.sort() return [module for name, module in modules]
Return an alphabetical list of all modules.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L590-L594
null
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.packageGraph
python
def packageGraph(self, packagelevel=None): packages = {} for module in self.listModules(): package_name = self.packageOf(module.modname, packagelevel) if package_name not in packages: dirname = os.path.dirname(module.filename) packages[package_name...
Convert a module graph to a package graph.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L596-L611
[ "def packageOf(self, dotted_name, packagelevel=None):\n \"\"\"Determine the package that contains ``dotted_name``.\"\"\"\n if '.' not in dotted_name:\n return dotted_name\n if not self.isPackage(dotted_name):\n dotted_name = '.'.join(dotted_name.split('.')[:-1])\n if packagelevel:\n ...
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.collapseCycles
python
def collapseCycles(self): # This algorithm determines Strongly Connected Components. Look it up. # It is adapted to suit our data structures. # Phase 0: prepare the graph imports = {} for u in self.modules: imports[u] = set() for v in self.modules[u].impo...
Create a graph with cycles collapsed. Collapse modules participating in a cycle to a single node.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L634-L699
[ "def visit1(u):\n visited[u] = True\n for v in imports[u]:\n if not visited[v]:\n visit1(v)\n order.append(u)\n", "def visit2(u):\n visited[u] = True\n component.append(u)\n for v in revimports[u]:\n if not visited[v]:\n visit2(v)\n" ]
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.printImportedNames
python
def printImportedNames(self): for module in self.listModules(): print("%s:" % module.modname) print(" %s" % "\n ".join(imp.name for imp in module.imported_names))
Produce a report of imported names.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L701-L705
[ "def listModules(self):\n \"\"\"Return an alphabetical list of all modules.\"\"\"\n modules = list(self.modules.items())\n modules.sort()\n return [module for name, module in modules]\n" ]
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.printImports
python
def printImports(self): for module in self.listModules(): print("%s:" % module.label) if self.external_dependencies: imports = list(module.imports) else: imports = [modname for modname in module.imports if modname in ...
Produce a report of dependencies.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L707-L717
[ "def listModules(self):\n \"\"\"Return an alphabetical list of all modules.\"\"\"\n modules = list(self.modules.items())\n modules.sort()\n return [module for name, module in modules]\n" ]
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.printUnusedImports
python
def printUnusedImports(self): for module in self.listModules(): names = [(unused.lineno, unused.name) for unused in module.unused_names] names.sort() for lineno, name in names: if not self.all_unused: line = linecache.g...
Produce a report of unused imports.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L719-L731
[ "def listModules(self):\n \"\"\"Return an alphabetical list of all modules.\"\"\"\n modules = list(self.modules.items())\n modules.sort()\n return [module for name, module in modules]\n" ]
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
mgedmin/findimports
findimports.py
ModuleGraph.printDot
python
def printDot(self): print("digraph ModuleDependencies {") print(" node[shape=box];") allNames = set() nameDict = {} for n, module in enumerate(self.listModules()): module._dot_name = "mod%d" % n nameDict[module.modname] = module._dot_name prin...
Produce a dependency graph in dot format.
train
https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L733-L758
[ "def quote(s):\n \"\"\"Quote a string for graphviz.\n\n This function is probably incomplete.\n \"\"\"\n return s.replace(\"\\\\\", \"\\\\\\\\\").replace('\"', '\\\\\"').replace('\\n', '\\\\n')\n", "def listModules(self):\n \"\"\"Return an alphabetical list of all modules.\"\"\"\n modules = list...
class ModuleGraph(object): """Module graph.""" trackUnusedNames = False all_unused = False warn_about_duplicates = False verbose = False external_dependencies = True # some builtin modules do not exist as separate .so files on disk builtin_modules = sys.builtin_module_names def __...
brendonh/pyth
pyth/plugins/rtf15/reader.py
Rtf15Reader.read
python
def read(self, source, errors='strict', clean_paragraphs=True): reader = Rtf15Reader(source, errors, clean_paragraphs) return reader.go()
source: A list of P objects.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/rtf15/reader.py#L80-L86
[ "def go(self):\n self.source.seek(0)\n\n if self.source.read(5) != r\"{\\rtf\":\n from pyth.errors import WrongFileType\n raise WrongFileType(\"Doesn't look like an RTF file\")\n\n self.source.seek(0)\n\n self.charsetTable = None\n self.charset = 'cp1252'\n self.group = Group(self)\n...
class Rtf15Reader(PythReader): @classmethod def __init__(self, source, errors='strict', clean_paragraphs=True): self.source = source self.errors = errors self.clean_paragraphs = clean_paragraphs self.document = document.Document def go(self): self.source.seek(0)...
brendonh/pyth
pyth/plugins/rtf15/reader.py
DocBuilder.cleanParagraph
python
def cleanParagraph(self): runs = self.block.content if not runs: self.block = None return if not self.clean_paragraphs: return joinedRuns = [] hasContent = False for run in runs: if run.content[0]: hasC...
Compress text runs, remove whitespace at start and end, skip empty blocks, etc
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/rtf15/reader.py#L241-L284
null
class DocBuilder(object): def __init__(self, doc, clean_paragraphs=True): self.run = [] self.propStack = [{}] self.block = None self.isImage = False self.listLevel = None self.listStack = [doc] self.clean_paragraphs = clean_paragraphs def flushRun(sel...
brendonh/pyth
pyth/plugins/xhtml/css.py
CSS.parse_css
python
def parse_css(self, css): rulesets = self.ruleset_re.findall(css) for (selector, declarations) in rulesets: rule = Rule(self.parse_selector(selector)) rule.properties = self.parse_declarations(declarations) self.rules.append(rule)
Parse a css style sheet into the CSS object. For the moment this will only work for very simple css documents. It works by using regular expression matching css syntax. This is not bullet proof.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/xhtml/css.py#L73-L85
[ "def parse_declarations(self, declarations):\n \"\"\"\n parse a css declaration list\n \"\"\"\n declarations = self.declaration_re.findall(declarations)\n return dict(declarations)\n", "def parse_selector(self, selector):\n \"\"\"\n parse a css selector\n \"\"\"\n tag, klass = self.sele...
class CSS(object): """ Represents a css document """ # The regular expressions used to parse the css document # match a rule e.g: '.imp {font-weight: bold; color: blue}' ruleset_re = re.compile(r'\s*(.+?)\s+\{(.*?)\}') # match a property declaration, e.g: 'font-weight = bold' declaratio...
brendonh/pyth
pyth/plugins/xhtml/css.py
CSS.parse_declarations
python
def parse_declarations(self, declarations): declarations = self.declaration_re.findall(declarations) return dict(declarations)
parse a css declaration list
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/xhtml/css.py#L87-L92
null
class CSS(object): """ Represents a css document """ # The regular expressions used to parse the css document # match a rule e.g: '.imp {font-weight: bold; color: blue}' ruleset_re = re.compile(r'\s*(.+?)\s+\{(.*?)\}') # match a property declaration, e.g: 'font-weight = bold' declaratio...
brendonh/pyth
pyth/plugins/xhtml/css.py
CSS.parse_selector
python
def parse_selector(self, selector): tag, klass = self.selector_re.match(selector).groups() return Selector(tag, klass)
parse a css selector
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/xhtml/css.py#L94-L99
null
class CSS(object): """ Represents a css document """ # The regular expressions used to parse the css document # match a rule e.g: '.imp {font-weight: bold; color: blue}' ruleset_re = re.compile(r'\s*(.+?)\s+\{(.*?)\}') # match a property declaration, e.g: 'font-weight = bold' declaratio...
brendonh/pyth
pyth/plugins/xhtml/css.py
CSS.get_properties
python
def get_properties(self, node): ret = {} # Try all the rules one by one for rule in self.rules: if rule.selector(node): ret.update(rule.properties) # Also search for direct 'style' arguments in the html doc for style_node in node.findParents(attrs={'st...
return a dict of all the properties of a given BeautifulSoup node found by applying the css style.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/xhtml/css.py#L101-L116
[ "def parse_declarations(self, declarations):\n \"\"\"\n parse a css declaration list\n \"\"\"\n declarations = self.declaration_re.findall(declarations)\n return dict(declarations)\n" ]
class CSS(object): """ Represents a css document """ # The regular expressions used to parse the css document # match a rule e.g: '.imp {font-weight: bold; color: blue}' ruleset_re = re.compile(r'\s*(.+?)\s+\{(.*?)\}') # match a property declaration, e.g: 'font-weight = bold' declaratio...
brendonh/pyth
pyth/__init__.py
namedModule
python
def namedModule(name): topLevel = __import__(name) packages = name.split(".")[1:] m = topLevel for p in packages: m = getattr(m, p) return m
Return a module given its name.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/__init__.py#L37-L44
null
""" Pyth -- Python text markup and conversion """ import os.path __version__ = '0.5.6' writerMap = { '.rtf': 'pyth.plugins.rtf15.writer.Rtf15Writer', '.html': 'pyth.plugins.xhtml.writer.XHTMLWriter', '.xhtml': 'pyth.plugins.xhtml.writer.XHTMLWriter', '.txt': 'pyth.plugins.plaintext.writer.PlaintextWr...
brendonh/pyth
pyth/__init__.py
namedObject
python
def namedObject(name): classSplit = name.split('.') module = namedModule('.'.join(classSplit[:-1])) return getattr(module, classSplit[-1])
Get a fully named module-global object.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/__init__.py#L47-L52
[ "def namedModule(name):\n \"\"\"Return a module given its name.\"\"\"\n topLevel = __import__(name)\n packages = name.split(\".\")[1:]\n m = topLevel\n for p in packages:\n m = getattr(m, p)\n return m\n" ]
""" Pyth -- Python text markup and conversion """ import os.path __version__ = '0.5.6' writerMap = { '.rtf': 'pyth.plugins.rtf15.writer.Rtf15Writer', '.html': 'pyth.plugins.xhtml.writer.XHTMLWriter', '.xhtml': 'pyth.plugins.xhtml.writer.XHTMLWriter', '.txt': 'pyth.plugins.plaintext.writer.PlaintextWr...
brendonh/pyth
pyth/plugins/rst/writer.py
RSTWriter.text
python
def text(self, text): ret = u"".join(text.content) if 'url' in text.properties: return u"`%s`_" % ret if 'bold' in text.properties: return u"**%s**" % ret if 'italic' in text.properties: return u"*%s*" % ret if 'sub' in text.properties: ...
process a pyth text and return the formatted string
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/rst/writer.py#L40-L55
null
class RSTWriter(PythWriter): @classmethod def write(klass, document, target=None): if target is None: target = StringIO() writer = RSTWriter(document, target) return writer.go() def __init__(self, doc, target): self.document = doc self.target = target ...
brendonh/pyth
pyth/plugins/rst/writer.py
RSTWriter.paragraph
python
def paragraph(self, paragraph, prefix=""): content = [] for text in paragraph.content: content.append(self.text(text)) content = u"".join(content).encode("utf-8") for line in content.split("\n"): self.target.write(" " * self.indent) self.target.write...
process a pyth paragraph into the target
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/rst/writer.py#L57-L81
[ "def text(self, text):\n \"\"\"\n process a pyth text and return the formatted string\n \"\"\"\n ret = u\"\".join(text.content)\n if 'url' in text.properties:\n return u\"`%s`_\" % ret\n if 'bold' in text.properties:\n return u\"**%s**\" % ret\n if 'italic' in text.properties:\n ...
class RSTWriter(PythWriter): @classmethod def write(klass, document, target=None): if target is None: target = StringIO() writer = RSTWriter(document, target) return writer.go() def __init__(self, doc, target): self.document = doc self.target = target ...
brendonh/pyth
pyth/plugins/rst/writer.py
RSTWriter.list
python
def list(self, list, prefix=None): self.indent += 1 for (i, entry) in enumerate(list.content): for (j, paragraph) in enumerate(entry.content): prefix = "- " if j == 0 else " " handler = self.paragraphDispatch[paragraph.__class__] handler(parag...
Process a pyth list into the target
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/rst/writer.py#L83-L94
null
class RSTWriter(PythWriter): @classmethod def write(klass, document, target=None): if target is None: target = StringIO() writer = RSTWriter(document, target) return writer.go() def __init__(self, doc, target): self.document = doc self.target = target ...
brendonh/pyth
pyth/plugins/xhtml/reader.py
XHTMLReader.format
python
def format(self, soup): # Remove all the newline characters before a closing tag. for node in soup.findAll(text=True): if node.rstrip(" ").endswith("\n"): node.replaceWith(node.rstrip(" ").rstrip("\n")) # Join the block elements lines into a single long line f...
format a BeautifulSoup document This will transform the block elements content from multi-lines text into single line. This allow us to avoid having to deal with further text rendering once this step has been done.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/xhtml/reader.py#L40-L65
null
class XHTMLReader(PythReader): @classmethod def read(self, source, css_source=None, encoding="utf-8", link_callback=None): reader = XHTMLReader(source, css_source, encoding, link_callback) return reader.go() def __init__(self, source, css_source=None, encoding="utf-8", link_callback=None):...
brendonh/pyth
pyth/plugins/xhtml/reader.py
XHTMLReader.url
python
def url(self, node): a_node = node.findParent('a') if not a_node: return None if self.link_callback is None: return a_node.get('href') else: return self.link_callback(a_node.get('href'))
return the url of a BeautifulSoup node or None if there is no url.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/xhtml/reader.py#L99-L111
null
class XHTMLReader(PythReader): @classmethod def read(self, source, css_source=None, encoding="utf-8", link_callback=None): reader = XHTMLReader(source, css_source, encoding, link_callback) return reader.go() def __init__(self, source, css_source=None, encoding="utf-8", link_callback=None):...
brendonh/pyth
pyth/plugins/xhtml/reader.py
XHTMLReader.process_text
python
def process_text(self, node): text = node.string.strip() if not text: return # Set all the properties properties=dict() if self.is_bold(node): properties['bold'] = True if self.is_italic(node): properties['italic'] = True if se...
Return a pyth Text object from a BeautifulSoup node or None if the text is empty.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/xhtml/reader.py#L113-L137
[ "def is_bold(self, node):\n \"\"\"\n Return true if the BeautifulSoup node needs to be rendered as\n bold.\n \"\"\"\n return (node.findParent(['b', 'strong']) is not None or\n self.css.is_bold(node))\n", "def is_italic(self, node):\n \"\"\"\n Return true if the BeautifulSoup node n...
class XHTMLReader(PythReader): @classmethod def read(self, source, css_source=None, encoding="utf-8", link_callback=None): reader = XHTMLReader(source, css_source, encoding, link_callback) return reader.go() def __init__(self, source, css_source=None, encoding="utf-8", link_callback=None):...
brendonh/pyth
pyth/plugins/xhtml/reader.py
XHTMLReader.process_into
python
def process_into(self, node, obj): if isinstance(node, BeautifulSoup.NavigableString): text = self.process_text(node) if text: obj.append(text) return if node.name == 'p': # add a new paragraph into the pyth object new_obj = doc...
Process a BeautifulSoup node and fill its elements into a pyth base object.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/xhtml/reader.py#L139-L165
[ "def append(self, item):\n \"\"\"\n Try to add an item to this element.\n\n If the item is of the wrong type, and if this element has a sub-type,\n then try to create such a sub-type and insert the item into that, instead.\n\n This happens recursively, so (in python-markup):\n L [ u'Foo' ]\n ...
class XHTMLReader(PythReader): @classmethod def read(self, source, css_source=None, encoding="utf-8", link_callback=None): reader = XHTMLReader(source, css_source, encoding, link_callback) return reader.go() def __init__(self, source, css_source=None, encoding="utf-8", link_callback=None):...
brendonh/pyth
pyth/document.py
_PythBase.append
python
def append(self, item): okay = True if not isinstance(item, self.contentType): if hasattr(self.contentType, 'contentType'): try: item = self.contentType(content=[item]) except TypeError: okay = False else: ...
Try to add an item to this element. If the item is of the wrong type, and if this element has a sub-type, then try to create such a sub-type and insert the item into that, instead. This happens recursively, so (in python-markup): L [ u'Foo' ] actually creates: ...
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/document.py#L30-L59
null
class _PythBase(object): def __init__(self, properties={}, content=[]): self.properties = {} self.content = [] for (k,v) in properties.iteritems(): self[k] = v for item in content: self.append(item) def __setitem__(self, key, value): if key no...
brendonh/pyth
pyth/plugins/python/reader.py
_MetaPythonBase
python
def _MetaPythonBase(): class MagicGetItem(type): def __new__(mcs, name, bases, dict): klass = type.__new__(mcs, name, bases, dict) mcs.__getitem__ = lambda _, k: klass()[k] return klass return MagicGetItem
Return a metaclass which implements __getitem__, allowing e.g. P[...] instead of P()[...]
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/python/reader.py#L40-L52
null
""" Write Pyth documents straight in Python, a la Nevow's Stan. """ from pyth.format import PythReader from pyth.document import * def _convert(content): if isinstance(content, _PythonBase): return content.toPyth() return content class PythonReader(PythReader): @classmethod def read(self, s...
brendonh/pyth
pyth/plugins/latex/writer.py
LatexWriter.write
python
def write(klass, document, target=None, stylesheet=""): writer = LatexWriter(document, target, stylesheet) return writer.go()
convert a pyth document to a latex document we can specify a stylesheet as a latex document fragment that will be inserted after the headers. This way we can override the default style.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/latex/writer.py#L19-L28
[ "def go(self):\n rst = RSTWriter.write(self.document).getvalue()\n settings = dict(input_encoding=\"UTF-8\",\n output_encoding=\"UTF-8\",\n stylesheet=\"stylesheet.tex\")\n latex = docutils.core.publish_string(rst,\n writer_name=...
class LatexWriter(PythWriter): @classmethod def __init__(self, doc, target=None, stylesheet=""): """Create a writer that produce a latex document we can specify a stylesheet as a latex document fragment that will be inserted after the headers. This way we can override the de...
brendonh/pyth
pyth/plugins/latex/writer.py
LatexWriter.full_stylesheet
python
def full_stylesheet(self): latex_fragment = r""" \usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref} \hypersetup{ pdftitle={%s}, pdfauthor={%s}, pdfsubject={%s} } """ % (self.document.properties.get("title"), self.do...
Return the style sheet that will ultimately be inserted into the latex document. This is the user given style sheet plus some additional parts to add the meta data.
train
https://github.com/brendonh/pyth/blob/f2a06fc8dc9b1cfc439ea14252d39b9845a7fa4b/pyth/plugins/latex/writer.py#L42-L60
null
class LatexWriter(PythWriter): @classmethod def write(klass, document, target=None, stylesheet=""): """ convert a pyth document to a latex document we can specify a stylesheet as a latex document fragment that will be inserted after the headers. This way we can override ...
cloudsigma/cgroupspy
cgroupspy/trees.py
BaseTree._build_tree
python
def _build_tree(self): groups = self._groups or self.get_children_paths(self.root_path) for group in groups: node = Node(name=group, parent=self.root) self.root.children.append(node) self._init_sub_groups(node)
Build a full or a partial tree, depending on the groups/sub-groups specified.
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/trees.py#L71-L80
[ "def _init_sub_groups(self, parent):\n \"\"\"\n Initialise sub-groups, and create any that do not already exist.\n \"\"\"\n\n if self._sub_groups:\n for sub_group in self._sub_groups:\n for component in split_path_components(sub_group):\n fp = os.path.join(parent.full_pa...
class BaseTree(object): """ A basic cgroup node tree. An exact representation of the filesystem tree, provided by cgroups. """ def __init__(self, root_path="/sys/fs/cgroup/", groups=None, sub_groups=None): self.root_path = root_path self._groups = groups or [] self._sub_groups = sub_gr...
cloudsigma/cgroupspy
cgroupspy/trees.py
BaseTree._init_sub_groups
python
def _init_sub_groups(self, parent): if self._sub_groups: for sub_group in self._sub_groups: for component in split_path_components(sub_group): fp = os.path.join(parent.full_path, component) if os.path.exists(fp): node =...
Initialise sub-groups, and create any that do not already exist.
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/trees.py#L82-L99
[ "def split_path_components(path):\n components=[]\n while True:\n path, component = os.path.split(path)\n if component != \"\":\n components.append(component)\n else:\n if path != \"\":\n components.append(path)\n break\n components.reve...
class BaseTree(object): """ A basic cgroup node tree. An exact representation of the filesystem tree, provided by cgroups. """ def __init__(self, root_path="/sys/fs/cgroup/", groups=None, sub_groups=None): self.root_path = root_path self._groups = groups or [] self._sub_groups = sub_gr...
cloudsigma/cgroupspy
cgroupspy/trees.py
BaseTree._init_children
python
def _init_children(self, parent): for dir_name in self.get_children_paths(parent.full_path): child = Node(name=dir_name, parent=parent) parent.children.append(child) self._init_children(child)
Initialise each node's children - essentially build the tree.
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/trees.py#L101-L109
null
class BaseTree(object): """ A basic cgroup node tree. An exact representation of the filesystem tree, provided by cgroups. """ def __init__(self, root_path="/sys/fs/cgroup/", groups=None, sub_groups=None): self.root_path = root_path self._groups = groups or [] self._sub_groups = sub_gr...
cloudsigma/cgroupspy
cgroupspy/nodes.py
Node.full_path
python
def full_path(self): if self.parent: return os.path.join(self.parent.full_path, self.name) return self.name
Absolute system path to the node
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L87-L92
null
class Node(object): """ Basic cgroup tree node. Provides means to link it to a parent and set a controller, depending on the cgroup the node exists in. """ NODE_ROOT = b"root" NODE_CONTROLLER_ROOT = b"controller_root" NODE_SLICE = b"slice" NODE_SCOPE = b"scope" NODE_CGROUP = b"cgrou...
cloudsigma/cgroupspy
cgroupspy/nodes.py
Node.path
python
def path(self): if self.parent: try: parent_path = self.parent.path.encode() except AttributeError: parent_path = self.parent.path return os.path.join(parent_path, self.name) return b"/"
Node's relative path from the root node
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L95-L104
null
class Node(object): """ Basic cgroup tree node. Provides means to link it to a parent and set a controller, depending on the cgroup the node exists in. """ NODE_ROOT = b"root" NODE_CONTROLLER_ROOT = b"controller_root" NODE_SLICE = b"slice" NODE_SCOPE = b"scope" NODE_CGROUP = b"cgrou...
cloudsigma/cgroupspy
cgroupspy/nodes.py
Node._get_node_type
python
def _get_node_type(self): if self.parent is None: return self.NODE_ROOT elif self.parent.node_type == self.NODE_ROOT: return self.NODE_CONTROLLER_ROOT elif b".slice" in self.name or b'.partition' in self.name: return self.NODE_SLICE elif b".scope" in ...
Returns the current node's type
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L106-L118
null
class Node(object): """ Basic cgroup tree node. Provides means to link it to a parent and set a controller, depending on the cgroup the node exists in. """ NODE_ROOT = b"root" NODE_CONTROLLER_ROOT = b"controller_root" NODE_SLICE = b"slice" NODE_SCOPE = b"scope" NODE_CGROUP = b"cgrou...
cloudsigma/cgroupspy
cgroupspy/nodes.py
Node._get_controller_type
python
def _get_controller_type(self): if self.node_type == self.NODE_CONTROLLER_ROOT and self.name in self.CONTROLLERS: return self.name elif self.parent: return self.parent.controller_type else: return None
Returns the current node's controller type
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L120-L128
null
class Node(object): """ Basic cgroup tree node. Provides means to link it to a parent and set a controller, depending on the cgroup the node exists in. """ NODE_ROOT = b"root" NODE_CONTROLLER_ROOT = b"controller_root" NODE_SLICE = b"slice" NODE_SCOPE = b"scope" NODE_CGROUP = b"cgrou...
cloudsigma/cgroupspy
cgroupspy/nodes.py
Node.create_cgroup
python
def create_cgroup(self, name): node = Node(name, parent=self) if node in self.children: raise RuntimeError('Node {} already exists under {}'.format(name, self.path)) name = name.encode() fp = os.path.join(self.full_path, name) os.mkdir(fp) self.children.appen...
Create a cgroup by name and attach it under this node.
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L137-L149
null
class Node(object): """ Basic cgroup tree node. Provides means to link it to a parent and set a controller, depending on the cgroup the node exists in. """ NODE_ROOT = b"root" NODE_CONTROLLER_ROOT = b"controller_root" NODE_SLICE = b"slice" NODE_SCOPE = b"scope" NODE_CGROUP = b"cgrou...
cloudsigma/cgroupspy
cgroupspy/nodes.py
Node.delete_cgroup
python
def delete_cgroup(self, name): name = name.encode() fp = os.path.join(self.full_path, name) if os.path.exists(fp): os.rmdir(fp) node = Node(name, parent=self) try: self.children.remove(node) except ValueError: return
Delete a cgroup by name and detach it from this node. Raises OSError if the cgroup is not empty.
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L151-L164
null
class Node(object): """ Basic cgroup tree node. Provides means to link it to a parent and set a controller, depending on the cgroup the node exists in. """ NODE_ROOT = b"root" NODE_CONTROLLER_ROOT = b"controller_root" NODE_SLICE = b"slice" NODE_SCOPE = b"scope" NODE_CGROUP = b"cgrou...
cloudsigma/cgroupspy
cgroupspy/nodes.py
Node.delete_empty_children
python
def delete_empty_children(self): for child in self.children: child.delete_empty_children() try: if os.path.exists(child.full_path): os.rmdir(child.full_path) except OSError: pass else: self.children.remove(child)
Walk through the children of this node and delete any that are empty.
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L166-L176
null
class Node(object): """ Basic cgroup tree node. Provides means to link it to a parent and set a controller, depending on the cgroup the node exists in. """ NODE_ROOT = b"root" NODE_CONTROLLER_ROOT = b"controller_root" NODE_SLICE = b"slice" NODE_SCOPE = b"scope" NODE_CGROUP = b"cgrou...
cloudsigma/cgroupspy
cgroupspy/nodes.py
NodeControlGroup.add_node
python
def add_node(self, node): if self.controllers.get(node.controller_type, None): raise RuntimeError("Cannot add node {} to the node group. A node for {} group is already assigned".format( node, node.controller_type )) self.nodes.append(node) ...
A a Node object to the group. Only one node per cgroup is supported
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L219-L231
null
class NodeControlGroup(object): """ A tree node that can group together same multiple nodes based on their position in the cgroup hierarchy For example - we have mounted all the cgroups in /sys/fs/cgroup/ and we have a scope in each of them under /{cpuset,cpu,memory,cpuacct}/isolated.scope/. Then Node...
cloudsigma/cgroupspy
cgroupspy/nodes.py
NodeControlGroup.group_tasks
python
def group_tasks(self): tasks = set() for node in walk_tree(self): for ctrl in node.controllers.values(): tasks.update(ctrl.tasks) return tasks
All tasks in the hierarchy, affected by this group.
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L241-L247
[ "def walk_tree(root):\n \"\"\"Pre-order depth-first\"\"\"\n yield root\n\n for child in root.children:\n for el in walk_tree(child):\n yield el\n" ]
class NodeControlGroup(object): """ A tree node that can group together same multiple nodes based on their position in the cgroup hierarchy For example - we have mounted all the cgroups in /sys/fs/cgroup/ and we have a scope in each of them under /{cpuset,cpu,memory,cpuacct}/isolated.scope/. Then Node...
cloudsigma/cgroupspy
cgroupspy/nodes.py
NodeControlGroup.tasks
python
def tasks(self): tasks = set() for ctrl in self.controllers.values(): tasks.update(ctrl.tasks) return tasks
Tasks in this exact group
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/nodes.py#L250-L255
null
class NodeControlGroup(object): """ A tree node that can group together same multiple nodes based on their position in the cgroup hierarchy For example - we have mounted all the cgroups in /sys/fs/cgroup/ and we have a scope in each of them under /{cpuset,cpu,memory,cpuacct}/isolated.scope/. Then Node...
cloudsigma/cgroupspy
cgroupspy/controllers.py
Controller.filepath
python
def filepath(self, filename): return os.path.join(self.node.full_path, filename)
The full path to a file
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/controllers.py#L48-L51
null
class Controller(object): """ Base controller. Provides access to general files, existing in all cgroups and means to get/set properties """ tasks = MultiLineIntegerFile("tasks") procs = MultiLineIntegerFile("cgroup.procs") notify_on_release = FlagFile("notify_on_release") clone_children =...
cloudsigma/cgroupspy
cgroupspy/controllers.py
Controller.get_property
python
def get_property(self, filename): with open(self.filepath(filename)) as f: return f.read().strip()
Opens the file and reads the value
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/controllers.py#L53-L57
[ "def filepath(self, filename):\n \"\"\"The full path to a file\"\"\"\n\n return os.path.join(self.node.full_path, filename)\n" ]
class Controller(object): """ Base controller. Provides access to general files, existing in all cgroups and means to get/set properties """ tasks = MultiLineIntegerFile("tasks") procs = MultiLineIntegerFile("cgroup.procs") notify_on_release = FlagFile("notify_on_release") clone_children =...
cloudsigma/cgroupspy
cgroupspy/controllers.py
Controller.set_property
python
def set_property(self, filename, value): with open(self.filepath(filename), "w") as f: return f.write(str(value))
Opens the file and writes the value
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/controllers.py#L59-L63
[ "def filepath(self, filename):\n \"\"\"The full path to a file\"\"\"\n\n return os.path.join(self.node.full_path, filename)\n" ]
class Controller(object): """ Base controller. Provides access to general files, existing in all cgroups and means to get/set properties """ tasks = MultiLineIntegerFile("tasks") procs = MultiLineIntegerFile("cgroup.procs") notify_on_release = FlagFile("notify_on_release") clone_children =...
cloudsigma/cgroupspy
cgroupspy/utils.py
walk_tree
python
def walk_tree(root): yield root for child in root.children: for el in walk_tree(child): yield el
Pre-order depth-first
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/utils.py#L32-L38
[ "def walk_tree(root):\n \"\"\"Pre-order depth-first\"\"\"\n yield root\n\n for child in root.children:\n for el in walk_tree(child):\n yield el\n" ]
""" Copyright (c) 2014, CloudSigma AG All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the fo...
cloudsigma/cgroupspy
cgroupspy/utils.py
walk_up_tree
python
def walk_up_tree(root): for child in root.children: for el in walk_up_tree(child): yield el yield root
Post-order depth-first
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/utils.py#L41-L47
[ "def walk_up_tree(root):\n \"\"\"Post-order depth-first\"\"\"\n for child in root.children:\n for el in walk_up_tree(child):\n yield el\n\n yield root\n" ]
""" Copyright (c) 2014, CloudSigma AG All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the fo...
cloudsigma/cgroupspy
cgroupspy/utils.py
get_device_major_minor
python
def get_device_major_minor(dev_path): stat = os.lstat(dev_path) return os.major(stat.st_rdev), os.minor(stat.st_rdev)
Returns the device (major, minor) tuple for simplicity :param dev_path: Path to the device :return: (device major, device minor) :rtype: (int, int)
train
https://github.com/cloudsigma/cgroupspy/blob/e705ac4ccdfe33d8ecc700e9a35a9556084449ca/cgroupspy/utils.py#L50-L58
null
""" Copyright (c) 2014, CloudSigma AG All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the fo...
django-fluent/django-fluent-dashboard
fluent_dashboard/items.py
CmsModelList.init_with_context
python
def init_with_context(self, context): # Apply the include/exclude patterns: listitems = self._visible_models(context['request']) # Convert to a similar data structure like the dashboard icons have. # This allows sorting the items identically. models = [ {'name': mode...
Initialize the menu.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/items.py#L27-L50
[ "def sort_cms_models(cms_models):\n \"\"\"\n Sort a set of CMS-related models in a custom (predefined) order.\n \"\"\"\n cms_models.sort(key=lambda model: (\n get_cms_model_order(model['name']) if is_cms_app(model['app_name']) else 999,\n model['app_name'],\n model['title']\n ))\...
class CmsModelList(items.ModelList): """ A custom :class:`~admin_tools.menu.items.ModelList` that displays menu items for each model. It has a strong bias towards sorting CMS apps on top. """ def is_item_visible(self, model, perms): """ Return whether the model should be displayed ...
django-fluent/django-fluent-dashboard
fluent_dashboard/items.py
ReturnToSiteItem.init_with_context
python
def init_with_context(self, context): super(ReturnToSiteItem, self).init_with_context(context) # See if the current page is being edited, update URL accordingly. edited_model = self.get_edited_object(context['request']) if edited_model: try: url = edited_mode...
Find the current URL based on the context. It uses :func:`get_edited_object` to find the model, and calls ``get_absolute_url()`` to get the frontend URL.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/items.py#L82-L99
[ "def get_edited_object(self, request):\n \"\"\"\n Return the object which is currently being edited.\n Returns ``None`` if the match could not be made.\n \"\"\"\n resolvermatch = urls.resolve(request.path_info)\n if resolvermatch.namespace == 'admin' and resolvermatch.url_name and resolvermatch.ur...
class ReturnToSiteItem(items.MenuItem): """ A "Return to site" button for the menu. It redirects the user back to the frontend pages. By default, it attempts to find the current frontend URL that corresponds with the model that's being edited in the admin 'change' page. If this is not possible,...
django-fluent/django-fluent-dashboard
fluent_dashboard/items.py
ReturnToSiteItem.get_edited_object
python
def get_edited_object(self, request): resolvermatch = urls.resolve(request.path_info) if resolvermatch.namespace == 'admin' and resolvermatch.url_name and resolvermatch.url_name.endswith('_change'): # In "appname_modelname_change" view of the admin. # Extract the appname and mode...
Return the object which is currently being edited. Returns ``None`` if the match could not be made.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/items.py#L101-L122
[ "def get_object_by_natural_key(self, app_label, model_name, object_id):\n \"\"\"\n Return a model based on a natural key.\n This is a utility function for :func:`get_edited_object`.\n \"\"\"\n try:\n model_type = ContentType.objects.get_by_natural_key(app_label, model_name)\n except Content...
class ReturnToSiteItem(items.MenuItem): """ A "Return to site" button for the menu. It redirects the user back to the frontend pages. By default, it attempts to find the current frontend URL that corresponds with the model that's being edited in the admin 'change' page. If this is not possible,...
django-fluent/django-fluent-dashboard
fluent_dashboard/items.py
ReturnToSiteItem.get_object_by_natural_key
python
def get_object_by_natural_key(self, app_label, model_name, object_id): try: model_type = ContentType.objects.get_by_natural_key(app_label, model_name) except ContentType.DoesNotExist: return None # Pointless to fetch the object, if there is no URL to generate # A...
Return a model based on a natural key. This is a utility function for :func:`get_edited_object`.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/items.py#L124-L143
null
class ReturnToSiteItem(items.MenuItem): """ A "Return to site" button for the menu. It redirects the user back to the frontend pages. By default, it attempts to find the current frontend URL that corresponds with the model that's being edited in the admin 'change' page. If this is not possible,...
django-fluent/django-fluent-dashboard
fluent_dashboard/dashboard.py
FluentIndexDashboard.get_personal_module
python
def get_personal_module(self): return PersonalModule( layout='inline', draggable=False, deletable=False, collapsible=False, )
Instantiate the :class:`~fluent_dashboard.modules.PersonalModule` for use in the dashboard.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/dashboard.py#L69-L78
null
class FluentIndexDashboard(Dashboard): """ A custom home screen for the Django admin interface. It displays the application groups based on with :ref:`FLUENT_DASHBOARD_APP_GROUPS` setting. To activate the dashboard add the following to your settings.py:: ADMIN_TOOLS_INDEX_DASHBOARD = 'fluent_d...
django-fluent/django-fluent-dashboard
fluent_dashboard/dashboard.py
FluentIndexDashboard.get_application_modules
python
def get_application_modules(self): modules = [] appgroups = get_application_groups() for title, kwargs in appgroups: AppListClass = get_class(kwargs.pop('module')) # e.g. CmsAppIconlist, AppIconlist, Applist modules.append(AppListClass(title, **kwargs)) return mo...
Instantiate all application modules (i.e. :class:`~admin_tools.dashboard.modules.AppList`, :class:`~fluent_dashboard.modules.AppIconList` and :class:`~fluent_dashboard.modules.CmsAppIconList`) for use in the dashboard.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/dashboard.py#L80-L93
[ "def get_application_groups():\n \"\"\"\n Return the applications of the system, organized in various groups.\n\n These groups are not connected with the application names,\n but rather with a pattern of applications.\n \"\"\"\n\n groups = []\n for title, groupdict in appsettings.FLUENT_DASHBOA...
class FluentIndexDashboard(Dashboard): """ A custom home screen for the Django admin interface. It displays the application groups based on with :ref:`FLUENT_DASHBOARD_APP_GROUPS` setting. To activate the dashboard add the following to your settings.py:: ADMIN_TOOLS_INDEX_DASHBOARD = 'fluent_d...
django-fluent/django-fluent-dashboard
fluent_dashboard/dashboard.py
FluentAppIndexDashboard.get_recent_actions_module
python
def get_recent_actions_module(self): return modules.RecentActions( _('Recent Actions'), include_list=self.get_app_content_types(), limit=5, enabled=False, collapsible=False )
Instantiate the :class:`~admin_tools.dashboard.modules.RecentActions` module for use in the appliation index page.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/dashboard.py#L153-L164
null
class FluentAppIndexDashboard(AppIndexDashboard): """ A custom application index page for the Django admin interface. This dashboard is displayed when one specific application is opened via the breadcrumb. It displays the models and recent actions of the specific application. To activate the dashbo...
django-fluent/django-fluent-dashboard
fluent_dashboard/appgroups.py
get_application_groups
python
def get_application_groups(): groups = [] for title, groupdict in appsettings.FLUENT_DASHBOARD_APP_GROUPS: # Allow to pass all possible arguments to the DashboardModule class. module_kwargs = groupdict.copy() # However, the 'models' is treated special, to have catch-all support. ...
Return the applications of the system, organized in various groups. These groups are not connected with the application names, but rather with a pattern of applications.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/appgroups.py#L27-L55
null
""" Splitting and organizing applications and models into groups. This module is mostly meant for internal use. """ from fnmatch import fnmatch from future.utils import iteritems from importlib import import_module from django.core.exceptions import ImproperlyConfigured from fluent_dashboard import appsettings import i...
django-fluent/django-fluent-dashboard
fluent_dashboard/appgroups.py
sort_cms_models
python
def sort_cms_models(cms_models): cms_models.sort(key=lambda model: ( get_cms_model_order(model['name']) if is_cms_app(model['app_name']) else 999, model['app_name'], model['title'] ))
Sort a set of CMS-related models in a custom (predefined) order.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/appgroups.py#L58-L66
null
""" Splitting and organizing applications and models into groups. This module is mostly meant for internal use. """ from fnmatch import fnmatch from future.utils import iteritems from importlib import import_module from django.core.exceptions import ImproperlyConfigured from fluent_dashboard import appsettings import i...
django-fluent/django-fluent-dashboard
fluent_dashboard/appgroups.py
is_cms_app
python
def is_cms_app(app_name): for pat in appsettings.FLUENT_DASHBOARD_CMS_APP_NAMES: if fnmatch(app_name, pat): return True return False
Return whether the given application is a CMS app
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/appgroups.py#L69-L77
null
""" Splitting and organizing applications and models into groups. This module is mostly meant for internal use. """ from fnmatch import fnmatch from future.utils import iteritems from importlib import import_module from django.core.exceptions import ImproperlyConfigured from fluent_dashboard import appsettings import i...
django-fluent/django-fluent-dashboard
fluent_dashboard/appgroups.py
get_cms_model_order
python
def get_cms_model_order(model_name): for (name, order) in iteritems(appsettings.FLUENT_DASHBOARD_CMS_MODEL_ORDER): if name in model_name: return order return 999
Return a numeric ordering for a model name.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/appgroups.py#L80-L87
null
""" Splitting and organizing applications and models into groups. This module is mostly meant for internal use. """ from fnmatch import fnmatch from future.utils import iteritems from importlib import import_module from django.core.exceptions import ImproperlyConfigured from fluent_dashboard import appsettings import i...
django-fluent/django-fluent-dashboard
fluent_dashboard/menu.py
FluentMenu.init_with_context
python
def init_with_context(self, context): site_name = get_admin_site_name(context) self.children += [ items.MenuItem(_('Dashboard'), reverse('{0}:index'.format(site_name))), items.Bookmarks(), ] for title, kwargs in get_application_groups(): if kwargs.ge...
Initialize the menu items.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/menu.py#L31-L48
[ "def get_application_groups():\n \"\"\"\n Return the applications of the system, organized in various groups.\n\n These groups are not connected with the application names,\n but rather with a pattern of applications.\n \"\"\"\n\n groups = []\n for title, groupdict in appsettings.FLUENT_DASHBOA...
class FluentMenu(Menu): """ Custom Menu for admin site. The top level menu items created by this menu reflect the application groups defined in :ref:`FLUENT_DASHBOARD_APP_GROUPS`. By using both the :class:`~fluent_dashboard.dashboard.FluentIndexDashboard` and this class, the menu and dashboard ...
django-fluent/django-fluent-dashboard
fluent_dashboard/modules.py
PersonalModule.init_with_context
python
def init_with_context(self, context): super(PersonalModule, self).init_with_context(context) current_user = context['request'].user if django.VERSION < (1, 5): current_username = current_user.first_name or current_user.username else: current_username = current_use...
Initializes the link list.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/modules.py#L61-L99
null
class PersonalModule(modules.LinkList): """ A simple module to display a welcome message. .. image:: /images/personalmodule.png :width: 471px :height: 77px :alt: PersonalModule for django-fluent-dashboard It renders the template ``fluent_dashboard/modules/personal.html``, unle...
django-fluent/django-fluent-dashboard
fluent_dashboard/modules.py
AppIconList.init_with_context
python
def init_with_context(self, context): super(AppIconList, self).init_with_context(context) apps = self.children # Standard model only has a title, change_url and add_url. # Restore the app_name and name, so icons can be matched. for app in apps: app_name = self._get_a...
Initializes the icon list.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/modules.py#L126-L149
[ "def _get_app_name(self, appdata):\n \"\"\"\n Extract the app name from the ``appdata`` that *django-admin-tools* provides.\n \"\"\"\n return appdata['url'].strip('/').split('/')[-1] # /foo/admin/appname/\n", "def _get_model_name(self, modeldata):\n \"\"\"\n Extract the model name from the ``m...
class AppIconList(modules.AppList): """ The list of applications, icon style. .. image:: /images/appiconlist.png :width: 471px :height: 124px :alt: AppIconList module for django-fluent-dashboard It uses the ``FLUENT_DASHBOARD_APP_ICONS`` setting to find application icons. """ ...
django-fluent/django-fluent-dashboard
fluent_dashboard/modules.py
AppIconList._get_model_name
python
def _get_model_name(self, modeldata): if 'change_url' in modeldata: return modeldata['change_url'].strip('/').split('/')[-1] # /foo/admin/appname/modelname elif 'add_url' in modeldata: return modeldata['add_url'].strip('/').split('/')[-2] # /foo/admin/appname/modelname/add...
Extract the model name from the ``modeldata`` that *django-admin-tools* provides.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/modules.py#L157-L166
null
class AppIconList(modules.AppList): """ The list of applications, icon style. .. image:: /images/appiconlist.png :width: 471px :height: 124px :alt: AppIconList module for django-fluent-dashboard It uses the ``FLUENT_DASHBOARD_APP_ICONS`` setting to find application icons. """ ...
django-fluent/django-fluent-dashboard
fluent_dashboard/modules.py
AppIconList.get_icon_for_model
python
def get_icon_for_model(self, app_name, model_name, default=None): key = "{0}/{1}".format(app_name, model_name) return appsettings.FLUENT_DASHBOARD_APP_ICONS.get(key, default)
Return the icon for the given model. It reads the :ref:`FLUENT_DASHBOARD_APP_ICONS` setting.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/modules.py#L168-L174
null
class AppIconList(modules.AppList): """ The list of applications, icon style. .. image:: /images/appiconlist.png :width: 471px :height: 124px :alt: AppIconList module for django-fluent-dashboard It uses the ``FLUENT_DASHBOARD_APP_ICONS`` setting to find application icons. """ ...
django-fluent/django-fluent-dashboard
fluent_dashboard/modules.py
AppIconList.get_icon_url
python
def get_icon_url(self, icon): if not icon.startswith('/') \ and not icon.startswith('http://') \ and not icon.startswith('https://'): if '/' in icon: return self.icon_static_root + icon else: return self.icon_theme_root + ic...
Replaces the "icon name" with a full usable URL. * When the icon is an absolute URL, it is used as-is. * When the icon contains a slash, it is relative from the ``STATIC_URL``. * Otherwise, it's relative to the theme url folder.
train
https://github.com/django-fluent/django-fluent-dashboard/blob/aee7ef39e0586cd160036b13b7944b69cd2b4b8c/fluent_dashboard/modules.py#L176-L192
null
class AppIconList(modules.AppList): """ The list of applications, icon style. .. image:: /images/appiconlist.png :width: 471px :height: 124px :alt: AppIconList module for django-fluent-dashboard It uses the ``FLUENT_DASHBOARD_APP_ICONS`` setting to find application icons. """ ...