_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q39500 | Client.show_domain_record | train | def show_domain_record(self, domain_id, record_id):
"""
This method returns the specified domain record.
Required parameters
domain_id:
Integer or Domain Name (e.g. domain.com), specifies the domain
for which to retrieve a record.
record... | python | {
"resource": ""
} |
q39501 | Client.destroy_domain_record | train | def destroy_domain_record(self, domain_id, record_id):
"""
This method deletes the specified domain record.
Required parameters
domain_id:
Integer or Domain Name (e.g. domain.com), specifies the domain
for which to destroy a record.
reco... | python | {
"resource": ""
} |
q39502 | Client.events | train | def events(self, event_id):
"""
This method is primarily used to report on the progress of an event
by providing the percentage of completion.
Required parameters
event_id:
Numeric, this is the id of the event you would like more
information ... | python | {
"resource": ""
} |
q39503 | get_ebuio_headers | train | def get_ebuio_headers(request):
"""Return a dict with ebuio headers"""
retour = {}
for (key, value) in request.headers:
if key.startswith('X-Plugit-'):
key = key[9:]
retour[key] = value
return retour | python | {
"resource": ""
} |
q39504 | demo | train | def demo():
"""Demonstrate progress bar."""
from time import sleep
maxProgress = 1000
with ProgressBar(max=maxProgress) as progressbar:
for i in range(-100, maxProgress):
sleep(0.01)
progressbar.update(i)
progressbar2 = ProgressBar(max=maxProgress)
for s in progre... | python | {
"resource": ""
} |
q39505 | ProgressBar.show | train | def show(self):
"""Redraw the text progress bar."""
if len(self.text) > self.textwidth:
label = self.text[0:self.textwidth]
else:
label = self.text.rjust(self.textwidth)
terminalSize = getTerminalSize()
if terminalSize is None:
terminalSize =... | python | {
"resource": ""
} |
q39506 | SinkhornKnopp.fit | train | def fit(self, P):
"""Fit the diagonal matrices in Sinkhorn Knopp's algorithm
Parameters
----------
P : 2d array-like
Must be a square non-negative 2d array-like object, that
is convertible to a numpy array. The matrix must not be
equal to 0 and it must have total... | python | {
"resource": ""
} |
q39507 | request_ligodotorg | train | def request_ligodotorg(url, debug=False):
"""Request the given URL using LIGO.ORG SAML authentication.
This requires an active Kerberos ticket for the user, to get one:
$ kinit albert.einstein@LIGO.ORG
Parameters
----------
url : `str`
URL path for request
debug : `bool`, optional... | python | {
"resource": ""
} |
q39508 | publish_cat1 | train | def publish_cat1(method, con, token, cat, kwargs):
"""
Constructs a "POST" and "DELETE" URL. The function is used by the publish and delete method
First category of "POST" and "DELETE" url construction. Caling it first category because for
publishing photos or more complex stuffs, newe... | python | {
"resource": ""
} |
q39509 | get_object_cat1 | train | def get_object_cat1(con, token, cat, kwargs):
"""
Constructs the "GET" URL. The functions is used by the get_object method
First Category of "GET" URL construction. Again calling it first category because more
complex functions maybe added later.
"""
req_str = "/"+kwarg... | python | {
"resource": ""
} |
q39510 | Match.get_variables_substitution_dictionaries | train | def get_variables_substitution_dictionaries(self, lhs_graph, rhs_graph):
"""
Looks for sub-isomorphisms of rhs into lhs
:param lhs_graph: The graph to look sub-isomorphisms into (the bigger graph)
:param rhs_graph: The smaller graph
:return: The list of matching names
""... | python | {
"resource": ""
} |
q39511 | readTableFromDelimited | train | def readTableFromDelimited(f, separator="\t"):
"""
Reads a table object from given plain delimited file.
"""
rowNames = []
columnNames = []
matrix = []
first = True
for line in f.readlines():
line = line.rstrip()
if len(line) == 0:
continue
row = lin... | python | {
"resource": ""
} |
q39512 | readTableFromCSV | train | def readTableFromCSV(f, dialect="excel"):
"""
Reads a table object from given CSV file.
"""
rowNames = []
columnNames = []
matrix = []
first = True
for row in csv.reader(f, dialect):
if first:
columnNames = row[1:]
first = False
else:
... | python | {
"resource": ""
} |
q39513 | Table.cell | train | def cell(self, rowName, columnName):
"""
Returns the value of the cell on the given row and column.
"""
return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]] | python | {
"resource": ""
} |
q39514 | Table.rows | train | def rows(self):
"""
Returns a list of dicts.
"""
rows = []
for rowName in self.rowNames:
row = {columnName: self[rowName, columnName] for columnName in self.columnNames}
row["_"] = rowName
rows.append(row)
return rows | python | {
"resource": ""
} |
q39515 | init_db | train | def init_db():
"""
Drops and re-creates the SQL schema
"""
db.drop_all()
db.configure_mappers()
db.create_all()
db.session.commit() | python | {
"resource": ""
} |
q39516 | ZipWrap.load_zipfile | train | def load_zipfile(self, path):
"""
import contents of a zipfile
"""
# try to add as zipfile
zin = zipfile.ZipFile(path)
for zinfo in zin.infolist():
name = zinfo.filename
if name.endswith("/"):
self.mkdir(name)
else:
... | python | {
"resource": ""
} |
q39517 | ZipWrap.load_dir | train | def load_dir(self, path):
"""
import contents of a directory
"""
def visit_path(arg, dirname, names):
for name in names:
fpath = os.path.join(dirname, name)
new_path = fpath[len(path):]
if os.path.isfile(fpath):
... | python | {
"resource": ""
} |
q39518 | ZipWrap._rel_path | train | def _rel_path(self, path, basepath=None):
"""
trim off basepath
"""
basepath = basepath or self.src_dir
return path[len(basepath) + 1:] | python | {
"resource": ""
} |
q39519 | ZipWrap.unzip | train | def unzip(self, directory):
"""
Write contents of zipfile to directory
"""
if not os.path.exists(directory):
os.makedirs(directory)
shutil.copytree(self.src_dir, directory) | python | {
"resource": ""
} |
q39520 | GraphDatabase.query | train | def query(self, string, repeat_n_times=None):
"""
This method performs the operations onto self.g
:param string: The list of operations to perform. The sequences of commands should be separated by a semicolon
An example might be
CREATE {'tag': 'PE... | python | {
"resource": ""
} |
q39521 | GraphDatabase.__query_with_builder | train | def __query_with_builder(self, string, builder):
"""
Uses the builder in the argument to modify the graph, according to the commands in the string
:param string: The single query to the database
:return: The result of the RETURN operation
"""
action_graph_pairs = self.__... | python | {
"resource": ""
} |
q39522 | create_secret | train | def create_secret(*args, **kwargs):
"""Return a secure key generated from the user and the object. As we load elements fron any class from user imput, this prevent the user to specify arbitrary class"""
to_sign = '-!'.join(args) + '$$'.join(kwargs.values())
key = settings.SECRET_FOR_SIGNS
hashed = hm... | python | {
"resource": ""
} |
q39523 | main | train | def main():
'''i am winston wolfe, i solve problems'''
arguments = docopt(__doc__, version=__version__)
if arguments['on']:
print 'Mr. Wolfe is at your service'
print 'If any of your programs run into an error'
print 'use wolfe $l'
print 'To undo the changes made by mr wolfe in your bashrc, do wo... | python | {
"resource": ""
} |
q39524 | pesaplyMM.make_payment | train | def make_payment(self, recipient, amount, description=None):
"""
make_payment allows for automated payments.
A use case includes the ability to trigger a payment to a customer
who requires a refund for example.
You only need to provide the recipient and the amount to be transfere... | python | {
"resource": ""
} |
q39525 | pesaplyMM.get_balance | train | def get_balance(self):
"""
Retrieves the balance for the configured account
"""
self.br.open(self.MOBILE_WEB_URL % {'accountno': self.account})
try:
# Search for the existence of the Register link - indicating a new account
self.br.find_link(text='Register... | python | {
"resource": ""
} |
q39526 | pesaplyMM.get_url | train | def get_url(self, url):
"""
Internally used to retrieve the contents of a URL
"""
_r = self.br.open(url)
# check that we've not been redirected to the login page
if self.br.geturl().startswith(self.AUTH_URL):
raise AuthRequiredException
elif self.br.g... | python | {
"resource": ""
} |
q39527 | pesaplyMM.post_url | train | def post_url(self, url, form):
"""
Internally used to retrieve the contents of a URL using
the POST request method.
The `form` parameter is a mechanize.HTMLForm object
This method will use a POST request type regardless of the method
used in the `form`.
"""
... | python | {
"resource": ""
} |
q39528 | pesaplyMM._parse_transactions | train | def _parse_transactions(self, response):
"""
This method parses the CSV output in `get_transactions`
to generate a usable list of transactions that use native
python data types
"""
transactions = list()
if response:
f = StringIO(response)
... | python | {
"resource": ""
} |
q39529 | getPlugItObject | train | def getPlugItObject(hproPk):
"""Return the plugit object and the baseURI to use if not in standalone mode"""
from hprojects.models import HostedProject
try:
hproject = HostedProject.objects.get(pk=hproPk)
except (HostedProject.DoesNotExist, ValueError):
try:
hproject = Host... | python | {
"resource": ""
} |
q39530 | generate_user | train | def generate_user(mode=None, pk=None):
"""Return a false user for standalone mode"""
user = None
if mode == 'log' or pk == "-1":
user = DUser(pk=-1, username='Logged', first_name='Logged', last_name='Hector', email='logeedin@plugit-standalone.ebuio')
user.gravatar = 'https://www.gravatar.c... | python | {
"resource": ""
} |
q39531 | gen404 | train | def gen404(request, baseURI, reason, project=None):
"""Return a 404 error"""
return HttpResponseNotFound(
render_to_response('plugIt/404.html', {'context':
{
'reason': reason,
'ebuio_baseUrl': baseURI,
'ebuio_userMode': request.session.get('plu... | python | {
"resource": ""
} |
q39532 | gen500 | train | def gen500(request, baseURI, project=None):
"""Return a 500 error"""
return HttpResponseServerError(
render_to_response('plugIt/500.html', {
'context': {
'ebuio_baseUrl': baseURI,
'ebuio_userMode': request.session.get('plugit-standalone-usermode', 'ano'),
... | python | {
"resource": ""
} |
q39533 | gen403 | train | def gen403(request, baseURI, reason, project=None):
"""Return a 403 error"""
orgas = None
public_ask = False
if not settings.PIAPI_STANDALONE:
from organizations.models import Organization
if project and project.plugItLimitOrgaJoinable:
orgas = project.plugItOrgaJoinable.or... | python | {
"resource": ""
} |
q39534 | get_cache_key | train | def get_cache_key(request, meta, orgaMode, currentOrga):
"""Return the cache key to use"""
# Caching
cacheKey = None
if 'cache_time' in meta:
if meta['cache_time'] > 0:
# by default, no cache by user
useUser = False
# If a logged user in needed, cache the ... | python | {
"resource": ""
} |
q39535 | check_rights_and_access | train | def check_rights_and_access(request, meta, project=None):
"""Check if the user can access the page"""
# User must be logged ?
if ('only_logged_user' in meta and meta['only_logged_user']):
if not request.user.is_authenticated():
return gen403(request, baseURI, 'only_logged_user', project)... | python | {
"resource": ""
} |
q39536 | is_requestaddress_in_networks | train | def is_requestaddress_in_networks(request, networks):
"""Helper method to check if the remote real ip of a request is in a network"""
from ipware.ip import get_real_ip, get_ip
# Get the real IP, i.e. no reverse proxy, no nginx
ip = get_real_ip(request)
if not ip:
ip = get_ip(request)
... | python | {
"resource": ""
} |
q39537 | is_address_in_network | train | def is_address_in_network(ip, net):
"""Is an address in a network"""
# http://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-network-in-python
import socket
import struct
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
netaddr, bits = net.split('/')
if int(bits) ==... | python | {
"resource": ""
} |
q39538 | find_in_cache | train | def find_in_cache(cacheKey):
"""Check if the content exists in cache and return it"""
# If we have to use cache, we try to find the result in cache
if cacheKey:
data = cache.get('plugit-cache-' + cacheKey, None)
# We found a result, we can return it
if data:
return (dat... | python | {
"resource": ""
} |
q39539 | build_base_parameters | train | def build_base_parameters(request):
"""Build the list of parameters to forward from the post and get parameters"""
getParameters = {}
postParameters = {}
files = {}
# Copy GET parameters, excluding ebuio_*
for v in request.GET:
if v[:6] != 'ebuio_':
val = request.GET.getlis... | python | {
"resource": ""
} |
q39540 | build_user_requested_parameters | train | def build_user_requested_parameters(request, meta):
"""Build the list of parameters requested by the plugit server"""
postParameters = {}
getParameters = {}
files = {}
# Add parameters requested by the server
if 'user_info' in meta:
for prop in meta['user_info']:
# Test if... | python | {
"resource": ""
} |
q39541 | build_parameters | train | def build_parameters(request, meta, orgaMode, currentOrga):
"""Return the list of get, post and file parameters to send"""
postParameters = {}
getParameters = {}
files = {}
def update_parameters(data):
tmp_getParameters, tmp_postParameters, tmp_files = data
getParameters.update(tm... | python | {
"resource": ""
} |
q39542 | build_extra_headers | train | def build_extra_headers(request, proxyMode, orgaMode, currentOrga):
"""Build the list of extra headers"""
things_to_add = {}
# If in proxymode, add needed infos to headers
if proxyMode:
# User
for prop in settings.PIAPI_USERDATA:
if hasattr(request.user, prop):
... | python | {
"resource": ""
} |
q39543 | handle_special_cases | train | def handle_special_cases(request, data, baseURI, meta):
"""Handle sepcial cases for returned values by the doAction function"""
if request.method == 'OPTIONS':
r = HttpResponse('')
return r
if data is None:
return gen404(request, baseURI, 'data')
if data.__class__.__name__ == ... | python | {
"resource": ""
} |
q39544 | build_final_response | train | def build_final_response(request, meta, result, menu, hproject, proxyMode, context):
"""Build the final response to send back to the browser"""
if 'no_template' in meta and meta['no_template']: # Just send the json back
return HttpResponse(result)
# TODO this breaks pages not using new template
... | python | {
"resource": ""
} |
q39545 | render_data | train | def render_data(context, templateContent, proxyMode, rendered_data, menukey='menubar'):
"""Render the template"""
if proxyMode:
# Update csrf_tokens
csrf = unicode(context['csrf_token'])
tag = u'{~__PLUGIT_CSRF_TOKEN__~}'
rendered_data = unicode(rendered_data, 'utf-8').replace(t... | python | {
"resource": ""
} |
q39546 | cache_if_needed | train | def cache_if_needed(cacheKey, result, menu, context, meta):
"""Cache the result, if needed"""
if cacheKey:
# This will be a method in django 1.7
flat_context = {}
for d in context.dicts:
flat_context.update(d)
del flat_context['csrf_token']
data = {'result... | python | {
"resource": ""
} |
q39547 | get_current_orga | train | def get_current_orga(request, hproject, availableOrga):
"""Return the current orga to use"""
# If nothing available return 404
if len(availableOrga) == 0:
raise Http404
# Find the current orga
currentOrgaId = request.session.get('plugit-orgapk-' + str(hproject.pk), None)
# If we don't... | python | {
"resource": ""
} |
q39548 | update_session | train | def update_session(request, session_to_set, hproPk):
"""Update the session with users-realted values"""
for key, value in session_to_set.items():
request.session['plugit_' + str(hproPk) + '_' + key] = value | python | {
"resource": ""
} |
q39549 | get_current_session | train | def get_current_session(request, hproPk):
"""Get the current session value"""
retour = {}
base_key = 'plugit_' + str(hproPk) + '_'
for key, value in request.session.iteritems():
if key.startswith(base_key):
retour[key[len(base_key):]] = value
return retour | python | {
"resource": ""
} |
q39550 | media | train | def media(request, path, hproPk=None):
"""Ask the server for a media and return it to the client browser. Forward cache headers"""
if not settings.PIAPI_STANDALONE:
(plugIt, baseURI, _) = getPlugItObject(hproPk)
else:
global plugIt, baseURI
try:
(media, contentType, cache_contr... | python | {
"resource": ""
} |
q39551 | setUser | train | def setUser(request):
"""In standalone mode, change the current user"""
if not settings.PIAPI_STANDALONE or settings.PIAPI_REALUSERS:
raise Http404
request.session['plugit-standalone-usermode'] = request.GET.get('mode')
return HttpResponse('') | python | {
"resource": ""
} |
q39552 | setOrga | train | def setOrga(request, hproPk=None):
"""Change the current orga"""
if settings.PIAPI_STANDALONE:
request.session['plugit-standalone-organame'] = request.GET.get('name')
request.session['plugit-standalone-orgapk'] = request.GET.get('pk')
else:
(_, _, hproject) = getPlugItObject(hproPk... | python | {
"resource": ""
} |
q39553 | check_api_key | train | def check_api_key(request, key, hproPk):
"""Check if an API key is valid"""
if settings.PIAPI_STANDALONE:
return True
(_, _, hproject) = getPlugItObject(hproPk)
if not hproject:
return False
if hproject.plugItApiKey is None or hproject.plugItApiKey == '':
return False
... | python | {
"resource": ""
} |
q39554 | home | train | def home(request, hproPk):
""" Route the request to runURI if defined otherwise go to plugIt """
if settings.PIAPI_STANDALONE:
return main(request, '', hproPk)
(plugIt, baseURI, hproject) = getPlugItObject(hproPk)
if hproject.runURI:
return HttpResponseRedirect(hproject.runURI)
els... | python | {
"resource": ""
} |
q39555 | api_home | train | def api_home(request, key=None, hproPk=None):
"""Show the home page for the API with all methods"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
return render_to_response('plugIt/api.html', {}, context_instance=RequestContext(request)) | python | {
"resource": ""
} |
q39556 | api_user | train | def api_user(request, userPk, key=None, hproPk=None):
"""Return information about an user"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
if settings.PIAPI_STANDALONE:
if not settings.PIAPI_REALUSERS:
user = generate_user(pk=userPk)
if us... | python | {
"resource": ""
} |
q39557 | api_orga | train | def api_orga(request, orgaPk, key=None, hproPk=None):
"""Return information about an organization"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
retour = {}
if settings.PIAPI_STANDALONE:
retour['pk'] = orgaPk
if orgaPk == "-1":
retour['... | python | {
"resource": ""
} |
q39558 | api_get_project_members | train | def api_get_project_members(request, key=None, hproPk=True):
"""Return the list of project members"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
if settings.PIAPI_STANDALONE:
if not settings.PIAPI_REALUSERS:
users = [generate_user(pk="-1"), generat... | python | {
"resource": ""
} |
q39559 | api_techgroup_list | train | def api_techgroup_list(request, key, hproPk):
"""Return the list of techgroup"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
from users.models import TechGroup
retour = [{
'uuid': t.uuid,
'uid': t.uid,
'name': t.name,
} for t in TechGro... | python | {
"resource": ""
} |
q39560 | api_user_techgroup_list | train | def api_user_techgroup_list(request, userPk, key, hproPk):
"""Return the list of techgroup of a user"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
# From UUID to Pk
from users.models import TechUser
user = get_object_or_404(TechUser, pk=userPk)
retour = ... | python | {
"resource": ""
} |
q39561 | generic_send_mail | train | def generic_send_mail(sender, dests, subject, message, key, origin='', html_message=False):
"""Generic mail sending function"""
# If no EBUIO Mail settings have been set, then no e-mail shall be sent
if settings.EBUIO_MAIL_SECRET_KEY and settings.EBUIO_MAIL_SECRET_HASH:
headers = {}
if key... | python | {
"resource": ""
} |
q39562 | api_send_mail | train | def api_send_mail(request, key=None, hproPk=None):
"""Send a email. Posts parameters are used"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
sender = request.POST.get('sender', settings.MAIL_SENDER)
dests = request.POST.getlist('dests')
subject = request.POST['... | python | {
"resource": ""
} |
q39563 | api_orgas | train | def api_orgas(request, key=None, hproPk=None):
"""Return the list of organizations pk"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
list_orgas = []
if settings.PIAPI_STANDALONE:
list_orgas = [{'id': -1, 'name': 'EBU', 'codops': 'ZZEBU'},
... | python | {
"resource": ""
} |
q39564 | api_ebuio_forum | train | def api_ebuio_forum(request, key=None, hproPk=None):
"""Create a topic on the forum of the ioproject. EBUIo only !"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
if settings.PIAPI_STANDALONE:
return HttpResponse(json.dumps({'error': 'no-on-ebuio'}), content_typ... | python | {
"resource": ""
} |
q39565 | api_ebuio_forum_get_topics_by_tag_for_user | train | def api_ebuio_forum_get_topics_by_tag_for_user(request, key=None, hproPk=None, tag=None, userPk=None):
"""Return the list of topics using the tag pk"""
# Check API key (in order to be sure that we have a valid one and that's correspond to the project
if not check_api_key(request, key, hproPk):
retu... | python | {
"resource": ""
} |
q39566 | Client.auto_complete | train | def auto_complete(self, term, state=None, postcode=None, max_results=None):
"""
Gets a list of addresses that begin with the given term.
"""
self._validate_state(state)
params = {"term": term, "state": state, "postcode": postcode,
"max_results": max_results or s... | python | {
"resource": ""
} |
q39567 | Client.parse_address | train | def parse_address(self, address_line):
"""
Parses the given address into it's individual address fields.
"""
params = {"term": address_line}
json = self._make_request('/address/getParsedAddress', params)
if json is None:
return None
return Address.from... | python | {
"resource": ""
} |
q39568 | Client.similar | train | def similar(self, address_line, max_results=None):
"""
Gets a list of valid addresses that are similar to the given term, can
be used to match invalid addresses to valid addresses.
"""
params = {"term": address_line,
"max_results": max_results or self.max_result... | python | {
"resource": ""
} |
q39569 | Client.connect | train | def connect(self, address, token=None):
"""
Connect the underlying websocket to the address,
send a handshake and optionally a token packet.
Returns `True` if connected, `False` if the connection failed.
:param address: string, `IP:PORT`
:param token: unique token, requ... | python | {
"resource": ""
} |
q39570 | Client.listen | train | def listen(self):
"""
Set up a quick connection. Returns on disconnect.
After calling `connect()`, this waits for messages from the server
using `select`, and notifies the subscriber of any events.
"""
import select
while self.connected:
r, w, e = sel... | python | {
"resource": ""
} |
q39571 | Client.on_message | train | def on_message(self, msg=None):
"""
Poll the websocket for a new packet.
`Client.listen()` calls this.
:param msg (string(byte array)): Optional. Parse the specified message
instead of receiving a packet from the socket.
"""
if msg is None:
try:
... | python | {
"resource": ""
} |
q39572 | Client.send_facebook | train | def send_facebook(self, token):
"""
Tells the server which Facebook account this client uses.
After sending, the server takes some time to
get the data from Facebook.
Seems to be broken in recent versions of the game.
"""
self.send_struct('<B%iB' % len(token), 8... | python | {
"resource": ""
} |
q39573 | Client.send_respawn | train | def send_respawn(self):
"""
Respawns the player.
"""
nick = self.player.nick
self.send_struct('<B%iH' % len(nick), 0, *map(ord, nick)) | python | {
"resource": ""
} |
q39574 | Client.send_target | train | def send_target(self, x, y, cid=0):
"""
Sets the target position of all cells.
`x` and `y` are world coordinates. They can exceed the world border.
For continuous movement, send a new target position
before the old one is reached.
In earlier versions of the game, it wa... | python | {
"resource": ""
} |
q39575 | Client.send_explode | train | def send_explode(self):
"""
In earlier versions of the game, sending this caused your cells
to split into lots of small cells and die.
"""
self.send_struct('<B', 20)
self.player.own_ids.clear()
self.player.cells_changed()
self.ingame = False
self.s... | python | {
"resource": ""
} |
q39576 | send_request | train | def send_request(req_cat, con, req_str, kwargs):
"""
Sends request to facebook graph
Returns the facebook-json response converted to python object
"""
try:
kwargs = parse.urlencode(kwargs) #python3x
except:
kwargs = urllib.urlencode(kwargs) #python2x
... | python | {
"resource": ""
} |
q39577 | action | train | def action(route, template='', methods=['GET']):
"""Decorator to create an action"""
def real_decorator(function):
function.pi_api_action = True
function.pi_api_route = route
function.pi_api_template = template
function.pi_api_methods = methods
if hasattr(function, 'pi_a... | python | {
"resource": ""
} |
q39578 | Command.handle | train | def handle(self, *args, **options):
"""
Handle liquibase command parameters
"""
database = getattr(
settings, 'LIQUIMIGRATE_DATABASE', options['database'])
try:
dbsettings = databases[database]
except KeyError:
raise CommandError("... | python | {
"resource": ""
} |
q39579 | lines | train | def lines(fp):
"""
Read lines of UTF-8 from the file-like object given in ``fp``, making sure
that when reading from STDIN, reads are at most line-buffered.
UTF-8 decoding errors are handled silently. Invalid characters are
replaced by U+FFFD REPLACEMENT CHARACTER.
Line endings are normalised ... | python | {
"resource": ""
} |
q39580 | api.publish | train | def publish(self, cat, **kwargs):
"""
This method is used for creating objects in the facebook graph.
The first paramter is "cat", the category of publish. In addition to "cat"
"id" must also be passed and is catched by "kwargs"
"""
... | python | {
"resource": ""
} |
q39581 | api.get_object | train | def get_object(self, cat, **kwargs):
"""
This method is used for retrieving objects from facebook. "cat", the category, must be
passed. When cat is "single", pass the "id "and desired "fields" of the single object. If the
cat is "multiple", only pass the... | python | {
"resource": ""
} |
q39582 | StripTableName | train | def StripTableName(name):
"""
Return the significant portion of a table name according to LIGO LW
naming conventions.
Example:
>>> StripTableName("sngl_burst_group:sngl_burst:table")
'sngl_burst'
>>> StripTableName("sngl_burst:table")
'sngl_burst'
>>> StripTableName("sngl_burst")
'sngl_burst'
"""
if name.... | python | {
"resource": ""
} |
q39583 | use_in | train | def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table,
Column, and Stream classes defined in this module when parsing XML
documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class LIGOLWContentHandler(ligolw.LIGO... | python | {
"resource": ""
} |
q39584 | Column.count | train | def count(self, value):
"""
Return the number of rows with this column equal to value.
"""
return sum(getattr(row, self.Name) == value for row in self.parentNode) | python | {
"resource": ""
} |
q39585 | Table.appendColumn | train | def appendColumn(self, name):
"""
Append a Column element named "name" to the table. Returns
the new child. Raises ValueError if the table already has
a column by that name, and KeyError if the validcolumns
attribute of this table does not contain an entry for a
column by that name.
Note that the name ... | python | {
"resource": ""
} |
q39586 | Table.appendRow | train | def appendRow(self, *args, **kwargs):
"""
Create and append a new row to this table, then return it
All positional and keyword arguments are passed to the RowType
constructor for this table.
"""
row = self.RowType(*args, **kwargs)
self.append(row)
return row | python | {
"resource": ""
} |
q39587 | Table.removeChild | train | def removeChild(self, child):
"""
Remove a child from this element. The child element is
returned, and it's parentNode element is reset.
"""
super(Table, self).removeChild(child)
if child.tagName == ligolw.Column.tagName:
self._update_column_info()
return child | python | {
"resource": ""
} |
q39588 | Table.sync_next_id | train | def sync_next_id(self):
"""
Determines the highest-numbered ID in this table, and sets
the table's .next_id attribute to the next highest ID in
sequence. If the .next_id attribute is already set to a
value greater than the highest value found, then it is left
unmodified. The return value is the ID identif... | python | {
"resource": ""
} |
q39589 | Table.applyKeyMapping | train | def applyKeyMapping(self, mapping):
"""
Used as the second half of the key reassignment algorithm.
Loops over each row in the table, replacing references to
old row keys with the new values from the mapping.
"""
for coltype, colname in zip(self.columntypes, self.columnnames):
if coltype in ligolwtypes.ID... | python | {
"resource": ""
} |
q39590 | Get.input | train | def input(self, field):
"""Gets user input for given field.
Can be interrupted with ^C.
:field: Field name.
:returns: User input.
"""
try:
desc = Get.TYPES[field]
return input("{}|{}[{}]> ".format(
field, "-" * (Get._LEN - len(fi... | python | {
"resource": ""
} |
q39591 | Get.get | train | def get(self, field, value=None):
"""Gets user input for given field and checks if it is valid.
If input is invalid, it will ask the user to enter it again.
Defaults values to empty or :value:.
It does not check validity of parent index. It can only be tested
further down the r... | python | {
"resource": ""
} |
q39592 | Arg._getPattern | train | def _getPattern(self, ipattern, done=None):
"""Parses sort pattern.
:ipattern: A pattern to parse.
:done: If :ipattern: refers to done|undone,
use this to indicate proper state.
:returns: A pattern suitable for Model.modify.
"""
if ipattern is None:
... | python | {
"resource": ""
} |
q39593 | Arg._getDone | train | def _getDone(self, done, undone):
"""Parses the done|undone state.
:done: Done marking pattern.
:undone: Not done marking pattern.
:returns: Pattern for done|undone or None if neither were specified.
"""
if done:
return self._getPattern(done, True)
i... | python | {
"resource": ""
} |
q39594 | Arg.view | train | def view(self, sort=None, purge=False, done=None, undone=None, **kwargs):
"""Handles the 'v' command.
:sort: Sort pattern.
:purge: Whether to purge items marked as 'done'.
:done: Done pattern.
:undone: Not done pattern.
:kwargs: Additional arguments to pass to the View o... | python | {
"resource": ""
} |
q39595 | Arg.modify | train | def modify(self, sort=None, purge=False, done=None, undone=None):
"""Handles the 'm' command.
:sort: Sort pattern.
:purge: Whether to purge items marked as 'done'.
:done: Done pattern.
:undone: Not done pattern.
"""
self.model.modifyInPlace(
sort=sel... | python | {
"resource": ""
} |
q39596 | Arg.add | train | def add(self, **args):
"""Handles the 'a' command.
:args: Arguments supplied to the 'a' command.
"""
kwargs = self.getKwargs(args)
if kwargs:
self.model.add(**kwargs) | python | {
"resource": ""
} |
q39597 | Arg.edit | train | def edit(self, **args):
"""Handles the 'e' command.
:args: Arguments supplied to the 'e' command.
"""
if self.model.exists(args["index"]):
values = dict(zip(
['parent', 'name', 'priority', 'comment', 'done'],
self.model.get(args["index"])
... | python | {
"resource": ""
} |
q39598 | Arg.rm | train | def rm(self, index):
"""Handles the 'r' command.
:index: Index of the item to remove.
"""
if self.model.exists(index):
self.model.remove(index) | python | {
"resource": ""
} |
q39599 | Arg.done | train | def done(self, index):
"""Handles the 'd' command.
:index: Index of the item to mark as done.
"""
if self.model.exists(index):
self.model.edit(index, done=True) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.