code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return self.request('post', url, data=data, **kwargs) | def post(self, url, data=None, **kwargs) | Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
:param **kwargs: Optional arguments that ``request`` takes. | 4.506377 | 5.44341 | 0.827859 |
return self.request('put', url, data=data, **kwargs) | def put(self, url, data=None, **kwargs) | Sends a PUT request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
:param **kwargs: Optional arguments that ``request`` takes. | 4.700102 | 5.439577 | 0.864057 |
return self.request('patch', url, data=data, **kwargs) | def patch(self, url, data=None, **kwargs) | Sends a PATCH request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.
:param **kwargs: Optional arguments that ``request`` takes. | 5.731892 | 7.216551 | 0.79427 |
print('Starting simulations...')
for i in range(self.num_trials):
print('---Trial {}---'.format(i))
self.run_trial(i)
print('Simulation completed.') | def run_simulation(self) | Runs the complete simulation | 4.167023 | 4.047504 | 1.029529 |
# Set-up trial environment and graph
self.env = NetworkEnvironment(self.G.copy(), initial_time=0, **self.environment_params)
# self.G = self.initial_topology.copy()
# self.trial_params = deepcopy(self.global_params)
# Set up agents on nodes
print('Setting up age... | def run_trial(self, trial_id=0) | Run a single trial of the simulation
Parameters
----------
trial_id : int | 5.086837 | 5.179579 | 0.982095 |
for i in self.env.G.nodes():
self.env.G.node[i]['agent'] = self.agent_type(environment=self.env, agent_id=i,
state=deepcopy(self.initial_states[i])) | def setup_network_agents(self) | Initializes agents on nodes of graph and registers them to the SimPy environment | 3.960945 | 3.482876 | 1.137263 |
n = A.size[0]
assert A.size[1] == n, "A must be a square matrix"
assert type(A) is spmatrix, "A must be a sparse matrix"
if ve is None:
ve = n-1
else:
assert type(ve) is int and 0<=ve<n,\
"ve must be an integer between 0 and A.size[0]-1"
As = symmetrize(A)
cp,... | def maxchord(A, ve = None) | Maximal chordal subgraph of sparsity graph.
Returns a lower triangular sparse matrix which is the projection
of :math:`A` on a maximal chordal subgraph and a perfect
elimination order :math:`p`. Only the
lower triangular part of :math:`A` is accessed. The
optional argument `ve` is the index of the ... | 3.49317 | 3.35146 | 1.042283 |
# ensure correct amout of slashes
def apiurl(route):
return '/'.join(s.strip('/') for s in ["", BASE_URL, route])
return add_senaite_route(apiurl(route), endpoint, **kw) | def add_route(route, endpoint=None, **kw) | Add a new JSON API route | 12.86969 | 12.52477 | 1.027539 |
config.out_file = out_file
config.verbose = verbose
config.in_file = in_file
config.out_file = out_file | def cli(config, in_file, out_file, verbose) | Main Interface to generate xml documents
from custom dictionaries using legal xsd files
complying with legal documents in all countires
around the world. | 2.365721 | 3.114265 | 0.75964 |
# TODO: look for a secure option for eval.
# Or simply the CLI only should manage json?
# TODO: Implement json option also.
dict_input = eval(config.in_file.read())
invoice = cfdv32.get_invoice(dict_input)
if invoice.valid:
config.out_file.write(invoice.document)
confi... | def cfdv32mx(config) | Format cfdi v3.2 for Mexico.
\b
File where the files will be written document.xml.
cfdicli --in_file /path/to/yout/json/documnt.json cfdv32mx
\b
File where the files will be written from document.json.
cfdicli --out_file ./document.xml cfdv32mx | 8.732309 | 8.801465 | 0.992143 |
if callable(key_prefix):
cache_key = key_prefix()
elif '%s' in key_prefix:
cache_key = key_prefix % request.path
else:
cache_key = key_prefix
cache_key = cache_key.encode('utf-8')
return cache_key | def _make_cache_key(key_prefix) | Make cache key from prefix
Borrowed from Flask-Cache extension | 2.359317 | 2.359629 | 0.999868 |
while self.keep_listening:
try:
frame = self.queue.get(False, timeout=queue_timeout)
return (frame, pyaudio.paContinue)
except Empty:
pass
return (None, pyaudio.paComplete) | def get_frame(self, in_data, frame_count, time_info, status) | Callback function for the pyaudio stream. Don't use directly. | 3.506012 | 3.440251 | 1.019115 |
self.keep_listening = False
self.stream.stop_stream()
self.stream.close()
self.pa.terminate() | def close_stream(self) | Closes the stream. Performs cleanup. | 3.151217 | 3.131808 | 1.006197 |
'''taobao.traderate.add 新增单个评价
新增单个评价(注:在评价之前需要对订单成功的时间进行判定(end_time),如果超过15天,不能再通过该接口进行评价)'''
request = TOPRequest('taobao.traderate.add')
request['tid'] = tid
request['result'] = result
request['role'] = role
if oid!=None: request['oid'] = oid
i... | def add(self, tid, result, role, session, oid=None, content=None, anony=None) | taobao.traderate.add 新增单个评价
新增单个评价(注:在评价之前需要对订单成功的时间进行判定(end_time),如果超过15天,不能再通过该接口进行评价) | 5.377264 | 2.071861 | 2.595378 |
'''taobao.traderates.get 搜索评价信息
搜索评价信息,只能获取距今180天内的评价记录'''
request = TOPRequest('taobao.traderates.get')
request['rate_type'] = rate_type
request['role'] = role
if not fields:
tradeRate = TradeRate()
fields = tradeRate.fields
reque... | def get(self, rate_type, role, session, fields=[], **kwargs) | taobao.traderates.get 搜索评价信息
搜索评价信息,只能获取距今180天内的评价记录 | 4.905318 | 2.937475 | 1.66991 |
'''taobao.traderates.search 商品评价查询接口
通过商品id查询对应的评价信息'''
request = TOPRequest('taobao.traderates.search')
request['num_iid'] = num_iid
request['seller_nick'] = seller_nick
request['page_no'] = page_no
request['page_size'] = page_size
self.create(se... | def search(self, num_iid, seller_nick, page_no=1, page_size=20) | taobao.traderates.search 商品评价查询接口
通过商品id查询对应的评价信息 | 4.239954 | 2.31656 | 1.83028 |
'''taobao.itemcats.authorize.get 查询B商家被授权品牌列表和类目列表'''
sellerAuthorize = SellerAuthorize()
request = TOPRequest('taobao.authorize.get')
if not fields:
fields = sellerAuthorize.fields
request['fields'] = ','.join(fields)
self.create(self.execute(request, session... | def authorize_get(self, session, fields=[]) | taobao.itemcats.authorize.get 查询B商家被授权品牌列表和类目列表 | 9.186649 | 4.26103 | 2.155969 |
'''taobao.itemcats.get 获取后台供卖家发布商品的标准商品类目'''
request = TOPRequest('taobao.itemcats.get')
if not fields:
itemCat = ItemCat()
fields = itemCat.fields
request['fields'] = fields
if parent_cid!=None:
request['parent_cid'] = parent_cid
if ci... | def get(self, parent_cid=None, cids=[], fields=[]) | taobao.itemcats.get 获取后台供卖家发布商品的标准商品类目 | 4.566573 | 2.867659 | 1.592439 |
'''taobao.itemprops.get 获取标准商品类目属性
Q:能否通过图形化界面获取特定类目下面的属性及属性值?
A:请点击属性工具,通过图形化界面直接获取上述数据
Q:关键属性,非关键属性,销售属性有什么区别? A:产品的关键属性是必填的,关键属性+类目id确定一个产品,非关键属性,是分类上除了关键属性和销售属性以外的属性。销售属性是只有一件实物的商品才能确定的一个属性,如:N73 红色,黑色。没有实物不能确定。
Q:销售属性与SKU之间有何关联?
A:销售属性是组成SKU的特殊属性,它会影响买家的... | def get(self, cid, fields=[], **kwargs) | taobao.itemprops.get 获取标准商品类目属性
Q:能否通过图形化界面获取特定类目下面的属性及属性值?
A:请点击属性工具,通过图形化界面直接获取上述数据
Q:关键属性,非关键属性,销售属性有什么区别? A:产品的关键属性是必填的,关键属性+类目id确定一个产品,非关键属性,是分类上除了关键属性和销售属性以外的属性。销售属性是只有一件实物的商品才能确定的一个属性,如:N73 红色,黑色。没有实物不能确定。
Q:销售属性与SKU之间有何关联?
A:销售属性是组成SKU的特殊属性,它会影响买家的购买和卖家的库存管理,... | 11.459412 | 1.853461 | 6.18271 |
'''taobao.itempropvalues.get 获取标准类目属性值
传入类目ID,必需是叶子类目,通过taobao.itemcats.get获取类目ID 返回字段目前支持有:cid,pid,prop_name,vid,name,name_alias,status,sort_order 作用:获取标准类目属性值'''
request = TOPRequest('taobao.itempropvalues.get')
if not fields:
propValue = PropValue()
fi... | def get(self, cid, pvs=None, fields=[]) | taobao.itempropvalues.get 获取标准类目属性值
传入类目ID,必需是叶子类目,通过taobao.itemcats.get获取类目ID 返回字段目前支持有:cid,pid,prop_name,vid,name,name_alias,status,sort_order 作用:获取标准类目属性值 | 8.244162 | 2.367957 | 3.48155 |
'''Sort a list of dictionaries by dictionary key'''
return sorted(data, key=itemgetter(key)) if data else [] | def sort_dict(self, data, key) | Sort a list of dictionaries by dictionary key | 5.915051 | 5.330675 | 1.109625 |
'''taobao.wangwang.eservice.avgwaittime.get 平均等待时长
根据客服ID和日期,获取该客服"当日接待的所有客户的平均等待时长"。 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"当日接待的所有客户的平均等待时长"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"当日接待的所有客户的平均等待时长"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"当日接待的所有客户的平均等待时长"。
- 4、被查者ID可以是多个,用 "... | def avgwaittime_get(self, service_staff_id, start_date, end_date, session) | taobao.wangwang.eservice.avgwaittime.get 平均等待时长
根据客服ID和日期,获取该客服"当日接待的所有客户的平均等待时长"。 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"当日接待的所有客户的平均等待时长"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"当日接待的所有客户的平均等待时长"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"当日接待的所有客户的平均等待时长"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能... | 5.184436 | 1.478968 | 3.505443 |
'''taobao.wangwang.eservice.chatpeers.get 获取聊天对象列表,查询时间段<=7天,只支持xml返回
获取聊天对象列表,查询时间段<=7天,只支持xml返回'''
request = TOPRequest('taobao.wangwang.eservice.chatlog.get')
request['chat_id'] = chat_id
request['charset'] = charset
request['start_date'] = start_date
... | def chatlogs_get(self, chat_id, start_date, end_date, charset, session) | taobao.wangwang.eservice.chatpeers.get 获取聊天对象列表,查询时间段<=7天,只支持xml返回
获取聊天对象列表,查询时间段<=7天,只支持xml返回 | 5.271122 | 2.276646 | 2.315301 |
'''taobao.wangwang.eservice.chatpeers.get 获取聊天对象列表,查询时间段<=7天,只支持xml返回'''
request = TOPRequest('taobao.wangwang.eservice.chatpeers.get')
request['from_id'] = from_id
request['to_id'] = to_id
request['start_date'] = start_date
request['end_date'] = end_date
self.cre... | def chatpeers_get(self, from_id, to_id, start_date, end_date, session) | taobao.wangwang.eservice.chatpeers.get 获取聊天对象列表,查询时间段<=7天,只支持xml返回 | 4.548621 | 2.169755 | 2.096376 |
'''taobao.wangwang.eservice.chatrecord.get 聊天记录查询
该接口会返回一个聊天记录的下载地址。 请于5分钟以后使用该链接下载(因为文件大小的不同,生成日志的时间会延长到50分钟),该链接有如下限制:
- 1.该链接的有效期为3个小时,逾期作废。
- 2.同一链接只能使用一次。
用户点击地址,下载聊天记录压缩包(压缩包中含有1个文件或多个文件,查询了几个用户的聊天记录,就含有几个文本文件)。 备注:
- 1、如果是操作者I... | def chatrecord_get(self, service_staff_id, start_date, end_date, session) | taobao.wangwang.eservice.chatrecord.get 聊天记录查询
该接口会返回一个聊天记录的下载地址。 请于5分钟以后使用该链接下载(因为文件大小的不同,生成日志的时间会延长到50分钟),该链接有如下限制:
- 1.该链接的有效期为3个小时,逾期作废。
- 2.同一链接只能使用一次。
用户点击地址,下载聊天记录压缩包(压缩包中含有1个文件或多个文件,查询了几个用户的聊天记录,就含有几个文本文件)。 备注:
- 1、如果是操作者ID=被查者ID,返回被... | 7.354952 | 1.333367 | 5.516075 |
'''taobao.wangwang.eservice.evals.get 获取评价详细
根据用户id查询用户对应的评价详细情况, 主账号id可以查询店铺内子账号的评价 组管理员可以查询组内账号的评价 非管理员的子账号可以查自己的评价'''
request = TOPRequest('taobao.wangwang.eservice.evals.get')
request['service_staff_id'] = service_staff_id
request['start_date'] = start_date
r... | def evals_get(self, service_staff_id, start_date, end_date, session) | taobao.wangwang.eservice.evals.get 获取评价详细
根据用户id查询用户对应的评价详细情况, 主账号id可以查询店铺内子账号的评价 组管理员可以查询组内账号的评价 非管理员的子账号可以查自己的评价 | 6.620142 | 2.197708 | 3.012294 |
'''taobao.wangwang.eservice.evaluation.get 客服评价统计
根据操作者ID,返回被查者ID指定日期内每个帐号每日的"客服评价统计" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"客服评价统计"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"客服评价统计"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"客服评价统计"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。
- 5、... | def evaluation_get(self, service_staff_id, start_date, end_date, session) | taobao.wangwang.eservice.evaluation.get 客服评价统计
根据操作者ID,返回被查者ID指定日期内每个帐号每日的"客服评价统计" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"客服评价统计"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"客服评价统计"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"客服评价统计"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。
- 5、开始时间与结束时间之间... | 5.502873 | 1.549275 | 3.551903 |
'''taobao.wangwang.eservice.groupmember.get 获取组成员列表
用某个组管理员账号查询,返回该组组名、和该组所有组成员ID(E客服的分流设置)。 用旺旺主帐号查询,返回所有组的组名和该组所有组成员ID。 返回的组成员ID可以是多个,用 "," 隔开。 被查者ID只能传入一个。 组成员中排名最靠前的ID是组管理员ID'''
request = TOPRequest('taobao.wangwang.eservice.groupmember.get')
request['manager_id'] = manager_... | def groupmember_get(self, manager_id, session) | taobao.wangwang.eservice.groupmember.get 获取组成员列表
用某个组管理员账号查询,返回该组组名、和该组所有组成员ID(E客服的分流设置)。 用旺旺主帐号查询,返回所有组的组名和该组所有组成员ID。 返回的组成员ID可以是多个,用 "," 隔开。 被查者ID只能传入一个。 组成员中排名最靠前的ID是组管理员ID | 11.571832 | 1.937059 | 5.973917 |
'''taobao.wangwang.eservice.loginlogs.get 获取登录日志
通过用户id查询用户自己或者子账户的登录日志: 主账号可以查询自己和店铺子账户的登录日志 组管理员可以查询自己和组内子账号的登录日志 非组管理员的子账户只能查询自己的登录日志'''
request = TOPRequest('taobao.wangwang.eservice.loginlogs.get')
request['service_staff_id'] = service_staff_id
request['start_date']... | def loginlogs_get(self, service_staff_id, start_date, end_date, session) | taobao.wangwang.eservice.loginlogs.get 获取登录日志
通过用户id查询用户自己或者子账户的登录日志: 主账号可以查询自己和店铺子账户的登录日志 组管理员可以查询自己和组内子账号的登录日志 非组管理员的子账户只能查询自己的登录日志 | 5.404851 | 2.002481 | 2.699077 |
'''taobao.wangwang.eservice.noreplynum.get 客服未回复人数
根据操作者ID,返回被查者ID指定日期内每个帐号每日的"未回复情况" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"未回复情况"(未回复人数、未回复的ID)。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"未回复情况"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"未回复情况"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。
... | def noreplynum_get(self, service_staff_id, start_date, end_date, session) | taobao.wangwang.eservice.noreplynum.get 客服未回复人数
根据操作者ID,返回被查者ID指定日期内每个帐号每日的"未回复情况" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"未回复情况"(未回复人数、未回复的ID)。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"未回复情况"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"未回复情况"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。
- 5、... | 6.218276 | 1.542755 | 4.030632 |
'''taobao.wangwang.eservice.onlinetime.get 日累计在线时长
描述:根据客服ID和日期,获取该客服"当日在线时长"。 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"当日在线时长"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"当日在线时长"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"当日在线时长"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。
- 5、日累计在线时长... | def onlinetime_get(self, service_staff_id, start_date, end_date, session) | taobao.wangwang.eservice.onlinetime.get 日累计在线时长
描述:根据客服ID和日期,获取该客服"当日在线时长"。 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"当日在线时长"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"当日在线时长"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"当日在线时长"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。
- 5、日累计在线时长定义:当日该用户累计的... | 5.517099 | 1.485697 | 3.713476 |
'''taobao.wangwang.eservice.receivenum.get 客服接待数
根据操作者ID,返回被查者ID指定时间段内每个帐号的"已接待人数" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"已接待人数"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"已接待人数"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"已接待人数"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。
- 5、规则:某客服... | def receivenum_get(self, service_staff_id, start_date, end_date, session) | taobao.wangwang.eservice.receivenum.get 客服接待数
根据操作者ID,返回被查者ID指定时间段内每个帐号的"已接待人数" 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"已接待人数"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"已接待人数"。
- 3、如果操作者是主账户,他可以查询所有子帐号的"已接待人数"。
- 4、被查者ID可以是多个,用 "," 隔开,id数不能超过30。
- 5、规则:某客服在1天内和同一个客户交... | 6.544407 | 1.443635 | 4.533283 |
'''taobao.wangwang.eservice.streamweigths.get 获取分流权重接口
获取当前登录用户自己的店铺内的分流权重设置'''
request = TOPRequest('taobao.wangwang.eservice.streamweigths.get')
self.create(self.execute(request, session))
return self.staff_stream_weights | def streamweigths_get(self, session) | taobao.wangwang.eservice.streamweigths.get 获取分流权重接口
获取当前登录用户自己的店铺内的分流权重设置 | 9.320771 | 4.067159 | 2.291716 |
"If exists: Invalidate old entry and return it."
old_entry = self.access_lookup.get(key)
if old_entry:
old_entry.is_valid = False
return old_entry | def _invalidate_entry(self, key) | If exists: Invalidate old entry and return it. | 8.015659 | 4.719344 | 1.698469 |
"Push entry onto our access log, invalidate the old entry if exists."
self._invalidate_entry(key)
new_entry = AccessEntry(key)
self.access_lookup[key] = new_entry
self.access_log_lock.acquire()
self.access_log.appendleft(new_entry)
self.access_log_lock.release() | def _push_entry(self, key) | Push entry onto our access log, invalidate the old entry if exists. | 4.865624 | 2.765568 | 1.759358 |
"Pop entries from our access log until we popped ``num`` valid ones."
while num > 0:
self.access_log_lock.acquire()
p = self.access_log.pop()
self.access_log_lock.release()
if not p.is_valid:
continue # Invalidated entry, skip
... | def _prune_entries(self, num) | Pop entries from our access log until we popped ``num`` valid ones. | 6.146271 | 3.809458 | 1.613424 |
"Rebuild our access_log without the invalidated entries."
self.access_log_lock.acquire()
self.access_log = deque(e for e in self.access_log if e.is_valid)
self.access_log_lock.release() | def _prune_invalidated_entries(self) | Rebuild our access_log without the invalidated entries. | 5.514442 | 2.870871 | 1.920826 |
"Return ordered access keys for inspection. Used for testing."
self.access_log_lock.acquire()
r = [e.key for e in self.access_log if e.is_valid]
self.access_log_lock.release()
return r | def _get_ordered_access_keys(self) | Return ordered access keys for inspection. Used for testing. | 6.169635 | 4.112633 | 1.500167 |
rs = screen_res[0]/float(screen_res[1])
ri = image_res[0]/float(image_res[1])
if rs > ri:
return (int(image_res[0] * screen_res[1]/image_res[1]), screen_res[1])
else:
return (screen_res[0], int(image_res[1]*screen_res[0]/image_res[0])) | def calc_scaled_res(self, screen_res, image_res) | Calculate appropriate texture size.
Calculate size or required texture so that it will fill the window,
but retains the movies original aspect ratio.
Parameters
----------
screen_res : tuple
Display window size/Resolution
image_res : tuple
Image width and height
Returns
-------
tuple
... | 1.800962 | 1.933039 | 0.931674 |
if not os.path.exists(vidSource):
print("File not found: " + vidSource)
pygame.display.quit()
pygame.quit()
sys.exit(1)
self.decoder.load_media(vidSource)
self.decoder.loop = self.loop
pygame.display.set_caption(os.path.split(vidSource)[1])
self.vidsize = self.decoder.clip.size
self.destsiz... | def load_media(self, vidSource) | Loads a video.
Parameters
----------
vidSource : str
The path to the video file | 2.625015 | 2.699333 | 0.972468 |
# Retrieve buffer from videosink
if self.texture_locked:
return
self.buffer = frame
self.texUpdated = True | def __texUpdate(self, frame) | Update the texture with the newly supplied frame. | 12.795575 | 12.167618 | 1.051609 |
# Signal player to start video playback
self.paused = False
# Start listening for incoming audio frames
if self.decoder.audioformat:
self.audio.start()
self.decoder.play()
# While video is playing, render frames
while self.decoder.status in [mediadecoder.PLAYING, mediadecoder.PAUSED]:
texture_... | def play(self) | Starts playback. | 2.834153 | 2.844053 | 0.996519 |
if self.decoder.status == mediadecoder.PAUSED:
self.decoder.pause()
self.paused = False
elif self.decoder.status == mediadecoder.PLAYING:
self.decoder.pause()
self.paused = True
else:
print("Player not in pausable state") | def pause(self) | Pauses playback. | 3.35355 | 3.21678 | 1.042518 |
ansi_code = [getattr(colorama.Fore, color.upper()), colorama.Fore.RESET]
return lambda msg: msg.join(ansi_code) | def fg(color) | Foreground color formatter function factory.
Each function casts from a unicode string to a colored bytestring
with the respective foreground color and foreground reset ANSI
escape codes. You can also use the ``fg.color`` or ``fg[color]``
directly as attributes/items.
The colors are the names of t... | 7.330924 | 8.599689 | 0.852464 |
logger = log(color)
return lambda symbol: logger(symbol * terminal_size.usable_width) | def hr(color) | Colored horizontal rule printer/logger factory.
The resulting function prints an entire terminal row with the given
symbol repeated. It's a terminal version of the HTML ``<hr/>``. | 29.943256 | 18.843912 | 1.589015 |
logger = log(color)
return lambda msg: logger(centralize(msg).rstrip()) | def clog(color) | Same to ``log``, but this one centralizes the message first. | 18.403049 | 11.871628 | 1.550171 |
for method_name, args in self.strategies:
method = getattr(self, "from_" + method_name)
width = method(*args)
if width and width > 0:
self.width = width
break # Found!
os.environ["COLUMNS"] = str(self.width) | def retrieve_width(self, signum=None, frame=None) | Stores the terminal width into ``self.width``, if possible.
This function is also the SIGWINCH event handler. | 4.78405 | 4.350382 | 1.099685 |
import fcntl, termios, array
winsize = array.array("H", [0] * 4) # row, col, xpixel, ypixel
if not fcntl.ioctl(fobj.fileno(), termios.TIOCGWINSZ, winsize, True):
return winsize[1] | def from_io_control(fobj) | Call TIOCGWINSZ (Terminal I/O Control to Get the WINdow SiZe)
where ``fobj`` is a file object (e.g. ``sys.stdout``),
returning the terminal width assigned to that file.
See the ``ioctl``, ``ioctl_list`` and tty_ioctl`` man pages
for more information. | 3.523631 | 2.956729 | 1.191733 |
from ctypes import windll, c_ushort
# https://msdn.microsoft.com/library/windows/desktop/ms683231
handle = windll.kernel32.GetStdHandle(std_handle)
# https://msdn.microsoft.com/library/windows/desktop/ms682093
info = (c_ushort * 11)() # It's a CONSOLE_SCREEN_BUFFER_INFO:... | def from_windows_handle(std_handle) | Use the Windows Console Handles API to get the console width,
where ``std_handle`` is the WINAPI ``GetStdHandle`` input
(e.g. STD_INPUT_HANDLE).
https://msdn.microsoft.com/library/windows/desktop/ms682075 | 3.769471 | 3.568342 | 1.056365 |
try:
connection = Connection(host=config['host'], region=config['region'])
filename = ".".join([config['table_name'], str(part), "dump"])
if config['compress']:
opener = gzip.GzipFile
filename += ".gz"
else:
opener = open
dumper = Ba... | def dump_part(part, total_segments=None) | 'part' may be the hash_key if we are dumping just a few hash_keys - else
it will be the segment number | 3.621286 | 3.43073 | 1.055544 |
if self.sample_type == SampleType.S16NativeEndian:
# Sample size is 2 bytes
return self.sample_size * self.channels
else:
raise ValueError('Unknown sample type: %d', self.sample_type) | def frame_size(self) | The byte size of a single frame of this format. | 6.507327 | 5.948906 | 1.09387 |
def decorate(cls):
def _add(index, name):
def _set_dir(self, value): getattr(self, store_name)[index] = value
def _get_dir(self): return getattr(self, store_name)[index]
setattr(cls, name, property(_get_dir, _set_dir))
for index, field_name in enumerate(fiel... | def add_fields(store_name, field_names) | A class-decorator that creates layout managers with a set of named
fields. | 2.763892 | 2.626582 | 1.052277 |
min_width = 0
min_height = 0
for element in self.elements:
if not element: continue
size = element.get_minimum_size(data)
min_width = max(min_width, size.x)
min_height = max(min_height, size.y)
return datatypes.Point(min_width, min... | def _get_smallest_dimensions(self, data) | A utility method to return the minimum size needed to fit
all the elements in. | 2.55843 | 2.283629 | 1.120335 |
return self._set(instance, value, **kw) | def set(self, instance, value, **kw) | Set the value of the field | 4.897767 | 5.792569 | 0.845526 |
value = self.get(instance)
return value or default | def json_data(self, instance, default=None) | Get a JSON compatible value | 12.061095 | 10.72537 | 1.124539 |
logger.debug("DexterityFieldManager::set: value=%r" % value)
# Check if the field is read only
if self.field.readonly:
raise Unauthorized("Field is read only")
fieldname = self.get_field_name()
# id fields take only strings
if fieldname == "id":
... | def _set(self, instance, value, **kw) | Set the value of the field | 5.248703 | 4.8878 | 1.073837 |
logger.debug("DexterityFieldManager::get: instance={} field={}"
.format(instance, self.field))
# TODO: Check security on the field level
return self.field.get(instance) | def _get(self, instance, **kw) | Get the value of the field | 12.074725 | 10.770088 | 1.121135 |
value = self.get(instance)
if not value:
return ""
if callable(value):
value = value()
return api.to_iso_date(value, default=default) | def json_data(self, instance, default=None) | Get a JSON compatible value | 5.779745 | 5.488746 | 1.053017 |
value = self.get(instance)
if value:
return value.output
return value | def json_data(self, instance, default=None) | Get a JSON compatible value | 10.668762 | 9.124101 | 1.169295 |
download = default
# calculate the download url
download = "{url}/@@download/{fieldname}/{filename}".format(
url=api.get_url(instance),
fieldname=self.get_field_name(),
filename=self.get_filename(instance),
)
return download | def get_download_url(self, instance, default=None) | Calculate the download url | 5.488954 | 4.745748 | 1.156605 |
value = self.get(instance)
out = []
for rel in value:
if rel.isBroken():
logger.warn("Skipping broken relation {}".format(repr(rel)))
continue
obj = rel.to_object
out.append(api.get_url_info(obj))
return out | def json_data(self, instance, default=None) | Get a JSON compatible value | 7.347764 | 7.014241 | 1.047549 |
logger.debug("ATFieldManager::set: value=%r" % value)
# check field permission
if not self.field.checkPermission("write", instance):
raise Unauthorized("You are not allowed to write the field {}"
.format(self.name))
# check if field i... | def _set(self, instance, value, **kw) | Set the value of the field | 5.933552 | 5.680548 | 1.044539 |
logger.debug("ATFieldManager::get: instance={} field={}"
.format(instance, self.field))
# check the field permission
if not self.field.checkPermission("read", instance):
raise Unauthorized("You are not allowed to read the field {}"
... | def _get(self, instance, **kw) | Get the value of the field | 5.49243 | 4.966938 | 1.105798 |
# Gracefully avoid programming errors in Computed fields
try:
return self._get(instance, **kw)
except AttributeError:
logger.error("Could not get the value of the computed field '{}'"
.format(self.get_field_name()))
return Non... | def get(self, instance, **kw) | Get the value of the field | 6.775049 | 6.922112 | 0.978755 |
if value:
try:
value = DateTime(value)
except SyntaxError:
logger.warn("Value '{}' is not a valid DateTime string"
.format(value))
return False
self._set(instance, value, **kw) | def set(self, instance, value, **kw) | Converts the value into a DateTime object before setting. | 4.465956 | 3.614333 | 1.235624 |
value = self.get(instance)
return api.to_iso_date(value) or default | def json_data(self, instance, default=None) | Get a JSON compatible value | 15.422698 | 13.279002 | 1.161435 |
filename = self.field.getFilename(instance)
if filename:
return filename
fieldname = self.get_field_name()
content_type = self.get_content_type(instance)
extension = mimetypes.guess_extension(content_type)
return fieldname + extension | def get_filename(self, instance) | Get the filename | 3.465095 | 3.240462 | 1.069321 |
download = default
# calculate the download url
download = "{url}/at_download/{fieldname}".format(
url=instance.absolute_url(), fieldname=self.get_field_name())
return download | def get_download_url(self, instance, default=None) | Calculate the download url | 9.89295 | 7.82174 | 1.264802 |
value = str(value).decode("base64")
# handle the filename
if "filename" not in kw:
logger.debug("FielFieldManager::set: No Filename detected "
"-> using title or id")
kw["filename"] = kw.get("id") or kw.get("title")
self._set(in... | def set(self, instance, value, **kw) | Decodes base64 value and set the file object | 8.206557 | 7.351355 | 1.116333 |
ref.append(api.get_object_by_uid(value))
# The value is already an object
if api.is_at_content(value):
ref.append(value)
# The value is a dictionary
# -> handle it like a catalog query
if u.is_dict(value):
results = api.search(portal_type=sel... | def set(self, instance, value, **kw): # noqa
ref = []
# The value is an UID
if api.is_uid(value) | Set the value of the refernce field | 2.429789 | 2.369929 | 1.025258 |
value = self.get(instance)
if value and self.is_multi_valued():
return map(api.get_url_info, value)
elif value and not self.is_multi_valued():
return api.get_url_info(value)
return value or default | def json_data(self, instance, default=None) | Get a JSON compatible value | 4.18695 | 4.005211 | 1.045375 |
proxy_object = self.get_proxy_object(instance)
if not proxy_object:
return None
return proxy_object.getField(self.name) | def get_proxy_field(self, instance) | Get the proxied field of this field | 3.530887 | 3.010081 | 1.17302 |
proxy_field = self.get_proxy_field(instance)
if proxy_field is None:
return None
# set the field with the proper field manager of the proxy field
fieldmanager = IFieldManager(proxy_field)
return fieldmanager.set(instance, value, **kw) | def set(self, instance, value, **kw) | Set the value of the (proxy) field | 4.735735 | 4.033204 | 1.174187 |
value = self.get(instance)
out = map(api.get_url_info, value)
return out or default | def json_data(self, instance, default=[]) | Get a JSON compatible value | 13.985617 | 13.047513 | 1.071899 |
if not isinstance(value, (list, tuple)):
value = [value]
uids = []
for item in value:
uid = None
if isinstance(item, dict):
uid = item.get("uid")
if api.is_uid(value):
uid = item
if uid is None... | def set(self, instance, value, **kw) | Set Analyses to an AR
:param instance: Analysis Request
:param value: Single AS UID or a list of dictionaries containing AS UIDs
:param kw: Additional keyword parameters passed to the field | 3.558798 | 3.237858 | 1.099121 |
ref.append(value)
# The value is a dictionary, get the UIDs.
if u.is_dict(value):
ref = ref.append(value.get("uid"))
# The value is already an object
if api.is_at_content(value):
ref.append(value)
# The value is a list
if u.is_list(v... | def set(self, instance, value, **kw): # noqa
ref = []
# The value is an UID
if api.is_uid(value) | Set the value of the uid reference field | 3.698448 | 3.556757 | 1.039837 |
assert isinstance(X, cspmatrix) and X.is_factor is False, "X must be a cspmatrix"
n = X.symb.n
snpost = X.symb.snpost
snptr = X.symb.snptr
chptr = X.symb.chptr
chidx = X.symb.chidx
relptr = X.symb.relptr
relidx = X.symb.relidx
blkptr = X.symb.blkptr
blkval = X.blkval
... | def cholesky(X) | Supernodal multifrontal Cholesky factorization:
.. math::
X = LL^T
where :math:`L` is lower-triangular. On exit, the argument :math:`X`
contains the Cholesky factor :math:`L`.
:param X: :py:class:`cspmatrix` | 3.922759 | 3.799005 | 1.032575 |
# 1. extract the schema fields
data = self.extract_fields()
# 2. include custom key-value pairs listed in the mapping dictionary
for key, attr in self.attributes.iteritems():
if key in self.ignore:
continue # skip ignores
# fetch the ma... | def to_dict(self) | extract the data of the content and return it as a dictionary | 5.82325 | 5.468199 | 1.06493 |
# get the proper data manager for the object
dm = IDataManager(self.context)
# filter out ignored fields
fieldnames = filter(lambda name: name not in self.ignore, self.keys)
# schema mapping
out = dict()
for fieldname in fieldnames:
try:
... | def extract_fields(self) | Extract the given fieldnames from the object
:returns: Schema name/value mapping
:rtype: dict | 5.482883 | 5.15751 | 1.063087 |
path = self.context.getPath()
portal_path = api.get_path(api.get_portal())
if portal_path not in path:
return "{}/{}".format(portal_path, path)
return path | def _x_get_physical_path(self) | Generate the physical path | 6.806363 | 6.221407 | 1.094023 |
UNDER, LETTER, OTHER = object(), object(), object()
def group_key_function(char):
if char == "_":
return UNDER
if char in string.ascii_letters:
return LETTER
return OTHER
def process_group(idx, key, chars):
if key is LETTER:
return "".... | def snake2ucamel(value) | Casts a snake_case string to an UpperCamelCase string. | 3.651917 | 3.70787 | 0.98491 |
def __missing__(self, key):
result = self[key] = func(key)
return result
wrapper = type(snake2ucamel(func.__name__), (dict,), {
"__missing__": __missing__,
"__call__": dict.__getitem__,
"__getattr__": dict.__getitem__,
"__doc__": func.__doc__, # Class docstring can't... | def attr_item_call_auto_cache(func) | Decorator for a a single positional argument function to cache
its results and to make ``f("a") == f["a"] == f.a``. | 4.84194 | 4.609467 | 1.050434 |
frame_locals = inspect.currentframe().f_back.f_locals
frame_locals[snake2ucamel(func.__name__)] = func
return func | def ucamel_method(func) | Decorator to ensure the given snake_case method is also written in
UpperCamelCase in the given namespace. That was mainly written to
avoid confusion when using wxPython and its UpperCamelCaseMethods. | 4.29591 | 4.937399 | 0.870076 |
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for actual_name, kwarg_rename in kws.items():
if kwarg_rename in kwargs:
kwargs[actual_name] = kwargs[kwarg_rename]
del kwargs[kwarg_rename]
... | def kw_map(**kws) | Decorator for renamed keyword arguments, given a keyword argument
mapping "actual_name: kwarg_rename" for each keyword parameter to
be renamed. | 2.241477 | 1.547105 | 1.44882 |
with io.open(fname, encoding=encoding) as f:
result = list(f)
if result:
if result[-1][-1:] == "\n":
result.append("\n")
else:
result[-1] += "\n"
return [line[:-1] for line in result]
return [] | def read_plain_text(fname, encoding="utf-8") | Reads a file as a list of strings. | 2.83937 | 2.83083 | 1.003017 |
n = A.size[0]
assert A.size[1] == n, "A must be a square matrix"
assert type(A) is spmatrix, "A must be a sparse matrix"
if ve is None:
ve = n-1
else:
assert type(ve) is int and 0<=ve<n,\
"ve must be an integer between 0 and A.size[0]-1"
As = symmetrize(A... | def maxcardsearch(A, ve = None) | Maximum cardinality search ordering of a sparse chordal matrix.
Returns the maximum cardinality search ordering of a symmetric
chordal matrix :math:`A`. Only the lower triangular part of
:math:`A` is accessed. The maximum cardinality search ordering
is a perfect elimination ordering in the factorizatio... | 3.921456 | 3.695394 | 1.061174 |
import logging
logger = logging.getLogger('spotify-connect')
handler = logging.NullHandler()
logger.addHandler(handler) | def _setup_logging() | Setup logging to log to nowhere by default.
For details, see:
http://docs.python.org/3/howto/logging.html#library-config
Internal function. | 5.545287 | 5.761194 | 0.962524 |
import functools
@functools.wraps(f)
def wrapper(*args, **kwargs):
with _lock:
return f(*args, **kwargs)
if not hasattr(wrapper, '__wrapped__'):
# Workaround for Python < 3.2
wrapper.__wrapped__ = f
return wrapper | def serialized(f) | Decorator that serializes access to all decorated functions.
The decorator acquires pyspotify's single global lock while calling any
wrapped function. It is used to serialize access to:
- All calls to functions on :attr:`spotify.lib`.
- All code blocks working on pointers returned from functions on
... | 2.898477 | 3.116438 | 0.930061 |
pages = {
(False, False):[2,3,4,5,1,8,7,6],
(False, True):[4,5,6,7,3,2,1,8],
(True, False):[5,4,3,2,6,7,8,1],
(True, True):[7,6,5,4,8,1,2,3]
}[page_edge_bottom, first_page_vertical]
output = []
num_pages = len(elements)
for index in range(0, num_pages, 8):
... | def get_pocketmod_pages(elements,
page_edge_bottom=True,
first_page_vertical=True) | Creates one or more managers that wraps the given elements into
one or more Pocket Mod-style page sets. Each manager in the list
that is returned corresponds to one page. This imposer is designed
to work with portrait oriented content pages, laid out onto a
landscape oriented page.
Arguments:
... | 3.082298 | 3.271559 | 0.94215 |
with self._close_lock:
epfd = self._epfd
if epfd >= 0:
self._epfd = -1
close(epfd) | def close(self) | Close the internal epoll file descriptor if it isn't closed
:raises OSError:
If the underlying ``close(2)`` fails. The error message matches
those found in the manual page. | 4.781229 | 4.714565 | 1.01414 |
if fd < 0:
_err_closed()
self = cls.__new__()
object.__init__(self)
self._epfd = fd
return self | def fromfd(cls, fd) | Create a new epoll object from a given file descriptor
:param fd:
A pre-made file descriptor obtained from ``epoll_create(2)`` or
``epoll_create1(2)``
:raises ValueError:
If fd is not a valid file descriptor
:returns:
A new epoll object
.... | 7.534548 | 12.576295 | 0.599107 |
if self._epfd < 0:
_err_closed()
if eventmask is None:
eventmask = EPOLLIN | EPOLLOUT | EPOLLPRI
ev = epoll_event()
ev.events = eventmask
ev.data.fd = fd
epoll_ctl(self._epfd, EPOLL_CTL_ADD, fd, byref(ev)) | def register(self, fd, eventmask=None) | Register a new descriptor
:param fd:
The descriptor to register.
:param eventmask:
Bit-mask of events that will be monitored. By default EPOLLIN,
EPOLLOUT and EPOLLPRI are used. Note that EPOLLHUP is implicit and
doesn't need to be provided.
:rais... | 3.836067 | 3.777294 | 1.01556 |
if self._epfd < 0:
_err_closed()
ev = epoll_event()
try:
epoll_ctl(self._epfd, EPOLL_CTL_DEL, fd, byref(ev))
except OSError as exc:
# Allow fd to be closed, matching Python 3.4
if exc.errno != EBADF:
raise | def unregister(self, fd) | Unregister a previously registered descriptor
:param fd:
The descriptor to unregister
:raises ValueError:
If :meth:`closed()` is True
:raises OSError:
If the underlying ``epoll_ctl(2)`` fails. The error message matches
those found in the manual pa... | 5.619536 | 5.628098 | 0.998479 |
if self._epfd < 0:
_err_closed()
ev = epoll_event()
ev.events = eventmask
ev.data.fd = fd
epoll_ctl(self._epfd, EPOLL_CTL_MOD, fd, byref(ev)) | def modify(self, fd, eventmask) | Change the bit-mask of events associated with a previously-registered
descriptor.
:param fd:
The descriptor to modify.
:param eventmask:
New bit-mask of events that will be monitored.
:raises ValueError:
If :meth:`closed()` is True
:raises OSE... | 5.987498 | 6.049801 | 0.989702 |
if self._epfd < 0:
_err_closed()
if timeout != -1:
# 1000 because epoll_wait(2) uses milliseconds
timeout = int(timeout * 1000)
if maxevents == -1:
maxevents = FD_SETSIZE - 1
events = (epoll_event * maxevents)()
num_events ... | def poll(self, timeout=-1, maxevents=-1) | Poll for events
:param timeout:
The amount of seconds to wait for events before giving up. The
default value, -1, represents infinity. Note that unlike the
underlying ``epoll_wait()`` timeout is a fractional number
representing **seconds**.
:param maxeven... | 3.910004 | 3.532014 | 1.107018 |
if isinstance(path, UNICODE):
return path
return path.decode(sys.getfilesystemencoding(), errors) | def to_unicode(path, errors="replace") | Given a bytestring/unicode path, return it as unicode. | 4.464234 | 3.959752 | 1.127403 |
if template_name is None or '.' not in template_name:
return False
ext = template_name.rsplit('.', 1)[1]
return ext in ('html', 'xhtml', 'htm', 'xml') | def guess_autoescape(self, template_name) | Given a template Name I will gues using its
extension if we should autoscape or not.
Default autoscaped extensions: ('html', 'xhtml', 'htm', 'xml') | 2.770034 | 2.201681 | 1.258145 |
# TODO: be able to get doc for error given an xsd.
# Changed path to allow have xsd that are imported by others xsd in the
# same library, and not call to SAT page each time that is generated
# a new XML.
with change_path():
path = os.path.join(
... | def validate(self, schema_str, xml_valid) | Compare the valid information on an xml from given schema.
:param str schema_str: content string from schema file.
:param str xml_valid: content string from xml file.
:returns: If it is Valid or Not.
:rtype: bool | 6.506081 | 6.428404 | 1.012083 |
cached = StringIO()
document = u''
try:
document = self.template.render(inv=self)
except UndefinedError as ups:
self.ups = ups
# TODO: Here should be called the cleanup 'Just before the validation'.
valid = self.validate(self.schema, docu... | def set_xml(self) | Set document xml just rendered already
validated against xsd to be signed.
:params boolean debug_mode: Either if you want
the rendered template to be saved either it
is valid or not with the given schema.
:returns boolean: Either was valid or not the generated document. | 8.995279 | 8.229794 | 1.093014 |
element = element.split('}')[-1]
xpath_path = \
'//xs:element[@name="{element}"]' + \
'/xs:annotation/xs:documentation'.format(element=element)
return xpath_path | def get_element_from_clark(self, element) | **Helper method:** Given a Clark's Notation
`{url:schema}Element` element, return the
valid xpath on your xsd file, frequently
it is not necesary overwrite this method but
different xsd from different source
can have different logic which I do not know now,
then simply ta... | 5.123397 | 4.789788 | 1.06965 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.