signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
---|---|---|---|
@property<EOL><INDENT>def serve_files_root(self):<DEDENT> | return self.__config['<STR_LIT>']<EOL> | The web root to use when serving files.
:type: str | f1473:c12:m11 |
@property<EOL><INDENT>def serve_files_list_directories(self):<DEDENT> | return self.__config['<STR_LIT>']<EOL> | Whether to list the contents of directories. This is only honored
when :py:attr:`.serve_files` is True.
:type: bool | f1473:c12:m13 |
@property<EOL><INDENT>def serve_robots_txt(self):<DEDENT> | return self.__config['<STR_LIT>']<EOL> | Whether to serve a default robots.txt file which denies everything.
:type: bool | f1473:c12:m15 |
@property<EOL><INDENT>def server_version(self):<DEDENT> | return self.__config['<STR_LIT>']<EOL> | The server version to be sent to clients in headers.
:type: str | f1473:c12:m17 |
def auth_set(self, status): | if not bool(status):<EOL><INDENT>self.__config['<STR_LIT>'] = None<EOL>self.logger.info('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.__config['<STR_LIT>'] = {}<EOL>self.logger.info('<STR_LIT>')<EOL><DEDENT> | Enable or disable requiring authentication on all incoming requests.
:param bool status: Whether to enable or disable requiring authentication. | f1473:c12:m19 |
def auth_delete_creds(self, username=None): | if not username:<EOL><INDENT>self.__config['<STR_LIT>'] = {}<EOL>self.logger.info('<STR_LIT>')<EOL>return<EOL><DEDENT>del self.__config['<STR_LIT>'][username]<EOL> | Delete the credentials for a specific username if specified or all
stored credentials.
:param str username: The username of the credentials to delete. | f1473:c12:m20 |
def auth_add_creds(self, username, password, pwtype='<STR_LIT>'): | if not isinstance(password, (bytes, str)):<EOL><INDENT>raise TypeError("<STR_LIT>".format(type(password).__name__))<EOL><DEDENT>pwtype = pwtype.lower()<EOL>if not pwtype in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.__config.get('<STR_LIT>') is None:<EOL><INDENT>self.__config['<STR_LIT>'] = {}<EOL>self.logger.info('<STR_LIT>')<EOL><DEDENT>if pwtype != '<STR_LIT>':<EOL><INDENT>algorithms_available = getattr(hashlib, '<STR_LIT>', ()) or getattr(hashlib, '<STR_LIT>', ())<EOL>if pwtype not in algorithms_available:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if pwtype == '<STR_LIT>' and len(password) == <NUM_LIT:32>:<EOL><INDENT>password = binascii.unhexlify(password)<EOL><DEDENT>elif pwtype == '<STR_LIT>' and len(password) == <NUM_LIT>:<EOL><INDENT>password = binascii.unhexlify(password)<EOL><DEDENT>if not isinstance(password, bytes):<EOL><INDENT>password = password.encode('<STR_LIT>')<EOL><DEDENT>if len(hashlib.new(pwtype, b'<STR_LIT>').digest()) != len(password):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>self.__config['<STR_LIT>'][username] = {'<STR_LIT:value>': password, '<STR_LIT:type>': pwtype}<EOL> | Add a valid set of credentials to be accepted for authentication.
Calling this function will automatically enable requiring
authentication. Passwords can be provided in either plaintext or
as a hash by specifying the hash type in the *pwtype* argument.
:param str username: The username of the credentials to be added.
:param password: The password data of the credentials to be added.
:type password: bytes, str
:param str pwtype: The type of the *password* data, (plain, md5, sha1, etc.). | f1473:c12:m21 |
def assertHTTPStatus(self, http_response, status): | self.assertTrue(isinstance(http_response, http.client.HTTPResponse))<EOL>error_message = "<STR_LIT>".format(http_response.status, status)<EOL>self.assertEqual(http_response.status, status, msg=error_message)<EOL> | Check an HTTP response object and ensure the status is correct.
:param http_response: The response object to check.
:type http_response: :py:class:`http.client.HTTPResponse`
:param int status: The status code to expect for *http_response*. | f1473:c13:m3 |
def http_request(self, resource, method='<STR_LIT:GET>', headers=None): | headers = (headers or {})<EOL>if not '<STR_LIT>' in headers:<EOL><INDENT>headers['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>self.http_connection.request(method, resource, headers=headers)<EOL>time.sleep(<NUM_LIT>)<EOL>response = self.http_connection.getresponse()<EOL>response.data = response.read()<EOL>return response<EOL> | Make an HTTP request to the test server and return the response.
:param str resource: The resource to issue the request to.
:param str method: The HTTP verb to use (GET, HEAD, POST etc.).
:param dict headers: The HTTP headers to provide in the request.
:return: The HTTP response object.
:rtype: :py:class:`http.client.HTTPResponse` | f1473:c13:m4 |
def get_cache_key(name): | return '<STR_LIT>' % (slugify(name))<EOL> | Prefixes and slugify the key name | f1480:m0 |
def requeue(modeladmin, request, queryset): | queryset.update(status=STATUS.queued)<EOL> | An admin action to requeue emails. | f1481:m1 |
def render_to_string(template_name, context=None, request=None, using=None): | if isinstance(template_name, (list, tuple)):<EOL><INDENT>template = select_template(template_name, using=using)<EOL><DEDENT>else:<EOL><INDENT>template = get_template(template_name, using=using)<EOL><DEDENT>return template.render(context, request), template.template._attached_images<EOL> | Loads a template and renders it with a context. Returns a tuple containing the rendered template string
and a list of attached images.
template_name may be a string or a list of strings. | f1482:m0 |
def validate_email_with_name(value): | value = force_text(value)<EOL>recipient = value<EOL>if '<STR_LIT:<>' and '<STR_LIT:>>' in value:<EOL><INDENT>start = value.find('<STR_LIT:<>') + <NUM_LIT:1><EOL>end = value.find('<STR_LIT:>>')<EOL>if start < end:<EOL><INDENT>recipient = value[start:end]<EOL><DEDENT><DEDENT>validate_email(recipient)<EOL> | Validate email address.
Both "Recipient Name <[email protected]>" and "[email protected]" are valid. | f1504:m0 |
def validate_comma_separated_emails(value): | if not isinstance(value, (tuple, list)):<EOL><INDENT>raise ValidationError('<STR_LIT>')<EOL><DEDENT>for email in value:<EOL><INDENT>try:<EOL><INDENT>validate_email_with_name(email)<EOL><DEDENT>except ValidationError:<EOL><INDENT>raise ValidationError('<STR_LIT>' % email, code='<STR_LIT>')<EOL><DEDENT><DEDENT> | Validate every email address in a comma separated list of emails. | f1504:m1 |
def validate_template_syntax(source): | try:<EOL><INDENT>Template(source)<EOL><DEDENT>except (TemplateSyntaxError, TemplateDoesNotExist) as err:<EOL><INDENT>raise ValidationError(text_type(err))<EOL><DEDENT> | Basic Django Template syntax validation. This allows for robuster template
authoring. | f1504:m2 |
def import_attribute(name): | module_name, attribute = name.rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL>module = importlib.import_module(module_name)<EOL>return getattr(module, attribute)<EOL> | Return an attribute from a dotted path name (e.g. "path.to.func"). | f1506:m0 |
def send_messages(self, email_messages): | from .mail import create<EOL>from .utils import create_attachments<EOL>if not email_messages:<EOL><INDENT>return<EOL><DEDENT>for email_message in email_messages:<EOL><INDENT>subject = email_message.subject<EOL>from_email = email_message.from_email<EOL>message = email_message.body<EOL>headers = email_message.extra_headers<EOL>alternatives = getattr(email_message, '<STR_LIT>', ())<EOL>for alternative in alternatives:<EOL><INDENT>if alternative[<NUM_LIT:1>].startswith('<STR_LIT>'):<EOL><INDENT>html_message = alternative[<NUM_LIT:0>]<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>html_message = '<STR_LIT>'<EOL><DEDENT>attachment_files = {}<EOL>for attachment in email_message.attachments:<EOL><INDENT>if isinstance(attachment, MIMEBase):<EOL><INDENT>attachment_files[attachment.get_filename()] = {<EOL>'<STR_LIT:file>': ContentFile(attachment.get_payload()),<EOL>'<STR_LIT>': attachment.get_content_type(),<EOL>'<STR_LIT>': OrderedDict(attachment.items()),<EOL>}<EOL><DEDENT>else:<EOL><INDENT>attachment_files[attachment[<NUM_LIT:0>]] = ContentFile(attachment[<NUM_LIT:1>])<EOL><DEDENT><DEDENT>email = create(sender=from_email,<EOL>recipients=email_message.to, cc=email_message.cc,<EOL>bcc=email_message.bcc, subject=subject,<EOL>message=message, html_message=html_message,<EOL>headers=headers)<EOL>if attachment_files:<EOL><INDENT>attachments = create_attachments(attachment_files)<EOL>email.attachments.add(*attachments)<EOL><DEDENT>if get_default_priority() == '<STR_LIT>':<EOL><INDENT>email.dispatch()<EOL><DEDENT><DEDENT> | Queue one or more EmailMessage objects and returns the number of
email messages sent. | f1508:c0:m2 |
def get_prep_value(self, value): | if isinstance(value, six.string_types):<EOL><INDENT>return value<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT:U+002CU+0020>'.join(map(lambda s: s.strip(), value))<EOL><DEDENT> | We need to accomodate queries where a single email,
or list of email addresses is supplied as arguments. For example:
- Email.objects.filter(to='[email protected]')
- Email.objects.filter(to=['[email protected]', '[email protected]']) | f1510:c0:m3 |
def south_field_triple(self): | from south.modelsinspector import introspector<EOL>field_class = '<STR_LIT>'<EOL>args, kwargs = introspector(self)<EOL>return (field_class, args, kwargs)<EOL> | Return a suitable description of this field for South.
Taken from smiley chris' easy_thumbnails | f1510:c0:m5 |
def get_available_backends(): | backends = get_config().get('<STR_LIT>', {})<EOL>if backends:<EOL><INDENT>return backends<EOL><DEDENT>backend = get_config().get('<STR_LIT>')<EOL>if backend:<EOL><INDENT>warnings.warn('<STR_LIT>',<EOL>DeprecationWarning)<EOL>backends['<STR_LIT:default>'] = backend<EOL>return backends<EOL><DEDENT>backends['<STR_LIT:default>'] = getattr(<EOL>settings, '<STR_LIT>',<EOL>'<STR_LIT>')<EOL>if '<STR_LIT>' in backends['<STR_LIT:default>']:<EOL><INDENT>backends['<STR_LIT:default>'] = '<STR_LIT>'<EOL><DEDENT>return backends<EOL> | Returns a dictionary of defined backend classes. For example:
{
'default': 'django.core.mail.backends.smtp.EmailBackend',
'locmem': 'django.core.mail.backends.locmem.EmailBackend',
} | f1514:m1 |
def get_config(): | return getattr(settings, '<STR_LIT>', {})<EOL> | Returns Post Office's configuration in dictionary format. e.g:
POST_OFFICE = {
'BATCH_SIZE': 1000
} | f1514:m3 |
def send_mail(subject, message, from_email, recipient_list, html_message='<STR_LIT>',<EOL>scheduled_time=None, headers=None, priority=PRIORITY.medium): | subject = force_text(subject)<EOL>status = None if priority == PRIORITY.now else STATUS.queued<EOL>emails = []<EOL>for address in recipient_list:<EOL><INDENT>emails.append(<EOL>Email.objects.create(<EOL>from_email=from_email, to=address, subject=subject,<EOL>message=message, html_message=html_message, status=status,<EOL>headers=headers, priority=priority, scheduled_time=scheduled_time<EOL>)<EOL>)<EOL><DEDENT>if priority == PRIORITY.now:<EOL><INDENT>for email in emails:<EOL><INDENT>email.dispatch()<EOL><DEDENT><DEDENT>return emails<EOL> | Add a new message to the mail queue. This is a replacement for Django's
``send_mail`` core email method. | f1517:m0 |
def get_email_template(name, language='<STR_LIT>'): | use_cache = getattr(settings, '<STR_LIT>', True)<EOL>if use_cache:<EOL><INDENT>use_cache = getattr(settings, '<STR_LIT>', True)<EOL><DEDENT>if not use_cache:<EOL><INDENT>return EmailTemplate.objects.get(name=name, language=language)<EOL><DEDENT>else:<EOL><INDENT>composite_name = '<STR_LIT>' % (name, language)<EOL>email_template = cache.get(composite_name)<EOL>if email_template is not None:<EOL><INDENT>return email_template<EOL><DEDENT>else:<EOL><INDENT>email_template = EmailTemplate.objects.get(name=name,<EOL>language=language)<EOL>cache.set(composite_name, email_template)<EOL>return email_template<EOL><DEDENT><DEDENT> | Function that returns an email template instance, from cache or DB. | f1517:m1 |
def create_attachments(attachment_files): | attachments = []<EOL>for filename, filedata in attachment_files.items():<EOL><INDENT>if isinstance(filedata, dict):<EOL><INDENT>content = filedata.get('<STR_LIT:file>', None)<EOL>mimetype = filedata.get('<STR_LIT>', None)<EOL>headers = filedata.get('<STR_LIT>', None)<EOL><DEDENT>else:<EOL><INDENT>content = filedata<EOL>mimetype = None<EOL>headers = None<EOL><DEDENT>opened_file = None<EOL>if isinstance(content, string_types):<EOL><INDENT>opened_file = open(content, '<STR_LIT:rb>')<EOL>content = File(opened_file)<EOL><DEDENT>attachment = Attachment()<EOL>if mimetype:<EOL><INDENT>attachment.mimetype = mimetype<EOL><DEDENT>attachment.headers = headers<EOL>attachment.file.save(filename, content=content, save=True)<EOL>attachments.append(attachment)<EOL>if opened_file is not None:<EOL><INDENT>opened_file.close()<EOL><DEDENT><DEDENT>return attachments<EOL> | Create Attachment instances from files
attachment_files is a dict of:
* Key - the filename to be used for the attachment.
* Value - file-like object, or a filename to open OR a dict of {'file': file-like-object, 'mimetype': string}
Returns a list of Attachment objects | f1517:m3 |
def parse_emails(emails): | if isinstance(emails, string_types):<EOL><INDENT>emails = [emails]<EOL><DEDENT>elif emails is None:<EOL><INDENT>emails = []<EOL><DEDENT>for email in emails:<EOL><INDENT>try:<EOL><INDENT>validate_email_with_name(email)<EOL><DEDENT>except ValidationError:<EOL><INDENT>raise ValidationError('<STR_LIT>' % email)<EOL><DEDENT><DEDENT>return emails<EOL> | A function that returns a list of valid email addresses.
This function will also convert a single email address into
a list of email addresses.
None value is also converted into an empty list. | f1517:m5 |
def valid_lock(self): | lock_pid = self.get_lock_pid()<EOL>if lock_pid is None:<EOL><INDENT>return False<EOL><DEDENT>if self._pid == lock_pid:<EOL><INDENT>return True<EOL><DEDENT>try:<EOL><INDENT>os.kill(lock_pid, <NUM_LIT:0>)<EOL><DEDENT>except OSError:<EOL><INDENT>self.release()<EOL>return False<EOL><DEDENT>return True<EOL> | See if the lock exists and is left over from an old process. | f1519:c1:m2 |
def acquire(self): | pid_file = os.open(self.pid_filename, os.O_CREAT | os.O_EXCL | os.O_RDWR)<EOL>os.write(pid_file, str(os.getpid()).encode('<STR_LIT:utf-8>'))<EOL>os.close(pid_file)<EOL>if hasattr(os, '<STR_LIT>') and platform.system() != '<STR_LIT>':<EOL><INDENT>os.symlink(self.pid_filename, self.lock_filename)<EOL><DEDENT>else:<EOL><INDENT>self.lock_filename = self.pid_filename<EOL><DEDENT> | Create a pid filename and create a symlink (the actual lock file)
across platforms that points to it. Symlink is used because it's an
atomic operation across platforms. | f1519:c1:m4 |
def release(self): | if self.lock_filename != self.pid_filename:<EOL><INDENT>try:<EOL><INDENT>os.unlink(self.lock_filename)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>os.remove(self.pid_filename)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT> | Try to delete the lock files. Doesn't matter if we fail | f1519:c1:m5 |
def get_upload_path(instance, filename): | if not instance.name:<EOL><INDENT>instance.name = filename <EOL><DEDENT>date = timezone.now().date()<EOL>filename = '<STR_LIT>'.format(name=uuid4().hex,<EOL>ext=filename.split('<STR_LIT:.>')[-<NUM_LIT:1>])<EOL>return os.path.join('<STR_LIT>', str(date.year),<EOL>str(date.month), str(date.day), filename)<EOL> | Overriding to store the original filename | f1520:m0 |
def email_message(self): | if self._cached_email_message:<EOL><INDENT>return self._cached_email_message<EOL><DEDENT>return self.prepare_email_message()<EOL> | Returns Django EmailMessage object for sending. | f1520:c0:m2 |
def prepare_email_message(self): | if self.template is not None:<EOL><INDENT>engine = get_template_engine()<EOL>subject = engine.from_string(self.template.subject).render(self.context)<EOL>plaintext_message = engine.from_string(self.template.content).render(self.context)<EOL>multipart_template = engine.from_string(self.template.html_content)<EOL>html_message = multipart_template.render(self.context)<EOL><DEDENT>else:<EOL><INDENT>subject = smart_text(self.subject)<EOL>plaintext_message = self.message<EOL>multipart_template = None<EOL>html_message = self.html_message<EOL><DEDENT>connection = connections[self.backend_alias or '<STR_LIT:default>']<EOL>if html_message:<EOL><INDENT>if plaintext_message:<EOL><INDENT>msg = EmailMultiAlternatives(<EOL>subject=subject, body=plaintext_message, from_email=self.from_email,<EOL>to=self.to, bcc=self.bcc, cc=self.cc,<EOL>headers=self.headers, connection=connection)<EOL>msg.attach_alternative(html_message, "<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>msg = EmailMultiAlternatives(<EOL>subject=subject, body=html_message, from_email=self.from_email,<EOL>to=self.to, bcc=self.bcc, cc=self.cc,<EOL>headers=self.headers, connection=connection)<EOL>msg.content_subtype = '<STR_LIT:html>'<EOL><DEDENT>if hasattr(multipart_template, '<STR_LIT>'):<EOL><INDENT>multipart_template.attach_related(msg)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>msg = EmailMessage(<EOL>subject=subject, body=plaintext_message, from_email=self.from_email,<EOL>to=self.to, bcc=self.bcc, cc=self.cc,<EOL>headers=self.headers, connection=connection)<EOL><DEDENT>for attachment in self.attachments.all():<EOL><INDENT>if attachment.headers:<EOL><INDENT>mime_part = MIMENonMultipart(*attachment.mimetype.split('<STR_LIT:/>'))<EOL>mime_part.set_payload(attachment.file.read())<EOL>for key, val in attachment.headers.items():<EOL><INDENT>try:<EOL><INDENT>mime_part.replace_header(key, val)<EOL><DEDENT>except KeyError:<EOL><INDENT>mime_part.add_header(key, val)<EOL><DEDENT><DEDENT>msg.attach(mime_part)<EOL><DEDENT>else:<EOL><INDENT>msg.attach(attachment.name, attachment.file.read(), mimetype=attachment.mimetype or None)<EOL><DEDENT>attachment.file.close()<EOL><DEDENT>self._cached_email_message = msg<EOL>return msg<EOL> | Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object,
depending on whether html_message is empty. | f1520:c0:m3 |
def dispatch(self, log_level=None,<EOL>disconnect_after_delivery=True, commit=True): | try:<EOL><INDENT>self.email_message().send()<EOL>status = STATUS.sent<EOL>message = '<STR_LIT>'<EOL>exception_type = '<STR_LIT>'<EOL><DEDENT>except Exception as e:<EOL><INDENT>status = STATUS.failed<EOL>message = str(e)<EOL>exception_type = type(e).__name__<EOL>if not commit:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>if commit:<EOL><INDENT>self.status = status<EOL>self.save(update_fields=['<STR_LIT:status>'])<EOL>if log_level is None:<EOL><INDENT>log_level = get_log_level()<EOL><DEDENT>if log_level == <NUM_LIT:1>:<EOL><INDENT>if status == STATUS.failed:<EOL><INDENT>self.logs.create(status=status, message=message,<EOL>exception_type=exception_type)<EOL><DEDENT><DEDENT>elif log_level == <NUM_LIT:2>:<EOL><INDENT>self.logs.create(status=status, message=message,<EOL>exception_type=exception_type)<EOL><DEDENT><DEDENT>return status<EOL> | Sends email and log the result. | f1520:c0:m4 |
def create(sender, recipients=None, cc=None, bcc=None, subject='<STR_LIT>', message='<STR_LIT>',<EOL>html_message='<STR_LIT>', context=None, scheduled_time=None, headers=None,<EOL>template=None, priority=None, render_on_delivery=False, commit=True,<EOL>backend='<STR_LIT>'): | priority = parse_priority(priority)<EOL>status = None if priority == PRIORITY.now else STATUS.queued<EOL>if recipients is None:<EOL><INDENT>recipients = []<EOL><DEDENT>if cc is None:<EOL><INDENT>cc = []<EOL><DEDENT>if bcc is None:<EOL><INDENT>bcc = []<EOL><DEDENT>if context is None:<EOL><INDENT>context = '<STR_LIT>'<EOL><DEDENT>if render_on_delivery:<EOL><INDENT>email = Email(<EOL>from_email=sender,<EOL>to=recipients,<EOL>cc=cc,<EOL>bcc=bcc,<EOL>scheduled_time=scheduled_time,<EOL>headers=headers, priority=priority, status=status,<EOL>context=context, template=template, backend_alias=backend<EOL>)<EOL><DEDENT>else:<EOL><INDENT>if template:<EOL><INDENT>subject = template.subject<EOL>message = template.content<EOL>html_message = template.html_content<EOL><DEDENT>_context = Context(context or {})<EOL>subject = Template(subject).render(_context)<EOL>message = Template(message).render(_context)<EOL>html_message = Template(html_message).render(_context)<EOL>email = Email(<EOL>from_email=sender,<EOL>to=recipients,<EOL>cc=cc,<EOL>bcc=bcc,<EOL>subject=subject,<EOL>message=message,<EOL>html_message=html_message,<EOL>scheduled_time=scheduled_time,<EOL>headers=headers, priority=priority, status=status,<EOL>backend_alias=backend<EOL>)<EOL><DEDENT>if commit:<EOL><INDENT>email.save()<EOL><DEDENT>return email<EOL> | Creates an email from supplied keyword arguments. If template is
specified, email subject and content will be rendered during delivery. | f1521:m0 |
def send_many(kwargs_list): | emails = []<EOL>for kwargs in kwargs_list:<EOL><INDENT>emails.append(send(commit=False, **kwargs))<EOL><DEDENT>Email.objects.bulk_create(emails)<EOL> | Similar to mail.send(), but this function accepts a list of kwargs.
Internally, it uses Django's bulk_create command for efficiency reasons.
Currently send_many() can't be used to send emails with priority = 'now'. | f1521:m2 |
def get_queued(): | return Email.objects.filter(status=STATUS.queued).select_related('<STR_LIT>').filter(Q(scheduled_time__lte=now()) | Q(scheduled_time=None)).order_by(*get_sending_order()).prefetch_related('<STR_LIT>')[:get_batch_size()]<EOL> | Returns a list of emails that should be sent:
- Status is queued
- Has scheduled_time lower than the current time or None | f1521:m3 |
def send_queued(processes=<NUM_LIT:1>, log_level=None): | queued_emails = get_queued()<EOL>total_sent, total_failed = <NUM_LIT:0>, <NUM_LIT:0><EOL>total_email = len(queued_emails)<EOL>logger.info('<STR_LIT>' %<EOL>(total_email, processes))<EOL>if log_level is None:<EOL><INDENT>log_level = get_log_level()<EOL><DEDENT>if queued_emails:<EOL><INDENT>if total_email < processes:<EOL><INDENT>processes = total_email<EOL><DEDENT>if processes == <NUM_LIT:1>:<EOL><INDENT>total_sent, total_failed = _send_bulk(queued_emails,<EOL>uses_multiprocessing=False,<EOL>log_level=log_level)<EOL><DEDENT>else:<EOL><INDENT>email_lists = split_emails(queued_emails, processes)<EOL>pool = Pool(processes)<EOL>results = pool.map(_send_bulk, email_lists)<EOL>pool.terminate()<EOL>total_sent = sum([result[<NUM_LIT:0>] for result in results])<EOL>total_failed = sum([result[<NUM_LIT:1>] for result in results])<EOL><DEDENT><DEDENT>message = '<STR_LIT>' % (<EOL>total_email,<EOL>total_sent,<EOL>total_failed<EOL>)<EOL>logger.info(message)<EOL>return (total_sent, total_failed)<EOL> | Sends out all queued mails that has scheduled_time less than now or None | f1521:m4 |
def parse(): | parser = argparse.ArgumentParser(<EOL>description='<STR_LIT>',<EOL>formatter_class=argparse.RawTextHelpFormatter<EOL>)<EOL>group = parser.add_mutually_exclusive_group()<EOL>group.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>metavar='<STR_LIT>',<EOL>)<EOL>group.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>metavar='<STR_LIT>',<EOL>)<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>metavar='<STR_LIT>',<EOL>required=False,<EOL>)<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>required=False,<EOL>action='<STR_LIT:store_true>',<EOL>)<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>required=False,<EOL>action='<STR_LIT:store_true>',<EOL>)<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>required=False,<EOL>action='<STR_LIT:store_true>',<EOL>)<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>required=False,<EOL>action='<STR_LIT:store_true>',<EOL>)<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>required=False,<EOL>action='<STR_LIT:store_true>',<EOL>)<EOL>parser.add_argument(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>help='<STR_LIT>',<EOL>required=False,<EOL>metavar='<STR_LIT>',<EOL>)<EOL>return vars(parser.parse_args())<EOL> | parse arguments supplied by cmd-line | f1523:m0 |
def __init__(self, api_key, params=None): | self._api_key = api_key<EOL>self._params = params or dict()<EOL>self._data = list()<EOL>self._entities = list()<EOL>self._all_entities = list()<EOL>self._merged_entities = list()<EOL>self._all_merged_entities = list()<EOL>self._text = None<EOL> | Initialize the BabelfyClient.
Arguments:
api_key -- key to connect the babelfy api
Keyword arguments:
params -- params for the api request | f1527:c0:m0 |
@property<EOL><INDENT>def entities(self):<DEDENT> | if not self._entities:<EOL><INDENT>self._parse_entities()<EOL><DEDENT>return self._entities<EOL> | returns a list of entities received from babelfy api | f1527:c0:m1 |
@property<EOL><INDENT>def all_entities(self):<DEDENT> | if not self._all_entities:<EOL><INDENT>self._parse_non_entities()<EOL><DEDENT>return self._all_entities<EOL> | returns a list of entities received from babelfy api and all
non-entity words from the sentence | f1527:c0:m2 |
@property<EOL><INDENT>def merged_entities(self):<DEDENT> | if not self._merged_entities:<EOL><INDENT>self._parse_merged_entities()<EOL><DEDENT>return self._merged_entities<EOL> | returns a list of entities received from babelfy api merged to the
longest possible entities | f1527:c0:m3 |
@property<EOL><INDENT>def all_merged_entities(self):<DEDENT> | if not self._all_merged_entities:<EOL><INDENT>self._parse_all_merged_entities()<EOL><DEDENT>return self._all_merged_entities<EOL> | returns a list entities received from babelfy api and all non-entity
words from the sentence merged to the longest possible entities | f1527:c0:m4 |
def babelfy(self, text, params=None): | self._entities = list()<EOL>self._all_entities = list()<EOL>self._merged_entities = list()<EOL>self._all_merged_entities = list()<EOL>self._text = "<STR_LIT:U+0020>".join(word.strip() for word in text.split())<EOL>params = params or self._params<EOL>params['<STR_LIT:key>'] = self._api_key<EOL>params['<STR_LIT:text>'] = self._text<EOL>if (sys.version < '<STR_LIT:3>' and isinstance(params['<STR_LIT:text>'], unicode)) or (sys.version >= '<STR_LIT:3>' and isinstance(params['<STR_LIT:text>'], bytes)): <EOL><INDENT>params['<STR_LIT:text>'] = params['<STR_LIT:text>'].encode('<STR_LIT:utf-8>')<EOL><DEDENT>url = BABELFY_API_URL + '<STR_LIT:?>' + urlencode(params)<EOL>request = Request(url)<EOL>request.add_header('<STR_LIT>', '<STR_LIT>')<EOL>response = urlopen(request)<EOL>if sys.version < '<STR_LIT:3>':<EOL><INDENT>buf = StringIO(response.read())<EOL><DEDENT>else:<EOL><INDENT>buf = BytesIO(response.read())<EOL><DEDENT>f = gzip.GzipFile(fileobj=buf)<EOL>reader = codecs.getreader('<STR_LIT:utf-8>')<EOL>self._data = json.load(reader(f))<EOL> | make a request to the babelfy api and babelfy param text
set self._data with the babelfied text as json object | f1527:c0:m5 |
def _parse_entities(self): | entities = list()<EOL>for result in self._data:<EOL><INDENT>entity = dict()<EOL>char_fragment = result.get('<STR_LIT>')<EOL>start = char_fragment.get('<STR_LIT:start>')<EOL>end = char_fragment.get('<STR_LIT:end>')<EOL>entity['<STR_LIT:start>'] = start<EOL>entity['<STR_LIT:end>'] = end<EOL>entity['<STR_LIT:text>'] = self._text[start: end+<NUM_LIT:1>]<EOL>if sys.version < '<STR_LIT:3>' and isinstance(entity['<STR_LIT:text>'], str):<EOL><INDENT>entity['<STR_LIT:text>'] = entity['<STR_LIT:test>'].decode('<STR_LIT:utf-8>')<EOL><DEDENT>entity['<STR_LIT>'] = True<EOL>for key, value in result.items():<EOL><INDENT>entity[key] = value<EOL><DEDENT>entities.append(entity)<EOL><DEDENT>self._entities = entities<EOL> | enrich the babelfied data with the text an the isEntity items
set self._entities with the enriched data | f1527:c0:m6 |
def _parse_non_entities(self): | def _differ(tokens):<EOL><INDENT>inner, outer = tokens<EOL>not_same_start = inner.get('<STR_LIT:start>') != outer.get('<STR_LIT:start>')<EOL>not_same_end = inner.get('<STR_LIT:end>') != outer.get('<STR_LIT:end>')<EOL>return not_same_start or not_same_end<EOL><DEDENT>def _get_dot_token():<EOL><INDENT>dot_token = dict()<EOL>dot_token['<STR_LIT:start>'] = (len(self._text) - <NUM_LIT:1>)<EOL>dot_token['<STR_LIT:end>'] = dot_token['<STR_LIT:start>']<EOL>dot_token['<STR_LIT:text>'] = '<STR_LIT:.>'<EOL>dot_token['<STR_LIT>'] = False<EOL>return dot_token<EOL><DEDENT>if self._text.endswith('<STR_LIT:.>'):<EOL><INDENT>text = self._text[:-<NUM_LIT:1>]<EOL>add_dot_token = True<EOL><DEDENT>else:<EOL><INDENT>text = self._text<EOL>add_dot_token = False<EOL><DEDENT>index = <NUM_LIT:0><EOL>all_tokens = list()<EOL>for token in text.split():<EOL><INDENT>comma_token = False<EOL>if token.endswith('<STR_LIT:U+002C>'):<EOL><INDENT>comma_token = True<EOL>token = token[:-<NUM_LIT:1>]<EOL><DEDENT>start = index<EOL>end = (start + len(token))<EOL>index += (len(token) + <NUM_LIT:1>)<EOL>all_tokens.append({<EOL>'<STR_LIT:start>': start,<EOL>'<STR_LIT:end>': end - <NUM_LIT:1>,<EOL>'<STR_LIT:text>': self._text[start: end],<EOL>'<STR_LIT>': False,<EOL>})<EOL>if comma_token:<EOL><INDENT>all_tokens.append({<EOL>'<STR_LIT:start>': index,<EOL>'<STR_LIT:end>': index,<EOL>'<STR_LIT:text>': '<STR_LIT:U+002C>',<EOL>'<STR_LIT>': False,<EOL>})<EOL>index += <NUM_LIT:1><EOL><DEDENT><DEDENT>token_tuples = list(product(all_tokens, self.entities))<EOL>redundant = [<EOL>tokens[<NUM_LIT:0>] for tokens in token_tuples if not _differ(tokens)]<EOL>non_entity_tokens = [<EOL>item for item in all_tokens if item not in redundant]<EOL>if add_dot_token:<EOL><INDENT>non_entity_tokens.append(_get_dot_token())<EOL><DEDENT>self._all_entities = sorted(<EOL>self._entities + non_entity_tokens, key=itemgetter('<STR_LIT:start>'))<EOL> | create data for all non-entities in the babelfied text
set self._all_entities with merged entity and non-entity data | f1527:c0:m7 |
def _parse_merged_entities(self): | self._merged_entities = list(filterfalse(<EOL>lambda token: self._is_wrapped(token, self.entities),<EOL>self.entities))<EOL> | set self._merged_entities to the longest possible(wrapping) tokens | f1527:c0:m8 |
def _parse_all_merged_entities(self): | self._all_merged_entities = list(filterfalse(<EOL>lambda token: self._is_wrapped(token, self.all_entities),<EOL>self.all_entities))<EOL> | set self._all_merged_entities to the longest possible(wrapping)
tokens including non-entity tokens | f1527:c0:m9 |
def _wraps(self, tokens): | def _differ(tokens):<EOL><INDENT>inner, outer = tokens<EOL>not_same_start = inner.get('<STR_LIT:start>') != outer.get('<STR_LIT:start>')<EOL>not_same_end = inner.get('<STR_LIT:end>') != outer.get('<STR_LIT:end>')<EOL>return not_same_start or not_same_end<EOL><DEDENT>def _in_range(tokens):<EOL><INDENT>inner, outer = tokens<EOL>starts_in = outer.get('<STR_LIT:start>') <= inner.get('<STR_LIT:start>')<= outer.get('<STR_LIT:end>')<EOL>ends_in = outer.get('<STR_LIT:start>') <= inner.get('<STR_LIT:end>')<= outer.get('<STR_LIT:end>')<EOL>return starts_in and ends_in<EOL><DEDENT>if not _differ(tokens):<EOL><INDENT>return False<EOL><DEDENT>return _in_range(tokens)<EOL> | determine if a token is wrapped by another token | f1527:c0:m10 |
def _is_wrapped(self, token, tokens): | for t in tokens:<EOL><INDENT>is_wrapped = self._wraps((token, t))<EOL>if is_wrapped:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL> | check if param token is wrapped by any token in tokens | f1527:c0:m11 |
def read_txt_file(filepath): | if sys.version > '<STR_LIT:3>':<EOL><INDENT>with open(filepath,'<STR_LIT:r>',encoding='<STR_LIT:utf-8>') as txt_file:<EOL><INDENT>return txt_file.readlines()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>with open(filepath) as txt_file:<EOL><INDENT>return txt_file.readlines()<EOL><DEDENT><DEDENT> | read text from `filepath` and remove linebreaks | f1528:m0 |
def dump_json(token_dict, dump_path): | if sys.version > '<STR_LIT:3>':<EOL><INDENT>with open(dump_path, '<STR_LIT:w>', encoding='<STR_LIT:utf-8>') as output_file:<EOL><INDENT>json.dump(token_dict, output_file, indent=<NUM_LIT:4>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>with open(dump_path, '<STR_LIT:w>') as output_file:<EOL><INDENT>json.dump(token_dict, output_file, indent=<NUM_LIT:4>)<EOL><DEDENT><DEDENT> | write json data to file | f1529:m0 |
def generator(<EOL>worker_id,<EOL>sleep=lambda x: time.sleep(x/<NUM_LIT>),<EOL>now=lambda: int(time.time()*<NUM_LIT:1000>)): | assert worker_id >= <NUM_LIT:0> and worker_id <= max_worker_id<EOL>last_timestamp = -<NUM_LIT:1><EOL>sequence = <NUM_LIT:0><EOL>while True:<EOL><INDENT>timestamp = now()<EOL>if last_timestamp > timestamp:<EOL><INDENT>log.warning(<EOL>"<STR_LIT>" % last_timestamp)<EOL>sleep(last_timestamp-timestamp)<EOL>continue<EOL><DEDENT>if last_timestamp == timestamp:<EOL><INDENT>sequence = (sequence + <NUM_LIT:1>) & sequence_mask<EOL>if sequence == <NUM_LIT:0>:<EOL><INDENT>log.warning("<STR_LIT>")<EOL>sequence = -<NUM_LIT:1> & sequence_mask<EOL>sleep(<NUM_LIT:1>)<EOL>continue<EOL><DEDENT><DEDENT>else:<EOL><INDENT>sequence = <NUM_LIT:0><EOL><DEDENT>last_timestamp = timestamp<EOL>yield (<EOL>((timestamp-fitepoch) << timestamp_left_shift) |<EOL>(worker_id << worker_id_shift) |<EOL>sequence)<EOL><DEDENT> | worker_id: a unique for your *entire* environment number between 0 and 255
to identify this generator.
sleep(n): function to pause this worker for n milliseconds. you usually
want to supply a custom method for this in asynchronous
processes.
now(): function to return a current unix timestamp in milliseconds.
useful for testing.
returns an iterator which yields a series of increasing integers,
guaranteed to be unique for this worker_id. | f1533:m1 |
def get_maps(count=None): | all_maps = maps.get_maps()<EOL>count = count or len(all_maps)<EOL>return sorted(random.sample(all_maps.keys(), min(count, len(all_maps))))<EOL> | Test only a few random maps to minimize time. | f1551:m0 |
def __init__(self, config): | self._config = config<EOL>self._sc2_proc = None<EOL>self._controller = None<EOL>self._initialize()<EOL> | Constructs the game controller object.
Args:
config: Interface configuration options. | f1553:c1:m0 |
def _initialize(self): | run_config = run_configs.get()<EOL>self._map_inst = maps.get(self._config.map_name)<EOL>self._map_data = self._map_inst.data(run_config)<EOL>self._sc2_proc = run_config.start(<EOL>want_rgb=self._config.interface.HasField('<STR_LIT>'))<EOL>self._controller = self._sc2_proc.controller<EOL> | Initialize play/replay connection. | f1553:c1:m1 |
def close(self): | if self._controller:<EOL><INDENT>self._controller.quit()<EOL>self._controller = None<EOL><DEDENT>if self._sc2_proc:<EOL><INDENT>self._sc2_proc.close()<EOL>self._sc2_proc = None<EOL><DEDENT> | Close the controller connection. | f1553:c1:m5 |
def _get_replay_data(self, controller, config): | f = features.features_from_game_info(game_info=controller.game_info())<EOL>observations = {}<EOL>last_actions = []<EOL>for _ in range(config.num_observations):<EOL><INDENT>raw_obs = controller.observe()<EOL>o = raw_obs.observation<EOL>obs = f.transform_obs(raw_obs)<EOL>if raw_obs.action_errors:<EOL><INDENT>print('<STR_LIT>', raw_obs.action_errors)<EOL><DEDENT>if o.game_loop == <NUM_LIT:2>:<EOL><INDENT>last_actions = [actions.FUNCTIONS.move_camera.id]<EOL><DEDENT>self.assertEqual(last_actions, list(obs.last_actions))<EOL>unit_type = obs.feature_screen.unit_type<EOL>observations[o.game_loop] = unit_type<EOL>if o.game_loop in config.actions:<EOL><INDENT>func = config.actions[o.game_loop](obs)<EOL>print(('<STR_LIT>' % o.game_loop).center(<NUM_LIT>, '<STR_LIT:->'))<EOL>print(_obs_string(obs))<EOL>scv_y, scv_x = (units.Terran.SCV == unit_type).nonzero()<EOL>print('<STR_LIT>', sorted(list(zip(scv_x, scv_y))))<EOL>print('<STR_LIT>', list(sorted(obs.available_actions)))<EOL>print('<STR_LIT>' % (func,))<EOL>self.assertIn(func.function, obs.available_actions)<EOL>if (func.function in<EOL>(actions.FUNCTIONS.Build_SupplyDepot_screen.id,<EOL>actions.FUNCTIONS.Build_Barracks_screen.id)):<EOL><INDENT>x, y = func.arguments[<NUM_LIT:1>]<EOL>self.assertEqual(_EMPTY, unit_type[y, x])<EOL><DEDENT>action = f.transform_action(o, func)<EOL>last_actions = [func.function]<EOL>controller.act(action)<EOL><DEDENT>else:<EOL><INDENT>last_actions = []<EOL><DEDENT>controller.step()<EOL><DEDENT>replay_data = controller.save_replay()<EOL>return replay_data, observations<EOL> | Runs a replay to get the replay data. | f1553:c2:m0 |
def fill(self, unit_proto): | unit_proto.unit_type = self.unit_type<EOL>unit_proto.player_relative = self.player_relative<EOL>unit_proto.health = self.health<EOL>unit_proto.shields = self.shields<EOL>unit_proto.energy = self.energy<EOL>unit_proto.transport_slots_taken = self.transport_slots_taken<EOL>unit_proto.build_progress = self.build_progress<EOL> | Fill a proto unit data object from this Unit. | f1554:c0:m1 |
def as_array(self): | return np.array([<EOL>self.unit_type,<EOL>self.player_relative,<EOL>self.health,<EOL>self.shields,<EOL>self.energy,<EOL>self.transport_slots_taken,<EOL>int(self.build_progress * <NUM_LIT:100>)<EOL>], dtype=np.int32)<EOL> | Return the unit represented as a numpy array. | f1554:c0:m2 |
def player_common(<EOL>self,<EOL>player_id=None,<EOL>minerals=None,<EOL>vespene=None,<EOL>food_cap=None,<EOL>food_used=None,<EOL>food_army=None,<EOL>food_workers=None,<EOL>idle_worker_count=None,<EOL>army_count=None,<EOL>warp_gate_count=None,<EOL>larva_count=None): | args = dict(locals())<EOL>for key, value in six.iteritems(args):<EOL><INDENT>if value is not None and key != '<STR_LIT>':<EOL><INDENT>setattr(self._player_common, key, value)<EOL><DEDENT><DEDENT>return self<EOL> | Update some or all of the fields in the PlayerCommon data. | f1554:c2:m2 |
def score_details(<EOL>self,<EOL>idle_production_time=None,<EOL>idle_worker_time=None,<EOL>total_value_units=None,<EOL>total_value_structures=None,<EOL>killed_value_units=None,<EOL>killed_value_structures=None,<EOL>collected_minerals=None,<EOL>collected_vespene=None,<EOL>collection_rate_minerals=None,<EOL>collection_rate_vespene=None,<EOL>spent_minerals=None,<EOL>spent_vespene=None): | args = dict(locals())<EOL>for key, value in six.iteritems(args):<EOL><INDENT>if value is not None and key != '<STR_LIT>':<EOL><INDENT>setattr(self._score_details, key, value)<EOL><DEDENT><DEDENT>return self<EOL> | Update some or all of the fields in the ScoreDetails data. | f1554:c2:m4 |
def build(self): | response_observation = sc_pb.ResponseObservation()<EOL>obs = response_observation.observation<EOL>obs.game_loop = self._game_loop<EOL>obs.player_common.CopyFrom(self._player_common)<EOL>obs.abilities.add(ability_id=<NUM_LIT:1>, requires_point=True) <EOL>obs.score.score = self._score<EOL>obs.score.score_details.CopyFrom(self._score_details)<EOL>def fill(image_data, size, bits):<EOL><INDENT>image_data.bits_per_pixel = bits<EOL>image_data.size.y = size[<NUM_LIT:0>]<EOL>image_data.size.x = size[<NUM_LIT:1>]<EOL>image_data.data = b'<STR_LIT>' * int(math.ceil(size[<NUM_LIT:0>] * size[<NUM_LIT:1>] * bits / <NUM_LIT:8>))<EOL><DEDENT>if '<STR_LIT>' in self._obs_spec:<EOL><INDENT>for feature in features.SCREEN_FEATURES:<EOL><INDENT>fill(getattr(obs.feature_layer_data.renders, feature.name),<EOL>self._obs_spec['<STR_LIT>'][<NUM_LIT:1>:], <NUM_LIT:8>)<EOL><DEDENT><DEDENT>if '<STR_LIT>' in self._obs_spec:<EOL><INDENT>for feature in features.MINIMAP_FEATURES:<EOL><INDENT>fill(getattr(obs.feature_layer_data.minimap_renders, feature.name),<EOL>self._obs_spec['<STR_LIT>'][<NUM_LIT:1>:], <NUM_LIT:8>)<EOL><DEDENT><DEDENT>if '<STR_LIT>' in self._obs_spec:<EOL><INDENT>fill(obs.render_data.map, self._obs_spec['<STR_LIT>'][:<NUM_LIT:2>], <NUM_LIT>)<EOL><DEDENT>if '<STR_LIT>' in self._obs_spec:<EOL><INDENT>fill(obs.render_data.minimap, self._obs_spec['<STR_LIT>'][:<NUM_LIT:2>], <NUM_LIT>)<EOL><DEDENT>if self._single_select:<EOL><INDENT>self._single_select.fill(obs.ui_data.single.unit)<EOL><DEDENT>if self._multi_select:<EOL><INDENT>for unit in self._multi_select:<EOL><INDENT>obs.ui_data.multi.units.add(**unit.as_dict())<EOL><DEDENT><DEDENT>if self._build_queue:<EOL><INDENT>for unit in self._build_queue:<EOL><INDENT>obs.ui_data.production.build_queue.add(**unit.as_dict())<EOL><DEDENT><DEDENT>if self._feature_units:<EOL><INDENT>for feature_unit in self._feature_units:<EOL><INDENT>obs.raw_data.units.add(**feature_unit.as_dict())<EOL><DEDENT><DEDENT>return response_observation<EOL> | Builds and returns a proto ResponseObservation. | f1554:c2:m11 |
def _xy_locs(mask): | y, x = mask.nonzero()<EOL>return list(zip(x, y))<EOL> | Mask should be a set of bools from comparison with a feature layer. | f1556:m0 |
def __init__(self, num_agents, observation_spec, action_spec): | self._num_agents = num_agents<EOL>self._observation_spec = observation_spec<EOL>self._action_spec = action_spec<EOL>self._episode_steps = <NUM_LIT:0><EOL>self.next_timestep = [<EOL>environment.TimeStep(<EOL>step_type=environment.StepType.MID,<EOL>reward=<NUM_LIT:0.>,<EOL>discount=<NUM_LIT:1.>,<EOL>observation=self._default_observation(obs_spec, agent_index))<EOL>for agent_index, obs_spec in enumerate(observation_spec)]<EOL>self.episode_length = float('<STR_LIT>')<EOL> | Initializes the TestEnvironment.
The `next_observation` is initialized to be reward = 0., discount = 1.,
and an appropriately sized observation of all zeros. `episode_length` is set
to `float('inf')`.
Args:
num_agents: The number of agents.
observation_spec: The observation specs for each player.
action_spec: The action specs for each player. | f1558:c0:m0 |
def reset(self): | self._episode_steps = <NUM_LIT:0><EOL>return self.step([None] * self._num_agents)<EOL> | Restarts episode and returns `next_observation` with `StepType.FIRST`. | f1558:c0:m1 |
def step(self, actions, step_mul=None): | del step_mul <EOL>if len(actions) != self._num_agents:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' % (<EOL>self._num_agents, len(actions)))<EOL><DEDENT>if self._episode_steps == <NUM_LIT:0>:<EOL><INDENT>step_type = environment.StepType.FIRST<EOL><DEDENT>elif self._episode_steps >= self.episode_length:<EOL><INDENT>step_type = environment.StepType.LAST<EOL><DEDENT>else:<EOL><INDENT>step_type = environment.StepType.MID<EOL><DEDENT>timesteps = []<EOL>for timestep in self.next_timestep:<EOL><INDENT>if step_type is environment.StepType.FIRST:<EOL><INDENT>timesteps.append(timestep._replace(<EOL>step_type=step_type,<EOL>reward=<NUM_LIT:0.>,<EOL>discount=<NUM_LIT:0.>))<EOL><DEDENT>elif step_type is environment.StepType.LAST:<EOL><INDENT>timesteps.append(timestep._replace(<EOL>step_type=step_type,<EOL>discount=<NUM_LIT:0.>))<EOL><DEDENT>else:<EOL><INDENT>timesteps.append(timestep)<EOL><DEDENT><DEDENT>if timesteps[<NUM_LIT:0>].step_type is environment.StepType.LAST:<EOL><INDENT>self._episode_steps = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>self._episode_steps += <NUM_LIT:1><EOL><DEDENT>return timesteps<EOL> | Returns `next_observation` modifying its `step_type` if necessary. | f1558:c0:m2 |
def action_spec(self): | return self._action_spec<EOL> | See base class. | f1558:c0:m3 |
def observation_spec(self): | return self._observation_spec<EOL> | See base class. | f1558:c0:m4 |
def _default_observation(self, obs_spec, agent_index): | observation = {}<EOL>for key, spec in obs_spec.items():<EOL><INDENT>observation[key] = np.zeros(shape=spec, dtype=np.int32)<EOL><DEDENT>return observation<EOL> | Returns an observation based on the observation spec. | f1558:c0:m5 |
def __init__(self,<EOL>_only_use_kwargs=None,<EOL>map_name=None,<EOL>players=None,<EOL>agent_interface_format=None,<EOL>discount=<NUM_LIT:1.>,<EOL>discount_zero_after_timeout=False,<EOL>visualize=False,<EOL>step_mul=None,<EOL>realtime=False,<EOL>save_replay_episodes=<NUM_LIT:0>,<EOL>replay_dir=None,<EOL>game_steps_per_episode=None,<EOL>score_index=None,<EOL>score_multiplier=None,<EOL>random_seed=None,<EOL>disable_fog=False,<EOL>ensure_available_actions=True): | del map_name <EOL>del discount <EOL>del discount_zero_after_timeout <EOL>del visualize <EOL>del step_mul <EOL>del save_replay_episodes <EOL>del replay_dir <EOL>del game_steps_per_episode <EOL>del score_index <EOL>del score_multiplier <EOL>del random_seed <EOL>del disable_fog <EOL>del ensure_available_actions <EOL>if _only_use_kwargs:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if realtime:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not players:<EOL><INDENT>num_agents = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>num_agents = sum(<NUM_LIT:1> for p in players if isinstance(p, sc2_env.Agent))<EOL><DEDENT>if agent_interface_format is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if isinstance(agent_interface_format, sc2_env.AgentInterfaceFormat):<EOL><INDENT>agent_interface_format = [agent_interface_format] * num_agents<EOL><DEDENT>if len(agent_interface_format) != num_agents:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self._features = [<EOL>features.Features(interface_format, map_size=DUMMY_MAP_SIZE)<EOL>for interface_format in agent_interface_format]<EOL>super(SC2TestEnv, self).__init__(<EOL>num_agents=num_agents,<EOL>action_spec=tuple(f.action_spec() for f in self._features),<EOL>observation_spec=tuple(f.observation_spec() for f in self._features))<EOL>self.episode_length = <NUM_LIT:10><EOL> | Initializes an SC2TestEnv.
Args:
_only_use_kwargs: Don't pass args, only kwargs.
map_name: Map name. Ignored.
players: A list of Agent and Bot instances that specify who will play.
agent_interface_format: A sequence containing one AgentInterfaceFormat
per agent, matching the order of agents specified in the players list.
Or a single AgentInterfaceFormat to be used for all agents.
discount: Unused.
discount_zero_after_timeout: Unused.
visualize: Unused.
step_mul: Unused.
realtime: Not supported by the mock environment, throws if set to true.
save_replay_episodes: Unused.
replay_dir: Unused.
game_steps_per_episode: Unused.
score_index: Unused.
score_multiplier: Unused.
random_seed: Unused.
disable_fog: Unused.
ensure_available_actions: Whether to throw an exception when an
unavailable action is passed to step().
Raises:
ValueError: if args are passed. | f1558:c1:m0 |
def save_replay(self, *args, **kwargs): | Does nothing. | f1558:c1:m1 |
|
def _default_observation(self, obs_spec, agent_index): | response_observation = dummy_observation.Builder(<EOL>obs_spec).game_loop(<NUM_LIT:0>).build()<EOL>features_ = self._features[agent_index]<EOL>observation = features_.transform_obs(response_observation)<EOL>if '<STR_LIT>' in observation:<EOL><INDENT>minimap_camera = observation.feature_minimap.camera<EOL>minimap_camera.fill(<NUM_LIT:0>)<EOL>height, width = [dim // <NUM_LIT:2> for dim in minimap_camera.shape]<EOL>minimap_camera[:height, :width].fill(<NUM_LIT:1>)<EOL><DEDENT>return observation<EOL> | Returns a mock observation from an SC2Env. | f1558:c1:m2 |
def run_loop(agents, env, max_frames=<NUM_LIT:0>, max_episodes=<NUM_LIT:0>): | total_frames = <NUM_LIT:0><EOL>total_episodes = <NUM_LIT:0><EOL>start_time = time.time()<EOL>observation_spec = env.observation_spec()<EOL>action_spec = env.action_spec()<EOL>for agent, obs_spec, act_spec in zip(agents, observation_spec, action_spec):<EOL><INDENT>agent.setup(obs_spec, act_spec)<EOL><DEDENT>try:<EOL><INDENT>while not max_episodes or total_episodes < max_episodes:<EOL><INDENT>total_episodes += <NUM_LIT:1><EOL>timesteps = env.reset()<EOL>for a in agents:<EOL><INDENT>a.reset()<EOL><DEDENT>while True:<EOL><INDENT>total_frames += <NUM_LIT:1><EOL>actions = [agent.step(timestep)<EOL>for agent, timestep in zip(agents, timesteps)]<EOL>if max_frames and total_frames >= max_frames:<EOL><INDENT>return<EOL><DEDENT>if timesteps[<NUM_LIT:0>].last():<EOL><INDENT>break<EOL><DEDENT>timesteps = env.step(actions)<EOL><DEDENT><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>pass<EOL><DEDENT>finally:<EOL><INDENT>elapsed_time = time.time() - start_time<EOL>print("<STR_LIT>" % (<EOL>elapsed_time, total_frames, total_frames / elapsed_time))<EOL><DEDENT> | A run loop to have agents and an environment interact. | f1559:m0 |
def tcp_server(tcp_addr, settings): | family = socket.AF_INET6 if "<STR_LIT::>" in tcp_addr.ip else socket.AF_INET<EOL>sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)<EOL>sock.bind(tcp_addr)<EOL>sock.listen(<NUM_LIT:1>)<EOL>logging.info("<STR_LIT>", tcp_addr)<EOL>conn, addr = sock.accept()<EOL>logging.info("<STR_LIT>", Addr(*addr))<EOL>write_tcp(conn, settings["<STR_LIT>"])<EOL>send_settings = {k: v for k, v in settings.items() if k != "<STR_LIT>"}<EOL>logging.debug("<STR_LIT>", send_settings)<EOL>write_tcp(conn, json.dumps(send_settings).encode())<EOL>return conn<EOL> | Start up the tcp server, send the settings. | f1560:m2 |
def tcp_client(tcp_addr): | family = socket.AF_INET6 if "<STR_LIT::>" in tcp_addr.ip else socket.AF_INET<EOL>sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)<EOL>for i in range(<NUM_LIT>):<EOL><INDENT>logging.info("<STR_LIT>", tcp_addr, i)<EOL>try:<EOL><INDENT>sock.connect(tcp_addr)<EOL>break<EOL><DEDENT>except socket.error:<EOL><INDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>sock.connect(tcp_addr) <EOL><DEDENT>logging.info("<STR_LIT>")<EOL>map_data = read_tcp(sock)<EOL>settings_str = read_tcp(sock)<EOL>if not settings_str:<EOL><INDENT>raise socket.error("<STR_LIT>")<EOL><DEDENT>settings = json.loads(settings_str.decode())<EOL>logging.info("<STR_LIT>", settings["<STR_LIT>"])<EOL>logging.debug("<STR_LIT>", settings)<EOL>settings["<STR_LIT>"] = map_data<EOL>return sock, settings<EOL> | Connect to the tcp server, and return the settings. | f1560:m3 |
def read_tcp_size(conn, size): | chunks = []<EOL>bytes_read = <NUM_LIT:0><EOL>while bytes_read < size:<EOL><INDENT>chunk = conn.recv(size - bytes_read)<EOL>if not chunk:<EOL><INDENT>if bytes_read > <NUM_LIT:0>:<EOL><INDENT>logging.warning("<STR_LIT>", bytes_read, size)<EOL><DEDENT>return<EOL><DEDENT>chunks.append(chunk)<EOL>bytes_read += len(chunk)<EOL><DEDENT>return b"<STR_LIT>".join(chunks)<EOL> | Read `size` number of bytes from `conn`, retrying as needed. | f1560:m8 |
def forward_ports(remote_host, local_host, local_listen_ports,<EOL>remote_listen_ports): | if "<STR_LIT::>" in local_host and not local_host.startswith("<STR_LIT:[>"):<EOL><INDENT>local_host = "<STR_LIT>" % local_host<EOL><DEDENT>ssh = whichcraft.which("<STR_LIT>") or whichcraft.which("<STR_LIT>")<EOL>if not ssh:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>args = [ssh, remote_host]<EOL>for local_port in local_listen_ports:<EOL><INDENT>args += ["<STR_LIT>", "<STR_LIT>" % (local_host, local_port,<EOL>local_host, local_port)]<EOL><DEDENT>for remote_port in remote_listen_ports:<EOL><INDENT>args += ["<STR_LIT>", "<STR_LIT>" % (local_host, remote_port,<EOL>local_host, remote_port)]<EOL><DEDENT>logging.info("<STR_LIT>", "<STR_LIT:U+0020>".join(args))<EOL>return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,<EOL>stdin=subprocess.PIPE, close_fds=(os.name == "<STR_LIT>"))<EOL> | Forwards ports such that multiplayer works between machines.
Args:
remote_host: Where to ssh to.
local_host: "127.0.0.1" or "::1".
local_listen_ports: Which ports to listen on locally to forward remotely.
remote_listen_ports: Which ports to listen on remotely to forward locally.
Returns:
The ssh process.
Raises:
ValueError: if it can't find ssh. | f1560:m10 |
def __init__(self, <EOL>_only_use_kwargs=None,<EOL>host="<STR_LIT:127.0.0.1>",<EOL>config_port=None,<EOL>race=None,<EOL>name="<STR_LIT>",<EOL>agent_interface_format=None,<EOL>discount=<NUM_LIT:1.>,<EOL>visualize=False,<EOL>step_mul=None,<EOL>realtime=False,<EOL>replay_dir=None,<EOL>replay_prefix=None): | if _only_use_kwargs:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if host not in ("<STR_LIT:127.0.0.1>", "<STR_LIT>"):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not config_port:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if agent_interface_format is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not race:<EOL><INDENT>race = sc2_env.Race.random<EOL><DEDENT>self._num_agents = <NUM_LIT:1><EOL>self._discount = discount<EOL>self._step_mul = step_mul or <NUM_LIT:8><EOL>self._realtime = realtime<EOL>self._last_step_time = None<EOL>self._save_replay_episodes = <NUM_LIT:1> if replay_dir else <NUM_LIT:0><EOL>self._replay_dir = replay_dir<EOL>self._replay_prefix = replay_prefix<EOL>self._score_index = -<NUM_LIT:1> <EOL>self._score_multiplier = <NUM_LIT:1><EOL>self._episode_length = <NUM_LIT:0> <EOL>self._ensure_available_actions = False<EOL>self._discount_zero_after_timeout = False<EOL>self._run_config = run_configs.get()<EOL>self._parallel = run_parallel.RunParallel() <EOL>interface = self._get_interface(<EOL>agent_interface_format=agent_interface_format, require_raw=visualize)<EOL>self._launch_remote(host, config_port, race, name, interface)<EOL>self._finalize([agent_interface_format], [interface], visualize)<EOL> | Create a SC2 Env that connects to a remote instance of the game.
This assumes that the game is already up and running, and it only needs to
join. You need some other script to launch the process and call
RequestCreateGame. It also assumes that it's a multiplayer game, and that
the ports are consecutive.
You must pass a resolution that you want to play at. You can send either
feature layer resolution or rgb resolution or both. If you send both you
must also choose which to use as your action space. Regardless of which you
choose you must send both the screen and minimap resolutions.
For each of the 4 resolutions, either specify size or both width and
height. If you specify size then both width and height will take that value.
Args:
_only_use_kwargs: Don't pass args, only kwargs.
host: Which ip to use. Either ipv4 or ipv6 localhost.
config_port: Where to find the config port.
race: Race for this agent.
name: The name of this agent, for saving in the replay.
agent_interface_format: AgentInterfaceFormat object describing the
format of communication between the agent and the environment.
discount: Returned as part of the observation.
visualize: Whether to pop up a window showing the camera and feature
layers. This won't work without access to a window manager.
step_mul: How many game steps per agent step (action/observation). None
means use the map default.
realtime: Whether to use realtime mode. In this mode the game simulation
automatically advances (at 22.4 gameloops per second) rather than
being stepped manually. The number of game loops advanced with each
call to step() won't necessarily match the step_mul specified. The
environment will attempt to honour step_mul, returning observations
with that spacing as closely as possible. Game loops will be skipped
if they cannot be retrieved and processed quickly enough.
replay_dir: Directory to save a replay.
replay_prefix: An optional prefix to use when saving replays.
Raises:
ValueError: if the race is invalid.
ValueError: if the resolutions aren't specified correctly.
ValueError: if the host or port are invalid. | f1560:c2:m0 |
def _launch_remote(self, host, config_port, race, name, interface): | self._tcp_conn, settings = tcp_client(Addr(host, config_port))<EOL>self._map_name = settings["<STR_LIT>"]<EOL>if settings["<STR_LIT>"]:<EOL><INDENT>self._udp_sock = udp_server(<EOL>Addr(host, settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]))<EOL>daemon_thread(tcp_to_udp,<EOL>(self._tcp_conn, self._udp_sock,<EOL>Addr(host, settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"])))<EOL>daemon_thread(udp_to_tcp, (self._udp_sock, self._tcp_conn))<EOL><DEDENT>extra_ports = [<EOL>settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"],<EOL>settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"],<EOL>settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"],<EOL>settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"],<EOL>]<EOL>self._sc2_procs = [self._run_config.start(<EOL>extra_ports=extra_ports, host=host, version=settings["<STR_LIT>"],<EOL>window_loc=(<NUM_LIT>, <NUM_LIT:50>), want_rgb=interface.HasField("<STR_LIT>"))]<EOL>self._controllers = [p.controller for p in self._sc2_procs]<EOL>join = sc_pb.RequestJoinGame(options=interface)<EOL>join.race = race<EOL>join.player_name = name<EOL>join.shared_port = <NUM_LIT:0> <EOL>join.server_ports.game_port = settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]<EOL>join.server_ports.base_port = settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"]<EOL>join.client_ports.add(game_port=settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"],<EOL>base_port=settings["<STR_LIT>"]["<STR_LIT>"]["<STR_LIT>"])<EOL>self._controllers[<NUM_LIT:0>].save_map(settings["<STR_LIT>"], settings["<STR_LIT>"])<EOL>self._controllers[<NUM_LIT:0>].join_game(join)<EOL> | Make sure this stays synced with bin/play_vs_agent.py. | f1560:c2:m1 |
def create_game(self, map_name): | map_inst = maps.get(map_name)<EOL>map_data = map_inst.data(self._run_config)<EOL>if map_name not in self._saved_maps:<EOL><INDENT>for controller in self._controllers:<EOL><INDENT>controller.save_map(map_inst.path, map_data)<EOL><DEDENT>self._saved_maps.add(map_name)<EOL><DEDENT>create = sc_pb.RequestCreateGame(<EOL>local_map=sc_pb.LocalMap(map_path=map_inst.path),<EOL>disable_fog=False)<EOL>for _ in range(self._num_agents):<EOL><INDENT>create.player_setup.add(type=sc_pb.Participant)<EOL><DEDENT>self._controllers[<NUM_LIT:0>].create_game(create)<EOL> | Create a game for the agents to join.
Args:
map_name: The map to use. | f1562:c0:m4 |
@property<EOL><INDENT>def hosts(self):<DEDENT> | return [process.host for process in self._processes]<EOL> | The hosts that the remote agents should connect to. | f1562:c0:m5 |
@property<EOL><INDENT>def host_ports(self):<DEDENT> | return [process.port for process in self._processes]<EOL> | The WebSocket ports that the remote agents should connect to. | f1562:c0:m6 |
@property<EOL><INDENT>def lan_ports(self):<DEDENT> | return self._lan_ports<EOL> | The LAN ports which the remote agents should specify when joining. | f1562:c0:m7 |
def close(self): | for controller in self._controllers:<EOL><INDENT>controller.quit()<EOL><DEDENT>self._controllers = []<EOL>for process in self._processes:<EOL><INDENT>process.close()<EOL><DEDENT>self._processes = []<EOL>portspicker.return_ports(self._lan_ports)<EOL>self._lan_ports = []<EOL> | Shutdown and free all resources. | f1562:c0:m8 |
def create_game(<EOL>self,<EOL>map_name,<EOL>bot_difficulty=sc_pb.VeryEasy,<EOL>bot_race=sc_common.Random,<EOL>bot_first=False): | self._controller.ping()<EOL>map_inst = maps.get(map_name)<EOL>map_data = map_inst.data(self._run_config)<EOL>if map_name not in self._saved_maps:<EOL><INDENT>self._controller.save_map(map_inst.path, map_data)<EOL>self._saved_maps.add(map_name)<EOL><DEDENT>create = sc_pb.RequestCreateGame(<EOL>local_map=sc_pb.LocalMap(map_path=map_inst.path, map_data=map_data),<EOL>disable_fog=False)<EOL>if not bot_first:<EOL><INDENT>create.player_setup.add(type=sc_pb.Participant)<EOL><DEDENT>create.player_setup.add(<EOL>type=sc_pb.Computer, race=bot_race, difficulty=bot_difficulty)<EOL>if bot_first:<EOL><INDENT>create.player_setup.add(type=sc_pb.Participant)<EOL><DEDENT>self._controller.create_game(create)<EOL> | Create a game, one remote agent vs the specified bot.
Args:
map_name: The map to use.
bot_difficulty: The difficulty of the bot to play against.
bot_race: The race for the bot.
bot_first: Whether the bot should be player 1 (else is player 2). | f1562:c1:m4 |
@property<EOL><INDENT>def host(self):<DEDENT> | return self._process.host<EOL> | The host that the remote agent should connect to. | f1562:c1:m5 |
@property<EOL><INDENT>def host_port(self):<DEDENT> | return self._process.port<EOL> | The WebSocket port that the remote agent should connect to. | f1562:c1:m6 |
def close(self): | if self._controller is not None:<EOL><INDENT>self._controller.quit()<EOL>self._controller = None<EOL><DEDENT>if self._process is not None:<EOL><INDENT>self._process.close()<EOL>self._process = None<EOL><DEDENT> | Shutdown and free all resources. | f1562:c1:m7 |
def __init__(self, <EOL>_only_use_kwargs=None,<EOL>map_name=None,<EOL>save_map=True,<EOL>host="<STR_LIT:127.0.0.1>",<EOL>host_port=None,<EOL>lan_port=None,<EOL>race=None,<EOL>name="<STR_LIT>",<EOL>agent_interface_format=None,<EOL>discount=<NUM_LIT:1.>,<EOL>visualize=False,<EOL>step_mul=None,<EOL>realtime=False,<EOL>replay_dir=None,<EOL>replay_prefix=None): | if _only_use_kwargs:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if agent_interface_format is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not race:<EOL><INDENT>race = sc2_env.Race.random<EOL><DEDENT>map_inst = map_name and maps.get(map_name)<EOL>self._map_name = map_name<EOL>self._num_agents = <NUM_LIT:1><EOL>self._discount = discount<EOL>self._step_mul = step_mul or (map_inst.step_mul if map_inst else <NUM_LIT:8>)<EOL>self._realtime = realtime<EOL>self._last_step_time = None<EOL>self._save_replay_episodes = <NUM_LIT:1> if replay_dir else <NUM_LIT:0><EOL>self._next_replay_save_time = time.time() + <NUM_LIT><EOL>self._replay_dir = replay_dir<EOL>self._replay_prefix = replay_prefix<EOL>self._score_index = -<NUM_LIT:1> <EOL>self._score_multiplier = <NUM_LIT:1><EOL>self._episode_length = <NUM_LIT:0> <EOL>self._ensure_available_actions = False<EOL>self._discount_zero_after_timeout = False<EOL>self._run_config = run_configs.get()<EOL>self._parallel = run_parallel.RunParallel() <EOL>self._in_game = False<EOL>interface = self._get_interface(<EOL>agent_interface_format=agent_interface_format, require_raw=visualize)<EOL>if isinstance(lan_port, collections.Sequence):<EOL><INDENT>if len(lan_port) != <NUM_LIT:4>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>ports = lan_port[:]<EOL><DEDENT>else:<EOL><INDENT>ports = [lan_port + p for p in range(<NUM_LIT:4>)] <EOL><DEDENT>self._connect_remote(<EOL>host, host_port, ports, race, name, map_inst, save_map, interface)<EOL>self._finalize([agent_interface_format], [interface], visualize)<EOL> | Create a SC2 Env that connects to a remote instance of the game.
This assumes that the game is already up and running, and that it only
needs to join the game - and leave once the game has ended. You need some
other script to launch the SC2 process and call RequestCreateGame. Note
that you must call close to leave the game when finished. Not doing so
will lead to issues when attempting to create another game on the same
SC2 process.
This class assumes that the game is multiplayer. LAN ports may be
specified either as a base port (from which the others will be implied),
or as an explicit list.
You must specify an agent_interface_format. See the `AgentInterfaceFormat`
documentation for further detail.
Args:
_only_use_kwargs: Don't pass args, only kwargs.
map_name: Name of a SC2 map. Run bin/map_list to get the full list of
known maps. Alternatively, pass a Map instance. Take a look at the
docs in maps/README.md for more information on available maps.
save_map: Whether to save map data before joining the game.
host: Host where the SC2 process we're connecting to is running.
host_port: The WebSocket port for the SC2 process we're connecting to.
lan_port: Either an explicit sequence of LAN ports corresponding to
[server game port, ...base port, client game port, ...base port],
or an int specifying base port - equivalent to specifying the
sequence [lan_port, lan_port+1, lan_port+2, lan_port+3].
race: Race for this agent.
name: The name of this agent, for saving in the replay.
agent_interface_format: AgentInterfaceFormat object describing the
format of communication between the agent and the environment.
discount: Returned as part of the observation.
visualize: Whether to pop up a window showing the camera and feature
layers. This won't work without access to a window manager.
step_mul: How many game steps per agent step (action/observation). None
means use the map default.
realtime: Whether to use realtime mode. In this mode the game simulation
automatically advances (at 22.4 gameloops per second) rather than
being stepped manually. The number of game loops advanced with each
call to step() won't necessarily match the step_mul specified. The
environment will attempt to honour step_mul, returning observations
with that spacing as closely as possible. Game loops will be skipped
if they cannot be retrieved and processed quickly enough.
replay_dir: Directory to save a replay.
replay_prefix: An optional prefix to use when saving replays.
Raises:
ValueError: if the race is invalid.
ValueError: if the resolutions aren't specified correctly.
ValueError: if lan_port is a sequence but its length != 4. | f1564:c1:m0 |
def _connect_remote(self, host, host_port, lan_ports, race, name, map_inst,<EOL>save_map, interface): | <EOL>logging.info("<STR_LIT>")<EOL>self._controllers = [remote_controller.RemoteController(host, host_port)]<EOL>logging.info("<STR_LIT>")<EOL>if map_inst and save_map:<EOL><INDENT>run_config = run_configs.get()<EOL>self._controllers[<NUM_LIT:0>].save_map(map_inst.path, map_inst.data(run_config))<EOL><DEDENT>join = sc_pb.RequestJoinGame(options=interface)<EOL>join.race = race<EOL>join.player_name = name<EOL>join.shared_port = <NUM_LIT:0> <EOL>join.server_ports.game_port = lan_ports.pop(<NUM_LIT:0>)<EOL>join.server_ports.base_port = lan_ports.pop(<NUM_LIT:0>)<EOL>join.client_ports.add(<EOL>game_port=lan_ports.pop(<NUM_LIT:0>), base_port=lan_ports.pop(<NUM_LIT:0>))<EOL>logging.info("<STR_LIT>")<EOL>self._controllers[<NUM_LIT:0>].join_game(join)<EOL>self._in_game = True<EOL>logging.info("<STR_LIT>")<EOL> | Make sure this stays synced with bin/agent_remote.py. | f1564:c1:m3 |
@abc.abstractmethod<EOL><INDENT>def reset(self):<DEDENT> | Starts a new sequence and returns the first `TimeStep` of this sequence.
Returns:
A `TimeStep` namedtuple containing:
step_type: A `StepType` of `FIRST`.
reward: Zero.
discount: Zero.
observation: A NumPy array, or a dict, list or tuple of arrays
corresponding to `observation_spec()`. | f1566:c2:m0 |
|
@abc.abstractmethod<EOL><INDENT>def step(self, action):<DEDENT> | Updates the environment according to the action and returns a `TimeStep`.
If the environment returned a `TimeStep` with `StepType.LAST` at the
previous step, this call to `step` will start a new sequence and `action`
will be ignored.
This method will also start a new sequence if called after the environment
has been constructed and `restart` has not been called. Again, in this case
`action` will be ignored.
Args:
action: A NumPy array, or a dict, list or tuple of arrays corresponding to
`action_spec()`.
Returns:
A `TimeStep` namedtuple containing:
step_type: A `StepType` value.
reward: Reward at this timestep.
discount: A discount in the range [0, 1].
observation: A NumPy array, or a dict, list or tuple of arrays
corresponding to `observation_spec()`. | f1566:c2:m1 |
|
@abc.abstractmethod<EOL><INDENT>def observation_spec(self):<DEDENT> | Defines the observations provided by the environment.
Returns:
A tuple of specs (one per agent), where each spec is a dict of shape
tuples. | f1566:c2:m2 |
|
@abc.abstractmethod<EOL><INDENT>def action_spec(self):<DEDENT> | Defines the actions that should be provided to `step`.
Returns:
A tuple of specs (one per agent), where each spec is something that
defines the shape of the actions. | f1566:c2:m3 |
|
def close(self): | pass<EOL> | Frees any resources used by the environment.
Implement this method for an environment backed by an external process.
This method be used directly
```python
env = Env(...)
# Use env.
env.close()
```
or via a context manager
```python
with Env(...) as env:
# Use env.
``` | f1566:c2:m4 |
def __enter__(self): | return self<EOL> | Allows the environment to be used in a with-statement context. | f1566:c2:m5 |
def __exit__(self, unused_exception_type, unused_exc_value, unused_traceback): | self.close()<EOL> | Allows the environment to be used in a with-statement context. | f1566:c2:m6 |
def __init__(self, <EOL>_only_use_kwargs=None,<EOL>map_name=None,<EOL>players=None,<EOL>agent_race=None, <EOL>bot_race=None, <EOL>difficulty=None, <EOL>screen_size_px=None, <EOL>minimap_size_px=None, <EOL>agent_interface_format=None,<EOL>discount=<NUM_LIT:1.>,<EOL>discount_zero_after_timeout=False,<EOL>visualize=False,<EOL>step_mul=None,<EOL>realtime=False,<EOL>save_replay_episodes=<NUM_LIT:0>,<EOL>replay_dir=None,<EOL>replay_prefix=None,<EOL>game_steps_per_episode=None,<EOL>score_index=None,<EOL>score_multiplier=None,<EOL>random_seed=None,<EOL>disable_fog=False,<EOL>ensure_available_actions=True): | if _only_use_kwargs:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if screen_size_px or minimap_size_px:<EOL><INDENT>raise DeprecationWarning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if agent_race or bot_race or difficulty:<EOL><INDENT>raise DeprecationWarning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>map_inst = maps.get(map_name)<EOL>self._map_name = map_name<EOL>if not players:<EOL><INDENT>players = list()<EOL>players.append(Agent(Race.random))<EOL>if not map_inst.players or map_inst.players >= <NUM_LIT:2>:<EOL><INDENT>players.append(Bot(Race.random, Difficulty.very_easy))<EOL><DEDENT><DEDENT>for p in players:<EOL><INDENT>if not isinstance(p, (Agent, Bot)):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % p)<EOL><DEDENT><DEDENT>num_players = len(players)<EOL>self._num_agents = sum(<NUM_LIT:1> for p in players if isinstance(p, Agent))<EOL>self._players = players<EOL>if not <NUM_LIT:1> <= num_players <= <NUM_LIT:2> or not self._num_agents:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>if save_replay_episodes and not replay_dir:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if map_inst.players and num_players > map_inst.players:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % (<EOL>map_inst.players, num_players))<EOL><DEDENT>self._discount = discount<EOL>self._step_mul = step_mul or map_inst.step_mul<EOL>self._realtime = realtime<EOL>self._last_step_time = None<EOL>self._save_replay_episodes = save_replay_episodes<EOL>self._replay_dir = replay_dir<EOL>self._replay_prefix = replay_prefix<EOL>self._random_seed = random_seed<EOL>self._disable_fog = disable_fog<EOL>self._ensure_available_actions = ensure_available_actions<EOL>self._discount_zero_after_timeout = discount_zero_after_timeout<EOL>if score_index is None:<EOL><INDENT>self._score_index = map_inst.score_index<EOL><DEDENT>else:<EOL><INDENT>self._score_index = score_index<EOL><DEDENT>if score_multiplier is None:<EOL><INDENT>self._score_multiplier = map_inst.score_multiplier<EOL><DEDENT>else:<EOL><INDENT>self._score_multiplier = score_multiplier<EOL><DEDENT>self._episode_length = game_steps_per_episode<EOL>if self._episode_length is None:<EOL><INDENT>self._episode_length = map_inst.game_steps_per_episode<EOL><DEDENT>self._run_config = run_configs.get()<EOL>self._parallel = run_parallel.RunParallel() <EOL>if agent_interface_format is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if isinstance(agent_interface_format, AgentInterfaceFormat):<EOL><INDENT>agent_interface_format = [agent_interface_format] * self._num_agents<EOL><DEDENT>if len(agent_interface_format) != self._num_agents:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>interfaces = []<EOL>for i, interface_format in enumerate(agent_interface_format):<EOL><INDENT>require_raw = visualize and (i == <NUM_LIT:0>)<EOL>interfaces.append(self._get_interface(interface_format, require_raw))<EOL><DEDENT>if self._num_agents == <NUM_LIT:1>:<EOL><INDENT>self._launch_sp(map_inst, interfaces[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>self._launch_mp(map_inst, interfaces)<EOL><DEDENT>self._finalize(agent_interface_format, interfaces, visualize)<EOL> | Create a SC2 Env.
You must pass a resolution that you want to play at. You can send either
feature layer resolution or rgb resolution or both. If you send both you
must also choose which to use as your action space. Regardless of which you
choose you must send both the screen and minimap resolutions.
For each of the 4 resolutions, either specify size or both width and
height. If you specify size then both width and height will take that value.
Args:
_only_use_kwargs: Don't pass args, only kwargs.
map_name: Name of a SC2 map. Run bin/map_list to get the full list of
known maps. Alternatively, pass a Map instance. Take a look at the
docs in maps/README.md for more information on available maps.
players: A list of Agent and Bot instances that specify who will play.
agent_race: Deprecated. Use players instead.
bot_race: Deprecated. Use players instead.
difficulty: Deprecated. Use players instead.
screen_size_px: Deprecated. Use agent_interface_formats instead.
minimap_size_px: Deprecated. Use agent_interface_formats instead.
agent_interface_format: A sequence containing one AgentInterfaceFormat
per agent, matching the order of agents specified in the players list.
Or a single AgentInterfaceFormat to be used for all agents.
discount: Returned as part of the observation.
discount_zero_after_timeout: If True, the discount will be zero
after the `game_steps_per_episode` timeout.
visualize: Whether to pop up a window showing the camera and feature
layers. This won't work without access to a window manager.
step_mul: How many game steps per agent step (action/observation). None
means use the map default.
realtime: Whether to use realtime mode. In this mode the game simulation
automatically advances (at 22.4 gameloops per second) rather than
being stepped manually. The number of game loops advanced with each
call to step() won't necessarily match the step_mul specified. The
environment will attempt to honour step_mul, returning observations
with that spacing as closely as possible. Game loops will be skipped
if they cannot be retrieved and processed quickly enough.
save_replay_episodes: Save a replay after this many episodes. Default of 0
means don't save replays.
replay_dir: Directory to save replays. Required with save_replay_episodes.
replay_prefix: An optional prefix to use when saving replays.
game_steps_per_episode: Game steps per episode, independent of the
step_mul. 0 means no limit. None means use the map default.
score_index: -1 means use the win/loss reward, >=0 is the index into the
score_cumulative with 0 being the curriculum score. None means use
the map default.
score_multiplier: How much to multiply the score by. Useful for negating.
random_seed: Random number seed to use when initializing the game. This
lets you run repeatable games/tests.
disable_fog: Whether to disable fog of war.
ensure_available_actions: Whether to throw an exception when an
unavailable action is passed to step().
Raises:
ValueError: if the agent_race, bot_race or difficulty are invalid.
ValueError: if too many players are requested for a map.
ValueError: if the resolutions aren't specified correctly.
DeprecationWarning: if screen_size_px or minimap_size_px are sent.
DeprecationWarning: if agent_race, bot_race or difficulty are sent. | f1568:c3:m0 |
def observation_spec(self): | return tuple(f.observation_spec() for f in self._features)<EOL> | Look at Features for full specs. | f1568:c3:m5 |
def action_spec(self): | return tuple(f.action_spec() for f in self._features)<EOL> | Look at Features for full specs. | f1568:c3:m6 |
Subsets and Splits