repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ryan-roemer/sphinx-bootstrap-theme | fabfile.py | get_rev | def get_rev(tag=True):
"""Get build revision.
@param tag Use git tag instead of hash?
"""
rev_cmd = "git describe --always --tag" if tag in (True, "True") else \
"git rev-parse HEAD"
return local(rev_cmd, capture=True).strip() | python | def get_rev(tag=True):
"""Get build revision.
@param tag Use git tag instead of hash?
"""
rev_cmd = "git describe --always --tag" if tag in (True, "True") else \
"git rev-parse HEAD"
return local(rev_cmd, capture=True).strip() | [
"def",
"get_rev",
"(",
"tag",
"=",
"True",
")",
":",
"rev_cmd",
"=",
"\"git describe --always --tag\"",
"if",
"tag",
"in",
"(",
"True",
",",
"\"True\"",
")",
"else",
"\"git rev-parse HEAD\"",
"return",
"local",
"(",
"rev_cmd",
",",
"capture",
"=",
"True",
")... | Get build revision.
@param tag Use git tag instead of hash? | [
"Get",
"build",
"revision",
"."
] | 69585281a300116fa9da37c29c333ab1cc5462ce | https://github.com/ryan-roemer/sphinx-bootstrap-theme/blob/69585281a300116fa9da37c29c333ab1cc5462ce/fabfile.py#L106-L113 | train | 205,900 |
ryan-roemer/sphinx-bootstrap-theme | fabfile.py | zip_bundle | def zip_bundle(tag=True):
"""Create zip file upload bundles.
@param tag Use git tag instead of hash?
"""
#rev = get_rev(tag)
rev = __version__
print("Cleaning old build files.")
clean()
local("mkdir -p build")
print("Bundling new files.")
with lcd("sphinx_bootstrap_theme/bootstrap"):
local("zip -r ../../build/bootstrap.zip .")
dest = os.path.abspath(os.path.join(DL_DIR, rev))
with lcd("build"):
local("mkdir -p %s" % dest)
local("cp bootstrap.zip %s" % dest)
print("Verifying contents.")
local("unzip -l bootstrap.zip") | python | def zip_bundle(tag=True):
"""Create zip file upload bundles.
@param tag Use git tag instead of hash?
"""
#rev = get_rev(tag)
rev = __version__
print("Cleaning old build files.")
clean()
local("mkdir -p build")
print("Bundling new files.")
with lcd("sphinx_bootstrap_theme/bootstrap"):
local("zip -r ../../build/bootstrap.zip .")
dest = os.path.abspath(os.path.join(DL_DIR, rev))
with lcd("build"):
local("mkdir -p %s" % dest)
local("cp bootstrap.zip %s" % dest)
print("Verifying contents.")
local("unzip -l bootstrap.zip") | [
"def",
"zip_bundle",
"(",
"tag",
"=",
"True",
")",
":",
"#rev = get_rev(tag)",
"rev",
"=",
"__version__",
"print",
"(",
"\"Cleaning old build files.\"",
")",
"clean",
"(",
")",
"local",
"(",
"\"mkdir -p build\"",
")",
"print",
"(",
"\"Bundling new files.\"",
")",
... | Create zip file upload bundles.
@param tag Use git tag instead of hash? | [
"Create",
"zip",
"file",
"upload",
"bundles",
"."
] | 69585281a300116fa9da37c29c333ab1cc5462ce | https://github.com/ryan-roemer/sphinx-bootstrap-theme/blob/69585281a300116fa9da37c29c333ab1cc5462ce/fabfile.py#L117-L140 | train | 205,901 |
arneb/django-messages | django_messages/admin.py | MessageAdmin.save_model | def save_model(self, request, obj, form, change):
"""
Saves the message for the recipient and looks in the form instance
for other possible recipients. Prevents duplication by excludin the
original recipient from the list of optional recipients.
When changing an existing message and choosing optional recipients,
the message is effectively resent to those users.
"""
obj.save()
if notification:
# Getting the appropriate notice labels for the sender and recipients.
if obj.parent_msg is None:
sender_label = 'messages_sent'
recipients_label = 'messages_received'
else:
sender_label = 'messages_replied'
recipients_label = 'messages_reply_received'
# Notification for the sender.
notification.send([obj.sender], sender_label, {'message': obj,})
if form.cleaned_data['group'] == 'all':
# send to all users
recipients = User.objects.exclude(pk=obj.recipient.pk)
else:
# send to a group of users
recipients = []
group = form.cleaned_data['group']
if group:
group = Group.objects.get(pk=group)
recipients.extend(
list(group.user_set.exclude(pk=obj.recipient.pk)))
# create messages for all found recipients
for user in recipients:
obj.pk = None
obj.recipient = user
obj.save()
if notification:
# Notification for the recipient.
notification.send([user], recipients_label, {'message' : obj,}) | python | def save_model(self, request, obj, form, change):
"""
Saves the message for the recipient and looks in the form instance
for other possible recipients. Prevents duplication by excludin the
original recipient from the list of optional recipients.
When changing an existing message and choosing optional recipients,
the message is effectively resent to those users.
"""
obj.save()
if notification:
# Getting the appropriate notice labels for the sender and recipients.
if obj.parent_msg is None:
sender_label = 'messages_sent'
recipients_label = 'messages_received'
else:
sender_label = 'messages_replied'
recipients_label = 'messages_reply_received'
# Notification for the sender.
notification.send([obj.sender], sender_label, {'message': obj,})
if form.cleaned_data['group'] == 'all':
# send to all users
recipients = User.objects.exclude(pk=obj.recipient.pk)
else:
# send to a group of users
recipients = []
group = form.cleaned_data['group']
if group:
group = Group.objects.get(pk=group)
recipients.extend(
list(group.user_set.exclude(pk=obj.recipient.pk)))
# create messages for all found recipients
for user in recipients:
obj.pk = None
obj.recipient = user
obj.save()
if notification:
# Notification for the recipient.
notification.send([user], recipients_label, {'message' : obj,}) | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"obj",
".",
"save",
"(",
")",
"if",
"notification",
":",
"# Getting the appropriate notice labels for the sender and recipients.",
"if",
"obj",
".",
"parent_msg",
... | Saves the message for the recipient and looks in the form instance
for other possible recipients. Prevents duplication by excludin the
original recipient from the list of optional recipients.
When changing an existing message and choosing optional recipients,
the message is effectively resent to those users. | [
"Saves",
"the",
"message",
"for",
"the",
"recipient",
"and",
"looks",
"in",
"the",
"form",
"instance",
"for",
"other",
"possible",
"recipients",
".",
"Prevents",
"duplication",
"by",
"excludin",
"the",
"original",
"recipient",
"from",
"the",
"list",
"of",
"opt... | 8e4b8e6660740e6f716ea4a7f4d77221baf166c5 | https://github.com/arneb/django-messages/blob/8e4b8e6660740e6f716ea4a7f4d77221baf166c5/django_messages/admin.py#L68-L110 | train | 205,902 |
arneb/django-messages | django_messages/models.py | inbox_count_for | def inbox_count_for(user):
"""
returns the number of unread messages for the given user but does not
mark them seen
"""
return Message.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True).count() | python | def inbox_count_for(user):
"""
returns the number of unread messages for the given user but does not
mark them seen
"""
return Message.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True).count() | [
"def",
"inbox_count_for",
"(",
"user",
")",
":",
"return",
"Message",
".",
"objects",
".",
"filter",
"(",
"recipient",
"=",
"user",
",",
"read_at__isnull",
"=",
"True",
",",
"recipient_deleted_at__isnull",
"=",
"True",
")",
".",
"count",
"(",
")"
] | returns the number of unread messages for the given user but does not
mark them seen | [
"returns",
"the",
"number",
"of",
"unread",
"messages",
"for",
"the",
"given",
"user",
"but",
"does",
"not",
"mark",
"them",
"seen"
] | 8e4b8e6660740e6f716ea4a7f4d77221baf166c5 | https://github.com/arneb/django-messages/blob/8e4b8e6660740e6f716ea4a7f4d77221baf166c5/django_messages/models.py#L95-L100 | train | 205,903 |
arneb/django-messages | django_messages/models.py | MessageManager.trash_for | def trash_for(self, user):
"""
Returns all messages that were either received or sent by the given
user and are marked as deleted.
"""
return self.filter(
recipient=user,
recipient_deleted_at__isnull=False,
) | self.filter(
sender=user,
sender_deleted_at__isnull=False,
) | python | def trash_for(self, user):
"""
Returns all messages that were either received or sent by the given
user and are marked as deleted.
"""
return self.filter(
recipient=user,
recipient_deleted_at__isnull=False,
) | self.filter(
sender=user,
sender_deleted_at__isnull=False,
) | [
"def",
"trash_for",
"(",
"self",
",",
"user",
")",
":",
"return",
"self",
".",
"filter",
"(",
"recipient",
"=",
"user",
",",
"recipient_deleted_at__isnull",
"=",
"False",
",",
")",
"|",
"self",
".",
"filter",
"(",
"sender",
"=",
"user",
",",
"sender_dele... | Returns all messages that were either received or sent by the given
user and are marked as deleted. | [
"Returns",
"all",
"messages",
"that",
"were",
"either",
"received",
"or",
"sent",
"by",
"the",
"given",
"user",
"and",
"are",
"marked",
"as",
"deleted",
"."
] | 8e4b8e6660740e6f716ea4a7f4d77221baf166c5 | https://github.com/arneb/django-messages/blob/8e4b8e6660740e6f716ea4a7f4d77221baf166c5/django_messages/models.py#L33-L44 | train | 205,904 |
arneb/django-messages | django_messages/views.py | delete | def delete(request, message_id, success_url=None):
"""
Marks a message as deleted by sender or recipient. The message is not
really removed from the database, because two users must delete a message
before it's save to remove it completely.
A cron-job should prune the database and remove old messages which are
deleted by both users.
As a side effect, this makes it easy to implement a trash with undelete.
You can pass ?next=/foo/bar/ via the url to redirect the user to a different
page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message.
"""
user = request.user
now = timezone.now()
message = get_object_or_404(Message, id=message_id)
deleted = False
if success_url is None:
success_url = reverse('messages_inbox')
if 'next' in request.GET:
success_url = request.GET['next']
if message.sender == user:
message.sender_deleted_at = now
deleted = True
if message.recipient == user:
message.recipient_deleted_at = now
deleted = True
if deleted:
message.save()
messages.info(request, _(u"Message successfully deleted."))
if notification:
notification.send([user], "messages_deleted", {'message': message,})
return HttpResponseRedirect(success_url)
raise Http404 | python | def delete(request, message_id, success_url=None):
"""
Marks a message as deleted by sender or recipient. The message is not
really removed from the database, because two users must delete a message
before it's save to remove it completely.
A cron-job should prune the database and remove old messages which are
deleted by both users.
As a side effect, this makes it easy to implement a trash with undelete.
You can pass ?next=/foo/bar/ via the url to redirect the user to a different
page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message.
"""
user = request.user
now = timezone.now()
message = get_object_or_404(Message, id=message_id)
deleted = False
if success_url is None:
success_url = reverse('messages_inbox')
if 'next' in request.GET:
success_url = request.GET['next']
if message.sender == user:
message.sender_deleted_at = now
deleted = True
if message.recipient == user:
message.recipient_deleted_at = now
deleted = True
if deleted:
message.save()
messages.info(request, _(u"Message successfully deleted."))
if notification:
notification.send([user], "messages_deleted", {'message': message,})
return HttpResponseRedirect(success_url)
raise Http404 | [
"def",
"delete",
"(",
"request",
",",
"message_id",
",",
"success_url",
"=",
"None",
")",
":",
"user",
"=",
"request",
".",
"user",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"message",
"=",
"get_object_or_404",
"(",
"Message",
",",
"id",
"=",
"mess... | Marks a message as deleted by sender or recipient. The message is not
really removed from the database, because two users must delete a message
before it's save to remove it completely.
A cron-job should prune the database and remove old messages which are
deleted by both users.
As a side effect, this makes it easy to implement a trash with undelete.
You can pass ?next=/foo/bar/ via the url to redirect the user to a different
page (e.g. `/foo/bar/`) than ``success_url`` after deletion of the message. | [
"Marks",
"a",
"message",
"as",
"deleted",
"by",
"sender",
"or",
"recipient",
".",
"The",
"message",
"is",
"not",
"really",
"removed",
"from",
"the",
"database",
"because",
"two",
"users",
"must",
"delete",
"a",
"message",
"before",
"it",
"s",
"save",
"to",... | 8e4b8e6660740e6f716ea4a7f4d77221baf166c5 | https://github.com/arneb/django-messages/blob/8e4b8e6660740e6f716ea4a7f4d77221baf166c5/django_messages/views.py#L131-L163 | train | 205,905 |
arneb/django-messages | django_messages/views.py | view | def view(request, message_id, form_class=ComposeForm, quote_helper=format_quote,
subject_template=_(u"Re: %(subject)s"),
template_name='django_messages/view.html'):
"""
Shows a single message.``message_id`` argument is required.
The user is only allowed to see the message, if he is either
the sender or the recipient. If the user is not allowed a 404
is raised.
If the user is the recipient and the message is unread
``read_at`` is set to the current datetime.
If the user is the recipient a reply form will be added to the
tenplate context, otherwise 'reply_form' will be None.
"""
user = request.user
now = timezone.now()
message = get_object_or_404(Message, id=message_id)
if (message.sender != user) and (message.recipient != user):
raise Http404
if message.read_at is None and message.recipient == user:
message.read_at = now
message.save()
context = {'message': message, 'reply_form': None}
if message.recipient == user:
form = form_class(initial={
'body': quote_helper(message.sender, message.body),
'subject': subject_template % {'subject': message.subject},
'recipient': [message.sender,]
})
context['reply_form'] = form
return render(request, template_name, context) | python | def view(request, message_id, form_class=ComposeForm, quote_helper=format_quote,
subject_template=_(u"Re: %(subject)s"),
template_name='django_messages/view.html'):
"""
Shows a single message.``message_id`` argument is required.
The user is only allowed to see the message, if he is either
the sender or the recipient. If the user is not allowed a 404
is raised.
If the user is the recipient and the message is unread
``read_at`` is set to the current datetime.
If the user is the recipient a reply form will be added to the
tenplate context, otherwise 'reply_form' will be None.
"""
user = request.user
now = timezone.now()
message = get_object_or_404(Message, id=message_id)
if (message.sender != user) and (message.recipient != user):
raise Http404
if message.read_at is None and message.recipient == user:
message.read_at = now
message.save()
context = {'message': message, 'reply_form': None}
if message.recipient == user:
form = form_class(initial={
'body': quote_helper(message.sender, message.body),
'subject': subject_template % {'subject': message.subject},
'recipient': [message.sender,]
})
context['reply_form'] = form
return render(request, template_name, context) | [
"def",
"view",
"(",
"request",
",",
"message_id",
",",
"form_class",
"=",
"ComposeForm",
",",
"quote_helper",
"=",
"format_quote",
",",
"subject_template",
"=",
"_",
"(",
"u\"Re: %(subject)s\"",
")",
",",
"template_name",
"=",
"'django_messages/view.html'",
")",
"... | Shows a single message.``message_id`` argument is required.
The user is only allowed to see the message, if he is either
the sender or the recipient. If the user is not allowed a 404
is raised.
If the user is the recipient and the message is unread
``read_at`` is set to the current datetime.
If the user is the recipient a reply form will be added to the
tenplate context, otherwise 'reply_form' will be None. | [
"Shows",
"a",
"single",
"message",
".",
"message_id",
"argument",
"is",
"required",
".",
"The",
"user",
"is",
"only",
"allowed",
"to",
"see",
"the",
"message",
"if",
"he",
"is",
"either",
"the",
"sender",
"or",
"the",
"recipient",
".",
"If",
"the",
"user... | 8e4b8e6660740e6f716ea4a7f4d77221baf166c5 | https://github.com/arneb/django-messages/blob/8e4b8e6660740e6f716ea4a7f4d77221baf166c5/django_messages/views.py#L193-L223 | train | 205,906 |
arneb/django-messages | django_messages/utils.py | format_quote | def format_quote(sender, body):
"""
Wraps text at 55 chars and prepends each
line with `> `.
Used for quoting messages in replies.
"""
lines = wrap(body, 55).split('\n')
for i, line in enumerate(lines):
lines[i] = "> %s" % line
quote = '\n'.join(lines)
return ugettext(u"%(sender)s wrote:\n%(body)s") % {
'sender': sender,
'body': quote
} | python | def format_quote(sender, body):
"""
Wraps text at 55 chars and prepends each
line with `> `.
Used for quoting messages in replies.
"""
lines = wrap(body, 55).split('\n')
for i, line in enumerate(lines):
lines[i] = "> %s" % line
quote = '\n'.join(lines)
return ugettext(u"%(sender)s wrote:\n%(body)s") % {
'sender': sender,
'body': quote
} | [
"def",
"format_quote",
"(",
"sender",
",",
"body",
")",
":",
"lines",
"=",
"wrap",
"(",
"body",
",",
"55",
")",
".",
"split",
"(",
"'\\n'",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"lines",
"[",
"i",
"]",
"=",
"\... | Wraps text at 55 chars and prepends each
line with `> `.
Used for quoting messages in replies. | [
"Wraps",
"text",
"at",
"55",
"chars",
"and",
"prepends",
"each",
"line",
"with",
">",
".",
"Used",
"for",
"quoting",
"messages",
"in",
"replies",
"."
] | 8e4b8e6660740e6f716ea4a7f4d77221baf166c5 | https://github.com/arneb/django-messages/blob/8e4b8e6660740e6f716ea4a7f4d77221baf166c5/django_messages/utils.py#L16-L29 | train | 205,907 |
amadeus4dev/amadeus-python | amadeus/reference_data/_location.py | Location.get | def get(self, **params):
'''
Returns details for a specific airport.
.. code-block:: python
amadeus.reference_data.location('ALHR').get()
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.client.get('/v1/reference-data/locations/{0}'
.format(self.location_id), **params) | python | def get(self, **params):
'''
Returns details for a specific airport.
.. code-block:: python
amadeus.reference_data.location('ALHR').get()
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.client.get('/v1/reference-data/locations/{0}'
.format(self.location_id), **params) | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"client",
".",
"get",
"(",
"'/v1/reference-data/locations/{0}'",
".",
"format",
"(",
"self",
".",
"location_id",
")",
",",
"*",
"*",
"params",
")"
] | Returns details for a specific airport.
.. code-block:: python
amadeus.reference_data.location('ALHR').get()
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed | [
"Returns",
"details",
"for",
"a",
"specific",
"airport",
"."
] | afb93667d2cd486ddc7f4a7f29f222f04453a44a | https://github.com/amadeus4dev/amadeus-python/blob/afb93667d2cd486ddc7f4a7f29f222f04453a44a/amadeus/reference_data/_location.py#L9-L21 | train | 205,908 |
amadeus4dev/amadeus-python | amadeus/shopping/_hotel_offer.py | HotelOffer.get | def get(self, **params):
'''
Returns details for a specific offer.
.. code-block:: python
amadeus.shopping.hotel_offer('XXX').get
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.client.get('/v2/shopping/hotel-offers/{0}'
.format(self.offer_id), **params) | python | def get(self, **params):
'''
Returns details for a specific offer.
.. code-block:: python
amadeus.shopping.hotel_offer('XXX').get
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed
'''
return self.client.get('/v2/shopping/hotel-offers/{0}'
.format(self.offer_id), **params) | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"client",
".",
"get",
"(",
"'/v2/shopping/hotel-offers/{0}'",
".",
"format",
"(",
"self",
".",
"offer_id",
")",
",",
"*",
"*",
"params",
")"
] | Returns details for a specific offer.
.. code-block:: python
amadeus.shopping.hotel_offer('XXX').get
:rtype: amadeus.Response
:raises amadeus.ResponseError: if the request could not be completed | [
"Returns",
"details",
"for",
"a",
"specific",
"offer",
"."
] | afb93667d2cd486ddc7f4a7f29f222f04453a44a | https://github.com/amadeus4dev/amadeus-python/blob/afb93667d2cd486ddc7f4a7f29f222f04453a44a/amadeus/shopping/_hotel_offer.py#L9-L21 | train | 205,909 |
ensime/ensime-vim | ensime_shared/typecheck.py | TypecheckHandler.buffer_typechecks | def buffer_typechecks(self, call_id, payload):
"""Adds typecheck events to the buffer"""
if self.currently_buffering_typechecks:
for note in payload['notes']:
self.buffered_notes.append(note) | python | def buffer_typechecks(self, call_id, payload):
"""Adds typecheck events to the buffer"""
if self.currently_buffering_typechecks:
for note in payload['notes']:
self.buffered_notes.append(note) | [
"def",
"buffer_typechecks",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"if",
"self",
".",
"currently_buffering_typechecks",
":",
"for",
"note",
"in",
"payload",
"[",
"'notes'",
"]",
":",
"self",
".",
"buffered_notes",
".",
"append",
"(",
"note",
... | Adds typecheck events to the buffer | [
"Adds",
"typecheck",
"events",
"to",
"the",
"buffer"
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/typecheck.py#L11-L15 | train | 205,910 |
ensime/ensime-vim | ensime_shared/typecheck.py | TypecheckHandler.buffer_typechecks_and_display | def buffer_typechecks_and_display(self, call_id, payload):
"""Adds typecheck events to the buffer, and displays them right away.
This is a workaround for this issue:
https://github.com/ensime/ensime-server/issues/1616
"""
self.buffer_typechecks(call_id, payload)
self.editor.display_notes(self.buffered_notes) | python | def buffer_typechecks_and_display(self, call_id, payload):
"""Adds typecheck events to the buffer, and displays them right away.
This is a workaround for this issue:
https://github.com/ensime/ensime-server/issues/1616
"""
self.buffer_typechecks(call_id, payload)
self.editor.display_notes(self.buffered_notes) | [
"def",
"buffer_typechecks_and_display",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"self",
".",
"buffer_typechecks",
"(",
"call_id",
",",
"payload",
")",
"self",
".",
"editor",
".",
"display_notes",
"(",
"self",
".",
"buffered_notes",
")"
] | Adds typecheck events to the buffer, and displays them right away.
This is a workaround for this issue:
https://github.com/ensime/ensime-server/issues/1616 | [
"Adds",
"typecheck",
"events",
"to",
"the",
"buffer",
"and",
"displays",
"them",
"right",
"away",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/typecheck.py#L17-L24 | train | 205,911 |
ensime/ensime-vim | ensime_shared/typecheck.py | TypecheckHandler.handle_typecheck_complete | def handle_typecheck_complete(self, call_id, payload):
"""Handles ``NewScalaNotesEvent```.
Calls editor to display/highlight line notes and clears notes buffer.
"""
self.log.debug('handle_typecheck_complete: in')
if not self.currently_buffering_typechecks:
self.log.debug('Completed typecheck was not requested by user, not displaying notes')
return
self.editor.display_notes(self.buffered_notes)
self.currently_buffering_typechecks = False
self.buffered_notes = [] | python | def handle_typecheck_complete(self, call_id, payload):
"""Handles ``NewScalaNotesEvent```.
Calls editor to display/highlight line notes and clears notes buffer.
"""
self.log.debug('handle_typecheck_complete: in')
if not self.currently_buffering_typechecks:
self.log.debug('Completed typecheck was not requested by user, not displaying notes')
return
self.editor.display_notes(self.buffered_notes)
self.currently_buffering_typechecks = False
self.buffered_notes = [] | [
"def",
"handle_typecheck_complete",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'handle_typecheck_complete: in'",
")",
"if",
"not",
"self",
".",
"currently_buffering_typechecks",
":",
"self",
".",
"log",
".",
... | Handles ``NewScalaNotesEvent```.
Calls editor to display/highlight line notes and clears notes buffer. | [
"Handles",
"NewScalaNotesEvent",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/typecheck.py#L32-L44 | train | 205,912 |
ensime/ensime-vim | ensime_shared/ensime.py | execute_with_client | def execute_with_client(quiet=False,
bootstrap_server=False,
create_client=True):
"""Decorator that gets a client and performs an operation on it."""
def wrapper(f):
def wrapper2(self, *args, **kwargs):
client = self.current_client(
quiet=quiet,
bootstrap_server=bootstrap_server,
create_client=create_client)
if client and client.running:
return f(self, client, *args, **kwargs)
return wrapper2
return wrapper | python | def execute_with_client(quiet=False,
bootstrap_server=False,
create_client=True):
"""Decorator that gets a client and performs an operation on it."""
def wrapper(f):
def wrapper2(self, *args, **kwargs):
client = self.current_client(
quiet=quiet,
bootstrap_server=bootstrap_server,
create_client=create_client)
if client and client.running:
return f(self, client, *args, **kwargs)
return wrapper2
return wrapper | [
"def",
"execute_with_client",
"(",
"quiet",
"=",
"False",
",",
"bootstrap_server",
"=",
"False",
",",
"create_client",
"=",
"True",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"def",
"wrapper2",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs... | Decorator that gets a client and performs an operation on it. | [
"Decorator",
"that",
"gets",
"a",
"client",
"and",
"performs",
"an",
"operation",
"on",
"it",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L12-L27 | train | 205,913 |
ensime/ensime-vim | ensime_shared/ensime.py | Ensime.client_status | def client_status(self, config_path):
"""Get status of client for a project, given path to its config."""
c = self.client_for(config_path)
status = "stopped"
if not c or not c.ensime:
status = 'unloaded'
elif c.ensime.is_ready():
status = 'ready'
elif c.ensime.is_running():
status = 'startup'
elif c.ensime.aborted():
status = 'aborted'
return status | python | def client_status(self, config_path):
"""Get status of client for a project, given path to its config."""
c = self.client_for(config_path)
status = "stopped"
if not c or not c.ensime:
status = 'unloaded'
elif c.ensime.is_ready():
status = 'ready'
elif c.ensime.is_running():
status = 'startup'
elif c.ensime.aborted():
status = 'aborted'
return status | [
"def",
"client_status",
"(",
"self",
",",
"config_path",
")",
":",
"c",
"=",
"self",
".",
"client_for",
"(",
"config_path",
")",
"status",
"=",
"\"stopped\"",
"if",
"not",
"c",
"or",
"not",
"c",
".",
"ensime",
":",
"status",
"=",
"'unloaded'",
"elif",
... | Get status of client for a project, given path to its config. | [
"Get",
"status",
"of",
"client",
"for",
"a",
"project",
"given",
"path",
"to",
"its",
"config",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L67-L79 | train | 205,914 |
ensime/ensime-vim | ensime_shared/ensime.py | Ensime.current_client | def current_client(self, quiet, bootstrap_server, create_client):
"""Return the client for current file in the editor."""
current_file = self._vim.current.buffer.name
config_path = ProjectConfig.find_from(current_file)
if config_path:
return self.client_for(
config_path,
quiet=quiet,
bootstrap_server=bootstrap_server,
create_client=create_client) | python | def current_client(self, quiet, bootstrap_server, create_client):
"""Return the client for current file in the editor."""
current_file = self._vim.current.buffer.name
config_path = ProjectConfig.find_from(current_file)
if config_path:
return self.client_for(
config_path,
quiet=quiet,
bootstrap_server=bootstrap_server,
create_client=create_client) | [
"def",
"current_client",
"(",
"self",
",",
"quiet",
",",
"bootstrap_server",
",",
"create_client",
")",
":",
"current_file",
"=",
"self",
".",
"_vim",
".",
"current",
".",
"buffer",
".",
"name",
"config_path",
"=",
"ProjectConfig",
".",
"find_from",
"(",
"cu... | Return the client for current file in the editor. | [
"Return",
"the",
"client",
"for",
"current",
"file",
"in",
"the",
"editor",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L86-L95 | train | 205,915 |
ensime/ensime-vim | ensime_shared/ensime.py | Ensime.client_for | def client_for(self, config_path, quiet=False, bootstrap_server=False,
create_client=False):
"""Get a cached client for a project, otherwise create one."""
client = None
abs_path = os.path.abspath(config_path)
if abs_path in self.clients:
client = self.clients[abs_path]
elif create_client:
client = self.create_client(config_path)
if client.setup(quiet=quiet, bootstrap_server=bootstrap_server):
self.clients[abs_path] = client
return client | python | def client_for(self, config_path, quiet=False, bootstrap_server=False,
create_client=False):
"""Get a cached client for a project, otherwise create one."""
client = None
abs_path = os.path.abspath(config_path)
if abs_path in self.clients:
client = self.clients[abs_path]
elif create_client:
client = self.create_client(config_path)
if client.setup(quiet=quiet, bootstrap_server=bootstrap_server):
self.clients[abs_path] = client
return client | [
"def",
"client_for",
"(",
"self",
",",
"config_path",
",",
"quiet",
"=",
"False",
",",
"bootstrap_server",
"=",
"False",
",",
"create_client",
"=",
"False",
")",
":",
"client",
"=",
"None",
"abs_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"config... | Get a cached client for a project, otherwise create one. | [
"Get",
"a",
"cached",
"client",
"for",
"a",
"project",
"otherwise",
"create",
"one",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L97-L108 | train | 205,916 |
ensime/ensime-vim | ensime_shared/ensime.py | Ensime.disable_plugin | def disable_plugin(self):
"""Disable ensime-vim, in the event of an error we can't usefully
recover from.
Todo:
This is incomplete and unreliable, see:
https://github.com/ensime/ensime-vim/issues/294
If used from a secondary thread, this may need to use threadsafe
Vim calls where available -- see :meth:`Editor.raw_message`.
"""
for path in self.runtime_paths():
self._vim.command('set runtimepath-={}'.format(path)) | python | def disable_plugin(self):
"""Disable ensime-vim, in the event of an error we can't usefully
recover from.
Todo:
This is incomplete and unreliable, see:
https://github.com/ensime/ensime-vim/issues/294
If used from a secondary thread, this may need to use threadsafe
Vim calls where available -- see :meth:`Editor.raw_message`.
"""
for path in self.runtime_paths():
self._vim.command('set runtimepath-={}'.format(path)) | [
"def",
"disable_plugin",
"(",
"self",
")",
":",
"for",
"path",
"in",
"self",
".",
"runtime_paths",
"(",
")",
":",
"self",
".",
"_vim",
".",
"command",
"(",
"'set runtimepath-={}'",
".",
"format",
"(",
"path",
")",
")"
] | Disable ensime-vim, in the event of an error we can't usefully
recover from.
Todo:
This is incomplete and unreliable, see:
https://github.com/ensime/ensime-vim/issues/294
If used from a secondary thread, this may need to use threadsafe
Vim calls where available -- see :meth:`Editor.raw_message`. | [
"Disable",
"ensime",
"-",
"vim",
"in",
"the",
"event",
"of",
"an",
"error",
"we",
"can",
"t",
"usefully",
"recover",
"from",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L133-L145 | train | 205,917 |
ensime/ensime-vim | ensime_shared/ensime.py | Ensime.runtime_paths | def runtime_paths(self): # TODO: memoize
"""All the runtime paths of ensime-vim plugin files."""
runtimepath = self._vim.options['runtimepath']
plugin = "ensime-vim"
paths = []
for path in runtimepath.split(','):
if plugin in path:
paths.append(os.path.expanduser(path))
return paths | python | def runtime_paths(self): # TODO: memoize
"""All the runtime paths of ensime-vim plugin files."""
runtimepath = self._vim.options['runtimepath']
plugin = "ensime-vim"
paths = []
for path in runtimepath.split(','):
if plugin in path:
paths.append(os.path.expanduser(path))
return paths | [
"def",
"runtime_paths",
"(",
"self",
")",
":",
"# TODO: memoize",
"runtimepath",
"=",
"self",
".",
"_vim",
".",
"options",
"[",
"'runtimepath'",
"]",
"plugin",
"=",
"\"ensime-vim\"",
"paths",
"=",
"[",
"]",
"for",
"path",
"in",
"runtimepath",
".",
"split",
... | All the runtime paths of ensime-vim plugin files. | [
"All",
"the",
"runtime",
"paths",
"of",
"ensime",
"-",
"vim",
"plugin",
"files",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L149-L159 | train | 205,918 |
ensime/ensime-vim | ensime_shared/ensime.py | Ensime.tick_clients | def tick_clients(self):
"""Trigger the periodic tick function in the client."""
if not self._ticker:
self._create_ticker()
for client in self.clients.values():
self._ticker.tick(client) | python | def tick_clients(self):
"""Trigger the periodic tick function in the client."""
if not self._ticker:
self._create_ticker()
for client in self.clients.values():
self._ticker.tick(client) | [
"def",
"tick_clients",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ticker",
":",
"self",
".",
"_create_ticker",
"(",
")",
"for",
"client",
"in",
"self",
".",
"clients",
".",
"values",
"(",
")",
":",
"self",
".",
"_ticker",
".",
"tick",
"(",
... | Trigger the periodic tick function in the client. | [
"Trigger",
"the",
"periodic",
"tick",
"function",
"in",
"the",
"client",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L161-L167 | train | 205,919 |
ensime/ensime-vim | ensime_shared/ensime.py | Ensime.fun_en_complete_func | def fun_en_complete_func(self, client, findstart_and_base, base=None):
"""Invokable function from vim and neovim to perform completion."""
if isinstance(findstart_and_base, list):
# Invoked by neovim
findstart = findstart_and_base[0]
base = findstart_and_base[1]
else:
# Invoked by vim
findstart = findstart_and_base
return client.complete_func(findstart, base) | python | def fun_en_complete_func(self, client, findstart_and_base, base=None):
"""Invokable function from vim and neovim to perform completion."""
if isinstance(findstart_and_base, list):
# Invoked by neovim
findstart = findstart_and_base[0]
base = findstart_and_base[1]
else:
# Invoked by vim
findstart = findstart_and_base
return client.complete_func(findstart, base) | [
"def",
"fun_en_complete_func",
"(",
"self",
",",
"client",
",",
"findstart_and_base",
",",
"base",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"findstart_and_base",
",",
"list",
")",
":",
"# Invoked by neovim",
"findstart",
"=",
"findstart_and_base",
"[",
"0... | Invokable function from vim and neovim to perform completion. | [
"Invokable",
"function",
"from",
"vim",
"and",
"neovim",
"to",
"perform",
"completion",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ensime.py#L320-L329 | train | 205,920 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.append | def append(self, text, afterline=None):
"""Append text to the current buffer.
Args:
text (str or Sequence[str]): One or many lines of text to append.
afterline (Optional[int]):
Line number to append after. If 0, text is prepended before the
first line; if ``None``, at end of the buffer.
"""
if afterline:
self._vim.current.buffer.append(text, afterline)
else:
self._vim.current.buffer.append(text) | python | def append(self, text, afterline=None):
"""Append text to the current buffer.
Args:
text (str or Sequence[str]): One or many lines of text to append.
afterline (Optional[int]):
Line number to append after. If 0, text is prepended before the
first line; if ``None``, at end of the buffer.
"""
if afterline:
self._vim.current.buffer.append(text, afterline)
else:
self._vim.current.buffer.append(text) | [
"def",
"append",
"(",
"self",
",",
"text",
",",
"afterline",
"=",
"None",
")",
":",
"if",
"afterline",
":",
"self",
".",
"_vim",
".",
"current",
".",
"buffer",
".",
"append",
"(",
"text",
",",
"afterline",
")",
"else",
":",
"self",
".",
"_vim",
"."... | Append text to the current buffer.
Args:
text (str or Sequence[str]): One or many lines of text to append.
afterline (Optional[int]):
Line number to append after. If 0, text is prepended before the
first line; if ``None``, at end of the buffer. | [
"Append",
"text",
"to",
"the",
"current",
"buffer",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L21-L33 | train | 205,921 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.getline | def getline(self, lnum=None):
"""Get a line from the current buffer.
Args:
lnum (Optional[str]): Number of the line to get, current if ``None``.
Todo:
- Give this more behavior of Vim ``getline()``?
- ``buffer[index]`` is zero-based, this is probably too confusing
"""
return self._vim.current.buffer[lnum] if lnum else self._vim.current.line | python | def getline(self, lnum=None):
"""Get a line from the current buffer.
Args:
lnum (Optional[str]): Number of the line to get, current if ``None``.
Todo:
- Give this more behavior of Vim ``getline()``?
- ``buffer[index]`` is zero-based, this is probably too confusing
"""
return self._vim.current.buffer[lnum] if lnum else self._vim.current.line | [
"def",
"getline",
"(",
"self",
",",
"lnum",
"=",
"None",
")",
":",
"return",
"self",
".",
"_vim",
".",
"current",
".",
"buffer",
"[",
"lnum",
"]",
"if",
"lnum",
"else",
"self",
".",
"_vim",
".",
"current",
".",
"line"
] | Get a line from the current buffer.
Args:
lnum (Optional[str]): Number of the line to get, current if ``None``.
Todo:
- Give this more behavior of Vim ``getline()``?
- ``buffer[index]`` is zero-based, this is probably too confusing | [
"Get",
"a",
"line",
"from",
"the",
"current",
"buffer",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L58-L68 | train | 205,922 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.getlines | def getlines(self, bufnr=None):
"""Get all lines of a buffer as a list.
Args:
bufnr (Optional[int]): A Vim buffer number, current if ``None``.
Returns:
List[str]
"""
buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer
return buf[:] | python | def getlines(self, bufnr=None):
"""Get all lines of a buffer as a list.
Args:
bufnr (Optional[int]): A Vim buffer number, current if ``None``.
Returns:
List[str]
"""
buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer
return buf[:] | [
"def",
"getlines",
"(",
"self",
",",
"bufnr",
"=",
"None",
")",
":",
"buf",
"=",
"self",
".",
"_vim",
".",
"buffers",
"[",
"bufnr",
"]",
"if",
"bufnr",
"else",
"self",
".",
"_vim",
".",
"current",
".",
"buffer",
"return",
"buf",
"[",
":",
"]"
] | Get all lines of a buffer as a list.
Args:
bufnr (Optional[int]): A Vim buffer number, current if ``None``.
Returns:
List[str] | [
"Get",
"all",
"lines",
"of",
"a",
"buffer",
"as",
"a",
"list",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L70-L80 | train | 205,923 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.menu | def menu(self, prompt, choices):
"""Presents a selection menu and returns the user's choice.
Args:
prompt (str): Text to ask the user what to select.
choices (Sequence[str]): Values for the user to select from.
Returns:
The value selected by the user, or ``None``.
Todo:
Nice opportunity to provide a hook for Unite.vim, etc. here.
"""
menu = [prompt] + [
"{0}. {1}".format(*choice) for choice in enumerate(choices, start=1)
]
command = 'inputlist({})'.format(repr(menu))
choice = int(self._vim.eval(command))
# Vim returns weird stuff if user clicks outside choices with mouse
if not 0 < choice < len(menu):
return
return choices[choice - 1] | python | def menu(self, prompt, choices):
"""Presents a selection menu and returns the user's choice.
Args:
prompt (str): Text to ask the user what to select.
choices (Sequence[str]): Values for the user to select from.
Returns:
The value selected by the user, or ``None``.
Todo:
Nice opportunity to provide a hook for Unite.vim, etc. here.
"""
menu = [prompt] + [
"{0}. {1}".format(*choice) for choice in enumerate(choices, start=1)
]
command = 'inputlist({})'.format(repr(menu))
choice = int(self._vim.eval(command))
# Vim returns weird stuff if user clicks outside choices with mouse
if not 0 < choice < len(menu):
return
return choices[choice - 1] | [
"def",
"menu",
"(",
"self",
",",
"prompt",
",",
"choices",
")",
":",
"menu",
"=",
"[",
"prompt",
"]",
"+",
"[",
"\"{0}. {1}\"",
".",
"format",
"(",
"*",
"choice",
")",
"for",
"choice",
"in",
"enumerate",
"(",
"choices",
",",
"start",
"=",
"1",
")",... | Presents a selection menu and returns the user's choice.
Args:
prompt (str): Text to ask the user what to select.
choices (Sequence[str]): Values for the user to select from.
Returns:
The value selected by the user, or ``None``.
Todo:
Nice opportunity to provide a hook for Unite.vim, etc. here. | [
"Presents",
"a",
"selection",
"menu",
"and",
"returns",
"the",
"user",
"s",
"choice",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L95-L118 | train | 205,924 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.set_buffer_options | def set_buffer_options(self, options, bufnr=None):
"""Set buffer-local options for a buffer, defaulting to current.
Args:
options (dict):
Options to set, with keys being Vim option names. For Boolean
options, use a :class:`bool` value as expected, e.g.
``{'buflisted': False}`` for ``setlocal nobuflisted``.
bufnr (Optional[int]):
A Vim buffer number, as you might get from VimL ``bufnr('%')``
or Python ``vim.current.buffer.number``. If ``None``, options
are set on the current buffer.
"""
buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer
# Special case handling for filetype, see doc on ``set_filetype``
filetype = options.pop('filetype', None)
if filetype:
self.set_filetype(filetype)
for opt, value in options.items():
buf.options[opt] = value | python | def set_buffer_options(self, options, bufnr=None):
"""Set buffer-local options for a buffer, defaulting to current.
Args:
options (dict):
Options to set, with keys being Vim option names. For Boolean
options, use a :class:`bool` value as expected, e.g.
``{'buflisted': False}`` for ``setlocal nobuflisted``.
bufnr (Optional[int]):
A Vim buffer number, as you might get from VimL ``bufnr('%')``
or Python ``vim.current.buffer.number``. If ``None``, options
are set on the current buffer.
"""
buf = self._vim.buffers[bufnr] if bufnr else self._vim.current.buffer
# Special case handling for filetype, see doc on ``set_filetype``
filetype = options.pop('filetype', None)
if filetype:
self.set_filetype(filetype)
for opt, value in options.items():
buf.options[opt] = value | [
"def",
"set_buffer_options",
"(",
"self",
",",
"options",
",",
"bufnr",
"=",
"None",
")",
":",
"buf",
"=",
"self",
".",
"_vim",
".",
"buffers",
"[",
"bufnr",
"]",
"if",
"bufnr",
"else",
"self",
".",
"_vim",
".",
"current",
".",
"buffer",
"# Special cas... | Set buffer-local options for a buffer, defaulting to current.
Args:
options (dict):
Options to set, with keys being Vim option names. For Boolean
options, use a :class:`bool` value as expected, e.g.
``{'buflisted': False}`` for ``setlocal nobuflisted``.
bufnr (Optional[int]):
A Vim buffer number, as you might get from VimL ``bufnr('%')``
or Python ``vim.current.buffer.number``. If ``None``, options
are set on the current buffer. | [
"Set",
"buffer",
"-",
"local",
"options",
"for",
"a",
"buffer",
"defaulting",
"to",
"current",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L125-L146 | train | 205,925 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.set_filetype | def set_filetype(self, filetype, bufnr=None):
"""Set filetype for a buffer.
Note: it's a quirk of Vim's Python API that using the buffer.options
dictionary to set filetype does not trigger ``FileType`` autocommands,
hence this implementation executes as a command instead.
Args:
filetype (str): The filetype to set.
bufnr (Optional[int]): A Vim buffer number, current if ``None``.
"""
if bufnr:
self._vim.command(str(bufnr) + 'bufdo set filetype=' + filetype)
else:
self._vim.command('set filetype=' + filetype) | python | def set_filetype(self, filetype, bufnr=None):
"""Set filetype for a buffer.
Note: it's a quirk of Vim's Python API that using the buffer.options
dictionary to set filetype does not trigger ``FileType`` autocommands,
hence this implementation executes as a command instead.
Args:
filetype (str): The filetype to set.
bufnr (Optional[int]): A Vim buffer number, current if ``None``.
"""
if bufnr:
self._vim.command(str(bufnr) + 'bufdo set filetype=' + filetype)
else:
self._vim.command('set filetype=' + filetype) | [
"def",
"set_filetype",
"(",
"self",
",",
"filetype",
",",
"bufnr",
"=",
"None",
")",
":",
"if",
"bufnr",
":",
"self",
".",
"_vim",
".",
"command",
"(",
"str",
"(",
"bufnr",
")",
"+",
"'bufdo set filetype='",
"+",
"filetype",
")",
"else",
":",
"self",
... | Set filetype for a buffer.
Note: it's a quirk of Vim's Python API that using the buffer.options
dictionary to set filetype does not trigger ``FileType`` autocommands,
hence this implementation executes as a command instead.
Args:
filetype (str): The filetype to set.
bufnr (Optional[int]): A Vim buffer number, current if ``None``. | [
"Set",
"filetype",
"for",
"a",
"buffer",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L149-L163 | train | 205,926 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.split_window | def split_window(self, fpath, vertical=False, size=None, bufopts=None):
"""Open file in a new split window.
Args:
fpath (str): Path of the file to open. If ``None``, a new empty
split is created.
vertical (bool): Whether to open a vertical split.
size (Optional[int]): The height (or width) to set for the new window.
bufopts (Optional[dict]): Buffer-local options to set in the split window.
See :func:`.set_buffer_options`.
"""
command = 'split {}'.format(fpath) if fpath else 'new'
if vertical:
command = 'v' + command
if size:
command = str(size) + command
self._vim.command(command)
if bufopts:
self.set_buffer_options(bufopts) | python | def split_window(self, fpath, vertical=False, size=None, bufopts=None):
"""Open file in a new split window.
Args:
fpath (str): Path of the file to open. If ``None``, a new empty
split is created.
vertical (bool): Whether to open a vertical split.
size (Optional[int]): The height (or width) to set for the new window.
bufopts (Optional[dict]): Buffer-local options to set in the split window.
See :func:`.set_buffer_options`.
"""
command = 'split {}'.format(fpath) if fpath else 'new'
if vertical:
command = 'v' + command
if size:
command = str(size) + command
self._vim.command(command)
if bufopts:
self.set_buffer_options(bufopts) | [
"def",
"split_window",
"(",
"self",
",",
"fpath",
",",
"vertical",
"=",
"False",
",",
"size",
"=",
"None",
",",
"bufopts",
"=",
"None",
")",
":",
"command",
"=",
"'split {}'",
".",
"format",
"(",
"fpath",
")",
"if",
"fpath",
"else",
"'new'",
"if",
"v... | Open file in a new split window.
Args:
fpath (str): Path of the file to open. If ``None``, a new empty
split is created.
vertical (bool): Whether to open a vertical split.
size (Optional[int]): The height (or width) to set for the new window.
bufopts (Optional[dict]): Buffer-local options to set in the split window.
See :func:`.set_buffer_options`. | [
"Open",
"file",
"in",
"a",
"new",
"split",
"window",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L165-L185 | train | 205,927 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.write | def write(self, noautocmd=False):
"""Writes the file of the current buffer.
Args:
noautocmd (bool): If true, write will skip autocommands.
Todo:
We should consider whether ``SourceFileInfo`` can replace most
usage of noautocmd. See #298
"""
cmd = 'noautocmd write' if noautocmd else 'write'
self._vim.command(cmd) | python | def write(self, noautocmd=False):
"""Writes the file of the current buffer.
Args:
noautocmd (bool): If true, write will skip autocommands.
Todo:
We should consider whether ``SourceFileInfo`` can replace most
usage of noautocmd. See #298
"""
cmd = 'noautocmd write' if noautocmd else 'write'
self._vim.command(cmd) | [
"def",
"write",
"(",
"self",
",",
"noautocmd",
"=",
"False",
")",
":",
"cmd",
"=",
"'noautocmd write'",
"if",
"noautocmd",
"else",
"'write'",
"self",
".",
"_vim",
".",
"command",
"(",
"cmd",
")"
] | Writes the file of the current buffer.
Args:
noautocmd (bool): If true, write will skip autocommands.
Todo:
We should consider whether ``SourceFileInfo`` can replace most
usage of noautocmd. See #298 | [
"Writes",
"the",
"file",
"of",
"the",
"current",
"buffer",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L187-L198 | train | 205,928 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.initialize | def initialize(self):
"""Sets up initial ensime-vim editor settings."""
# TODO: This seems wrong, the user setting value is never used anywhere.
if 'EnErrorStyle' not in self._vim.vars:
self._vim.vars['EnErrorStyle'] = 'EnError'
self._vim.command('highlight EnErrorStyle ctermbg=red gui=underline')
# TODO: this SHOULD be a buffer-local setting only, and since it should
# apply to all Scala files, ftplugin is the ideal place to set it. I'm
# not even sure how this is currently working when only set once.
self._vim.command('set omnifunc=EnCompleteFunc')
# TODO: custom filetype ftplugin
self._vim.command(
'autocmd FileType package_info nnoremap <buffer> <Space> :call EnPackageDecl()<CR>')
self._vim.command('autocmd FileType package_info setlocal splitright') | python | def initialize(self):
"""Sets up initial ensime-vim editor settings."""
# TODO: This seems wrong, the user setting value is never used anywhere.
if 'EnErrorStyle' not in self._vim.vars:
self._vim.vars['EnErrorStyle'] = 'EnError'
self._vim.command('highlight EnErrorStyle ctermbg=red gui=underline')
# TODO: this SHOULD be a buffer-local setting only, and since it should
# apply to all Scala files, ftplugin is the ideal place to set it. I'm
# not even sure how this is currently working when only set once.
self._vim.command('set omnifunc=EnCompleteFunc')
# TODO: custom filetype ftplugin
self._vim.command(
'autocmd FileType package_info nnoremap <buffer> <Space> :call EnPackageDecl()<CR>')
self._vim.command('autocmd FileType package_info setlocal splitright') | [
"def",
"initialize",
"(",
"self",
")",
":",
"# TODO: This seems wrong, the user setting value is never used anywhere.",
"if",
"'EnErrorStyle'",
"not",
"in",
"self",
".",
"_vim",
".",
"vars",
":",
"self",
".",
"_vim",
".",
"vars",
"[",
"'EnErrorStyle'",
"]",
"=",
"... | Sets up initial ensime-vim editor settings. | [
"Sets",
"up",
"initial",
"ensime",
"-",
"vim",
"editor",
"settings",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L206-L221 | train | 205,929 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.set_cursor | def set_cursor(self, row, col):
"""Set cursor position to given row and column in the current window.
Operation is not added to the jump list.
"""
self._vim.current.window.cursor = (row, col) | python | def set_cursor(self, row, col):
"""Set cursor position to given row and column in the current window.
Operation is not added to the jump list.
"""
self._vim.current.window.cursor = (row, col) | [
"def",
"set_cursor",
"(",
"self",
",",
"row",
",",
"col",
")",
":",
"self",
".",
"_vim",
".",
"current",
".",
"window",
".",
"cursor",
"=",
"(",
"row",
",",
"col",
")"
] | Set cursor position to given row and column in the current window.
Operation is not added to the jump list. | [
"Set",
"cursor",
"position",
"to",
"given",
"row",
"and",
"column",
"in",
"the",
"current",
"window",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L230-L235 | train | 205,930 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.word_under_cursor_pos | def word_under_cursor_pos(self):
"""Return start and end positions of the cursor respectively."""
self._vim.command('normal e')
end = self.cursor()
self._vim.command('normal b')
beg = self.cursor()
return beg, end | python | def word_under_cursor_pos(self):
"""Return start and end positions of the cursor respectively."""
self._vim.command('normal e')
end = self.cursor()
self._vim.command('normal b')
beg = self.cursor()
return beg, end | [
"def",
"word_under_cursor_pos",
"(",
"self",
")",
":",
"self",
".",
"_vim",
".",
"command",
"(",
"'normal e'",
")",
"end",
"=",
"self",
".",
"cursor",
"(",
")",
"self",
".",
"_vim",
".",
"command",
"(",
"'normal b'",
")",
"beg",
"=",
"self",
".",
"cu... | Return start and end positions of the cursor respectively. | [
"Return",
"start",
"and",
"end",
"positions",
"of",
"the",
"cursor",
"respectively",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L238-L244 | train | 205,931 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.selection_pos | def selection_pos(self):
"""Return start and end positions of the visual selection respectively."""
buff = self._vim.current.buffer
beg = buff.mark('<')
end = buff.mark('>')
return beg, end | python | def selection_pos(self):
"""Return start and end positions of the visual selection respectively."""
buff = self._vim.current.buffer
beg = buff.mark('<')
end = buff.mark('>')
return beg, end | [
"def",
"selection_pos",
"(",
"self",
")",
":",
"buff",
"=",
"self",
".",
"_vim",
".",
"current",
".",
"buffer",
"beg",
"=",
"buff",
".",
"mark",
"(",
"'<'",
")",
"end",
"=",
"buff",
".",
"mark",
"(",
"'>'",
")",
"return",
"beg",
",",
"end"
] | Return start and end positions of the visual selection respectively. | [
"Return",
"start",
"and",
"end",
"positions",
"of",
"the",
"visual",
"selection",
"respectively",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L246-L251 | train | 205,932 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.ask_input | def ask_input(self, prompt):
"""Prompt user for input and return the entered value."""
self._vim.command('call inputsave()')
self._vim.command('let user_input = input("{} ")'.format(prompt))
self._vim.command('call inputrestore()')
response = self._vim.eval('user_input')
self._vim.command('unlet user_input')
return response | python | def ask_input(self, prompt):
"""Prompt user for input and return the entered value."""
self._vim.command('call inputsave()')
self._vim.command('let user_input = input("{} ")'.format(prompt))
self._vim.command('call inputrestore()')
response = self._vim.eval('user_input')
self._vim.command('unlet user_input')
return response | [
"def",
"ask_input",
"(",
"self",
",",
"prompt",
")",
":",
"self",
".",
"_vim",
".",
"command",
"(",
"'call inputsave()'",
")",
"self",
".",
"_vim",
".",
"command",
"(",
"'let user_input = input(\"{} \")'",
".",
"format",
"(",
"prompt",
")",
")",
"self",
".... | Prompt user for input and return the entered value. | [
"Prompt",
"user",
"for",
"input",
"and",
"return",
"the",
"entered",
"value",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L266-L273 | train | 205,933 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.lazy_display_error | def lazy_display_error(self, filename):
"""Display error when user is over it."""
position = self.cursor()
error = self.get_error_at(position)
if error:
report = error.get_truncated_message(position, self.width() - 1)
self.raw_message(report) | python | def lazy_display_error(self, filename):
"""Display error when user is over it."""
position = self.cursor()
error = self.get_error_at(position)
if error:
report = error.get_truncated_message(position, self.width() - 1)
self.raw_message(report) | [
"def",
"lazy_display_error",
"(",
"self",
",",
"filename",
")",
":",
"position",
"=",
"self",
".",
"cursor",
"(",
")",
"error",
"=",
"self",
".",
"get_error_at",
"(",
"position",
")",
"if",
"error",
":",
"report",
"=",
"error",
".",
"get_truncated_message"... | Display error when user is over it. | [
"Display",
"error",
"when",
"user",
"is",
"over",
"it",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L290-L296 | train | 205,934 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.get_error_at | def get_error_at(self, cursor):
"""Return error at position `cursor`."""
for error in self._errors:
if error.includes(self._vim.eval("expand('%:p')"), cursor):
return error
return None | python | def get_error_at(self, cursor):
"""Return error at position `cursor`."""
for error in self._errors:
if error.includes(self._vim.eval("expand('%:p')"), cursor):
return error
return None | [
"def",
"get_error_at",
"(",
"self",
",",
"cursor",
")",
":",
"for",
"error",
"in",
"self",
".",
"_errors",
":",
"if",
"error",
".",
"includes",
"(",
"self",
".",
"_vim",
".",
"eval",
"(",
"\"expand('%:p')\"",
")",
",",
"cursor",
")",
":",
"return",
"... | Return error at position `cursor`. | [
"Return",
"error",
"at",
"position",
"cursor",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L298-L303 | train | 205,935 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.clean_errors | def clean_errors(self):
"""Clean errors and unhighlight them in vim."""
self._vim.eval('clearmatches()')
self._errors = []
self._matches = []
# Reset Syntastic notes - TODO: bufdo?
self._vim.current.buffer.vars['ensime_notes'] = [] | python | def clean_errors(self):
"""Clean errors and unhighlight them in vim."""
self._vim.eval('clearmatches()')
self._errors = []
self._matches = []
# Reset Syntastic notes - TODO: bufdo?
self._vim.current.buffer.vars['ensime_notes'] = [] | [
"def",
"clean_errors",
"(",
"self",
")",
":",
"self",
".",
"_vim",
".",
"eval",
"(",
"'clearmatches()'",
")",
"self",
".",
"_errors",
"=",
"[",
"]",
"self",
".",
"_matches",
"=",
"[",
"]",
"# Reset Syntastic notes - TODO: bufdo?",
"self",
".",
"_vim",
".",... | Clean errors and unhighlight them in vim. | [
"Clean",
"errors",
"and",
"unhighlight",
"them",
"in",
"vim",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L305-L311 | train | 205,936 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.raw_message | def raw_message(self, message, silent=False):
"""Display a message in the Vim status line."""
vim = self._vim
cmd = 'echo "{}"'.format(message.replace('"', '\\"'))
if silent:
cmd = 'silent ' + cmd
if self.isneovim:
vim.async_call(vim.command, cmd)
else:
vim.command(cmd) | python | def raw_message(self, message, silent=False):
"""Display a message in the Vim status line."""
vim = self._vim
cmd = 'echo "{}"'.format(message.replace('"', '\\"'))
if silent:
cmd = 'silent ' + cmd
if self.isneovim:
vim.async_call(vim.command, cmd)
else:
vim.command(cmd) | [
"def",
"raw_message",
"(",
"self",
",",
"message",
",",
"silent",
"=",
"False",
")",
":",
"vim",
"=",
"self",
".",
"_vim",
"cmd",
"=",
"'echo \"{}\"'",
".",
"format",
"(",
"message",
".",
"replace",
"(",
"'\"'",
",",
"'\\\\\"'",
")",
")",
"if",
"sile... | Display a message in the Vim status line. | [
"Display",
"a",
"message",
"in",
"the",
"Vim",
"status",
"line",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L318-L328 | train | 205,937 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.symbol_for_inspector_line | def symbol_for_inspector_line(self, lineno):
"""Given a line number for the Package Inspector window, returns the
fully-qualified name for the symbol on that line.
"""
def indent(line):
n = 0
for char in line:
if char == ' ':
n += 1
else:
break
return n / 2
lines = self._vim.current.buffer[:lineno]
i = indent(lines[-1])
fqn = [lines[-1].split()[-1]]
for line in reversed(lines):
if indent(line) == i - 1:
i -= 1
fqn.insert(0, line.split()[-1])
return ".".join(fqn) | python | def symbol_for_inspector_line(self, lineno):
"""Given a line number for the Package Inspector window, returns the
fully-qualified name for the symbol on that line.
"""
def indent(line):
n = 0
for char in line:
if char == ' ':
n += 1
else:
break
return n / 2
lines = self._vim.current.buffer[:lineno]
i = indent(lines[-1])
fqn = [lines[-1].split()[-1]]
for line in reversed(lines):
if indent(line) == i - 1:
i -= 1
fqn.insert(0, line.split()[-1])
return ".".join(fqn) | [
"def",
"symbol_for_inspector_line",
"(",
"self",
",",
"lineno",
")",
":",
"def",
"indent",
"(",
"line",
")",
":",
"n",
"=",
"0",
"for",
"char",
"in",
"line",
":",
"if",
"char",
"==",
"' '",
":",
"n",
"+=",
"1",
"else",
":",
"break",
"return",
"n",
... | Given a line number for the Package Inspector window, returns the
fully-qualified name for the symbol on that line. | [
"Given",
"a",
"line",
"number",
"for",
"the",
"Package",
"Inspector",
"window",
"returns",
"the",
"fully",
"-",
"qualified",
"name",
"for",
"the",
"symbol",
"on",
"that",
"line",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L330-L352 | train | 205,938 |
ensime/ensime-vim | ensime_shared/editor.py | Editor.display_notes | def display_notes(self, notes):
"""Renders "notes" reported by ENSIME, such as typecheck errors."""
# TODO: this can probably be a cached property like isneovim
hassyntastic = bool(int(self._vim.eval('exists(":SyntasticCheck")')))
if hassyntastic:
self.__display_notes_with_syntastic(notes)
else:
self.__display_notes(notes)
self._vim.command('redraw!') | python | def display_notes(self, notes):
"""Renders "notes" reported by ENSIME, such as typecheck errors."""
# TODO: this can probably be a cached property like isneovim
hassyntastic = bool(int(self._vim.eval('exists(":SyntasticCheck")')))
if hassyntastic:
self.__display_notes_with_syntastic(notes)
else:
self.__display_notes(notes)
self._vim.command('redraw!') | [
"def",
"display_notes",
"(",
"self",
",",
"notes",
")",
":",
"# TODO: this can probably be a cached property like isneovim",
"hassyntastic",
"=",
"bool",
"(",
"int",
"(",
"self",
".",
"_vim",
".",
"eval",
"(",
"'exists(\":SyntasticCheck\")'",
")",
")",
")",
"if",
... | Renders "notes" reported by ENSIME, such as typecheck errors. | [
"Renders",
"notes",
"reported",
"by",
"ENSIME",
"such",
"as",
"typecheck",
"errors",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/editor.py#L354-L365 | train | 205,939 |
ensime/ensime-vim | ensime_shared/symbol_format.py | formatted_completion_sig | def formatted_completion_sig(completion):
"""Regenerate signature for methods. Return just the name otherwise"""
f_result = completion["name"]
if is_basic_type(completion):
# It's a raw type
return f_result
elif len(completion["typeInfo"]["paramSections"]) == 0:
return f_result
# It's a function type
sections = completion["typeInfo"]["paramSections"]
f_sections = [formatted_param_section(ps) for ps in sections]
return u"{}{}".format(f_result, "".join(f_sections)) | python | def formatted_completion_sig(completion):
"""Regenerate signature for methods. Return just the name otherwise"""
f_result = completion["name"]
if is_basic_type(completion):
# It's a raw type
return f_result
elif len(completion["typeInfo"]["paramSections"]) == 0:
return f_result
# It's a function type
sections = completion["typeInfo"]["paramSections"]
f_sections = [formatted_param_section(ps) for ps in sections]
return u"{}{}".format(f_result, "".join(f_sections)) | [
"def",
"formatted_completion_sig",
"(",
"completion",
")",
":",
"f_result",
"=",
"completion",
"[",
"\"name\"",
"]",
"if",
"is_basic_type",
"(",
"completion",
")",
":",
"# It's a raw type",
"return",
"f_result",
"elif",
"len",
"(",
"completion",
"[",
"\"typeInfo\"... | Regenerate signature for methods. Return just the name otherwise | [
"Regenerate",
"signature",
"for",
"methods",
".",
"Return",
"just",
"the",
"name",
"otherwise"
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/symbol_format.py#L27-L39 | train | 205,940 |
ensime/ensime-vim | ensime_shared/symbol_format.py | formatted_param_section | def formatted_param_section(section):
"""Format a parameters list. Supports the implicit list"""
implicit = "implicit " if section["isImplicit"] else ""
s_params = [(p[0], formatted_param_type(p[1])) for p in section["params"]]
return "({}{})".format(implicit, concat_params(s_params)) | python | def formatted_param_section(section):
"""Format a parameters list. Supports the implicit list"""
implicit = "implicit " if section["isImplicit"] else ""
s_params = [(p[0], formatted_param_type(p[1])) for p in section["params"]]
return "({}{})".format(implicit, concat_params(s_params)) | [
"def",
"formatted_param_section",
"(",
"section",
")",
":",
"implicit",
"=",
"\"implicit \"",
"if",
"section",
"[",
"\"isImplicit\"",
"]",
"else",
"\"\"",
"s_params",
"=",
"[",
"(",
"p",
"[",
"0",
"]",
",",
"formatted_param_type",
"(",
"p",
"[",
"1",
"]",
... | Format a parameters list. Supports the implicit list | [
"Format",
"a",
"parameters",
"list",
".",
"Supports",
"the",
"implicit",
"list"
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/symbol_format.py#L48-L52 | train | 205,941 |
ensime/ensime-vim | ensime_shared/symbol_format.py | formatted_param_type | def formatted_param_type(ptype):
"""Return the short name for a type. Special treatment for by-name and var args"""
pt_name = ptype["name"]
if pt_name.startswith("<byname>"):
pt_name = pt_name.replace("<byname>[", "=> ")[:-1]
elif pt_name.startswith("<repeated>"):
pt_name = pt_name.replace("<repeated>[", "")[:-1] + "*"
return pt_name | python | def formatted_param_type(ptype):
"""Return the short name for a type. Special treatment for by-name and var args"""
pt_name = ptype["name"]
if pt_name.startswith("<byname>"):
pt_name = pt_name.replace("<byname>[", "=> ")[:-1]
elif pt_name.startswith("<repeated>"):
pt_name = pt_name.replace("<repeated>[", "")[:-1] + "*"
return pt_name | [
"def",
"formatted_param_type",
"(",
"ptype",
")",
":",
"pt_name",
"=",
"ptype",
"[",
"\"name\"",
"]",
"if",
"pt_name",
".",
"startswith",
"(",
"\"<byname>\"",
")",
":",
"pt_name",
"=",
"pt_name",
".",
"replace",
"(",
"\"<byname>[\"",
",",
"\"=> \"",
")",
"... | Return the short name for a type. Special treatment for by-name and var args | [
"Return",
"the",
"short",
"name",
"for",
"a",
"type",
".",
"Special",
"treatment",
"for",
"by",
"-",
"name",
"and",
"var",
"args"
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/symbol_format.py#L61-L68 | train | 205,942 |
ensime/ensime-vim | ensime_shared/protocol.py | ProtocolHandler.register_responses_handlers | def register_responses_handlers(self):
"""Register handlers for responses from the server.
A handler must accept only one parameter: `payload`.
"""
self.handlers["SymbolInfo"] = self.handle_symbol_info
self.handlers["IndexerReadyEvent"] = self.handle_indexer_ready
self.handlers["AnalyzerReadyEvent"] = self.handle_analyzer_ready
self.handlers["NewScalaNotesEvent"] = self.buffer_typechecks
self.handlers["NewJavaNotesEvent"] = self.buffer_typechecks_and_display
self.handlers["BasicTypeInfo"] = self.show_type
self.handlers["ArrowTypeInfo"] = self.show_type
self.handlers["FullTypeCheckCompleteEvent"] = self.handle_typecheck_complete
self.handlers["StringResponse"] = self.handle_string_response
self.handlers["CompletionInfoList"] = self.handle_completion_info_list
self.handlers["TypeInspectInfo"] = self.handle_type_inspect
self.handlers["SymbolSearchResults"] = self.handle_symbol_search
self.handlers["SourcePositions"] = self.handle_source_positions
self.handlers["DebugOutputEvent"] = self.handle_debug_output
self.handlers["DebugBreakEvent"] = self.handle_debug_break
self.handlers["DebugBacktrace"] = self.handle_debug_backtrace
self.handlers["DebugVmError"] = self.handle_debug_vm_error
self.handlers["RefactorDiffEffect"] = self.apply_refactor
self.handlers["ImportSuggestions"] = self.handle_import_suggestions
self.handlers["PackageInfo"] = self.handle_package_info
self.handlers["FalseResponse"] = self.handle_false_response | python | def register_responses_handlers(self):
"""Register handlers for responses from the server.
A handler must accept only one parameter: `payload`.
"""
self.handlers["SymbolInfo"] = self.handle_symbol_info
self.handlers["IndexerReadyEvent"] = self.handle_indexer_ready
self.handlers["AnalyzerReadyEvent"] = self.handle_analyzer_ready
self.handlers["NewScalaNotesEvent"] = self.buffer_typechecks
self.handlers["NewJavaNotesEvent"] = self.buffer_typechecks_and_display
self.handlers["BasicTypeInfo"] = self.show_type
self.handlers["ArrowTypeInfo"] = self.show_type
self.handlers["FullTypeCheckCompleteEvent"] = self.handle_typecheck_complete
self.handlers["StringResponse"] = self.handle_string_response
self.handlers["CompletionInfoList"] = self.handle_completion_info_list
self.handlers["TypeInspectInfo"] = self.handle_type_inspect
self.handlers["SymbolSearchResults"] = self.handle_symbol_search
self.handlers["SourcePositions"] = self.handle_source_positions
self.handlers["DebugOutputEvent"] = self.handle_debug_output
self.handlers["DebugBreakEvent"] = self.handle_debug_break
self.handlers["DebugBacktrace"] = self.handle_debug_backtrace
self.handlers["DebugVmError"] = self.handle_debug_vm_error
self.handlers["RefactorDiffEffect"] = self.apply_refactor
self.handlers["ImportSuggestions"] = self.handle_import_suggestions
self.handlers["PackageInfo"] = self.handle_package_info
self.handlers["FalseResponse"] = self.handle_false_response | [
"def",
"register_responses_handlers",
"(",
"self",
")",
":",
"self",
".",
"handlers",
"[",
"\"SymbolInfo\"",
"]",
"=",
"self",
".",
"handle_symbol_info",
"self",
".",
"handlers",
"[",
"\"IndexerReadyEvent\"",
"]",
"=",
"self",
".",
"handle_indexer_ready",
"self",
... | Register handlers for responses from the server.
A handler must accept only one parameter: `payload`. | [
"Register",
"handlers",
"for",
"responses",
"from",
"the",
"server",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L22-L47 | train | 205,943 |
ensime/ensime-vim | ensime_shared/protocol.py | ProtocolHandler.handle_incoming_response | def handle_incoming_response(self, call_id, payload):
"""Get a registered handler for a given response and execute it."""
self.log.debug('handle_incoming_response: in [typehint: %s, call ID: %s]',
payload['typehint'], call_id) # We already log the full JSON response
typehint = payload["typehint"]
handler = self.handlers.get(typehint)
def feature_not_supported(m):
msg = feedback["handler_not_implemented"]
self.editor.raw_message(msg.format(typehint, self.launcher.ensime_version))
if handler:
with catch(NotImplementedError, feature_not_supported):
handler(call_id, payload)
else:
self.log.warning('Response has not been handled: %s', Pretty(payload)) | python | def handle_incoming_response(self, call_id, payload):
"""Get a registered handler for a given response and execute it."""
self.log.debug('handle_incoming_response: in [typehint: %s, call ID: %s]',
payload['typehint'], call_id) # We already log the full JSON response
typehint = payload["typehint"]
handler = self.handlers.get(typehint)
def feature_not_supported(m):
msg = feedback["handler_not_implemented"]
self.editor.raw_message(msg.format(typehint, self.launcher.ensime_version))
if handler:
with catch(NotImplementedError, feature_not_supported):
handler(call_id, payload)
else:
self.log.warning('Response has not been handled: %s', Pretty(payload)) | [
"def",
"handle_incoming_response",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'handle_incoming_response: in [typehint: %s, call ID: %s]'",
",",
"payload",
"[",
"'typehint'",
"]",
",",
"call_id",
")",
"# We already ... | Get a registered handler for a given response and execute it. | [
"Get",
"a",
"registered",
"handler",
"for",
"a",
"given",
"response",
"and",
"execute",
"it",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L49-L65 | train | 205,944 |
ensime/ensime-vim | ensime_shared/protocol.py | ProtocolHandlerV1.handle_symbol_search | def handle_symbol_search(self, call_id, payload):
"""Handler for symbol search results"""
self.log.debug('handle_symbol_search: in %s', Pretty(payload))
syms = payload["syms"]
qfList = []
for sym in syms:
p = sym.get("pos")
if p:
item = self.editor.to_quickfix_item(str(p["file"]),
p["line"],
str(sym["name"]),
"info")
qfList.append(item)
self.editor.write_quickfix_list(qfList, "Symbol Search") | python | def handle_symbol_search(self, call_id, payload):
"""Handler for symbol search results"""
self.log.debug('handle_symbol_search: in %s', Pretty(payload))
syms = payload["syms"]
qfList = []
for sym in syms:
p = sym.get("pos")
if p:
item = self.editor.to_quickfix_item(str(p["file"]),
p["line"],
str(sym["name"]),
"info")
qfList.append(item)
self.editor.write_quickfix_list(qfList, "Symbol Search") | [
"def",
"handle_symbol_search",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'handle_symbol_search: in %s'",
",",
"Pretty",
"(",
"payload",
")",
")",
"syms",
"=",
"payload",
"[",
"\"syms\"",
"]",
"qfList",
"... | Handler for symbol search results | [
"Handler",
"for",
"symbol",
"search",
"results"
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L163-L177 | train | 205,945 |
ensime/ensime-vim | ensime_shared/protocol.py | ProtocolHandlerV1.handle_symbol_info | def handle_symbol_info(self, call_id, payload):
"""Handler for response `SymbolInfo`."""
with catch(KeyError, lambda e: self.editor.message("unknown_symbol")):
decl_pos = payload["declPos"]
f = decl_pos.get("file")
call_options = self.call_options[call_id]
self.log.debug('handle_symbol_info: call_options %s', call_options)
display = call_options.get("display")
if display and f:
self.editor.raw_message(f)
open_definition = call_options.get("open_definition")
if open_definition and f:
self.editor.clean_errors()
self.editor.doautocmd('BufLeave')
if call_options.get("split"):
vert = call_options.get("vert")
self.editor.split_window(f, vertical=vert)
else:
self.editor.edit(f)
self.editor.doautocmd('BufReadPre', 'BufRead', 'BufEnter')
self.set_position(decl_pos)
del self.call_options[call_id] | python | def handle_symbol_info(self, call_id, payload):
"""Handler for response `SymbolInfo`."""
with catch(KeyError, lambda e: self.editor.message("unknown_symbol")):
decl_pos = payload["declPos"]
f = decl_pos.get("file")
call_options = self.call_options[call_id]
self.log.debug('handle_symbol_info: call_options %s', call_options)
display = call_options.get("display")
if display and f:
self.editor.raw_message(f)
open_definition = call_options.get("open_definition")
if open_definition and f:
self.editor.clean_errors()
self.editor.doautocmd('BufLeave')
if call_options.get("split"):
vert = call_options.get("vert")
self.editor.split_window(f, vertical=vert)
else:
self.editor.edit(f)
self.editor.doautocmd('BufReadPre', 'BufRead', 'BufEnter')
self.set_position(decl_pos)
del self.call_options[call_id] | [
"def",
"handle_symbol_info",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"with",
"catch",
"(",
"KeyError",
",",
"lambda",
"e",
":",
"self",
".",
"editor",
".",
"message",
"(",
"\"unknown_symbol\"",
")",
")",
":",
"decl_pos",
"=",
"payload",
"[... | Handler for response `SymbolInfo`. | [
"Handler",
"for",
"response",
"SymbolInfo",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L179-L201 | train | 205,946 |
ensime/ensime-vim | ensime_shared/protocol.py | ProtocolHandlerV1.handle_string_response | def handle_string_response(self, call_id, payload):
"""Handler for response `StringResponse`.
This is the response for the following requests:
1. `DocUriAtPointReq` or `DocUriForSymbolReq`
2. `DebugToStringReq`
"""
self.log.debug('handle_string_response: in [typehint: %s, call ID: %s]',
payload['typehint'], call_id)
# :EnDocBrowse or :EnDocUri
url = payload['text']
if not url.startswith('http'):
port = self.ensime.http_port()
url = gconfig['localhost'].format(port, url)
options = self.call_options.get(call_id)
if options and options.get('browse'):
self._browse_doc(url)
del self.call_options[call_id]
else:
# TODO: make this return value of a Vim function synchronously, how?
self.log.debug('EnDocUri %s', url)
return url | python | def handle_string_response(self, call_id, payload):
"""Handler for response `StringResponse`.
This is the response for the following requests:
1. `DocUriAtPointReq` or `DocUriForSymbolReq`
2. `DebugToStringReq`
"""
self.log.debug('handle_string_response: in [typehint: %s, call ID: %s]',
payload['typehint'], call_id)
# :EnDocBrowse or :EnDocUri
url = payload['text']
if not url.startswith('http'):
port = self.ensime.http_port()
url = gconfig['localhost'].format(port, url)
options = self.call_options.get(call_id)
if options and options.get('browse'):
self._browse_doc(url)
del self.call_options[call_id]
else:
# TODO: make this return value of a Vim function synchronously, how?
self.log.debug('EnDocUri %s', url)
return url | [
"def",
"handle_string_response",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'handle_string_response: in [typehint: %s, call ID: %s]'",
",",
"payload",
"[",
"'typehint'",
"]",
",",
"call_id",
")",
"# :EnDocBrowse or... | Handler for response `StringResponse`.
This is the response for the following requests:
1. `DocUriAtPointReq` or `DocUriForSymbolReq`
2. `DebugToStringReq` | [
"Handler",
"for",
"response",
"StringResponse",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L203-L226 | train | 205,947 |
ensime/ensime-vim | ensime_shared/protocol.py | ProtocolHandlerV1.handle_completion_info_list | def handle_completion_info_list(self, call_id, payload):
"""Handler for a completion response."""
self.log.debug('handle_completion_info_list: in')
# filter out completions without `typeInfo` field to avoid server bug. See #324
completions = [c for c in payload["completions"] if "typeInfo" in c]
self.suggestions = [completion_to_suggest(c) for c in completions]
self.log.debug('handle_completion_info_list: %s', Pretty(self.suggestions)) | python | def handle_completion_info_list(self, call_id, payload):
"""Handler for a completion response."""
self.log.debug('handle_completion_info_list: in')
# filter out completions without `typeInfo` field to avoid server bug. See #324
completions = [c for c in payload["completions"] if "typeInfo" in c]
self.suggestions = [completion_to_suggest(c) for c in completions]
self.log.debug('handle_completion_info_list: %s', Pretty(self.suggestions)) | [
"def",
"handle_completion_info_list",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'handle_completion_info_list: in'",
")",
"# filter out completions without `typeInfo` field to avoid server bug. See #324",
"completions",
"=",... | Handler for a completion response. | [
"Handler",
"for",
"a",
"completion",
"response",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L237-L243 | train | 205,948 |
ensime/ensime-vim | ensime_shared/protocol.py | ProtocolHandlerV1.handle_type_inspect | def handle_type_inspect(self, call_id, payload):
"""Handler for responses `TypeInspectInfo`."""
style = 'fullName' if self.full_types_enabled else 'name'
interfaces = payload.get("interfaces")
ts = [i["type"][style] for i in interfaces]
prefix = "( " + ", ".join(ts) + " ) => "
self.editor.raw_message(prefix + payload["type"][style]) | python | def handle_type_inspect(self, call_id, payload):
"""Handler for responses `TypeInspectInfo`."""
style = 'fullName' if self.full_types_enabled else 'name'
interfaces = payload.get("interfaces")
ts = [i["type"][style] for i in interfaces]
prefix = "( " + ", ".join(ts) + " ) => "
self.editor.raw_message(prefix + payload["type"][style]) | [
"def",
"handle_type_inspect",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"style",
"=",
"'fullName'",
"if",
"self",
".",
"full_types_enabled",
"else",
"'name'",
"interfaces",
"=",
"payload",
".",
"get",
"(",
"\"interfaces\"",
")",
"ts",
"=",
"[",
... | Handler for responses `TypeInspectInfo`. | [
"Handler",
"for",
"responses",
"TypeInspectInfo",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L245-L251 | train | 205,949 |
ensime/ensime-vim | ensime_shared/protocol.py | ProtocolHandlerV1.show_type | def show_type(self, call_id, payload):
"""Show type of a variable or scala type."""
if self.full_types_enabled:
tpe = payload['fullName']
else:
tpe = payload['name']
self.log.info('Displayed type %s', tpe)
self.editor.raw_message(tpe) | python | def show_type(self, call_id, payload):
"""Show type of a variable or scala type."""
if self.full_types_enabled:
tpe = payload['fullName']
else:
tpe = payload['name']
self.log.info('Displayed type %s', tpe)
self.editor.raw_message(tpe) | [
"def",
"show_type",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"if",
"self",
".",
"full_types_enabled",
":",
"tpe",
"=",
"payload",
"[",
"'fullName'",
"]",
"else",
":",
"tpe",
"=",
"payload",
"[",
"'name'",
"]",
"self",
".",
"log",
".",
"... | Show type of a variable or scala type. | [
"Show",
"type",
"of",
"a",
"variable",
"or",
"scala",
"type",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L254-L262 | train | 205,950 |
ensime/ensime-vim | ensime_shared/protocol.py | ProtocolHandlerV2.handle_source_positions | def handle_source_positions(self, call_id, payload):
"""Handler for source positions"""
self.log.debug('handle_source_positions: in %s', Pretty(payload))
call_options = self.call_options[call_id]
word_under_cursor = call_options.get("word_under_cursor")
positions = payload["positions"]
if not positions:
self.editor.raw_message("No usages of <{}> found".format(word_under_cursor))
return
qf_list = []
for p in positions:
position = p["position"]
preview = str(p["preview"]) if "preview" in p else "<no preview>"
item = self.editor.to_quickfix_item(str(position["file"]),
position["line"],
preview,
"info")
qf_list.append(item)
qf_sorted = sorted(qf_list, key=itemgetter('filename', 'lnum'))
self.editor.write_quickfix_list(qf_sorted, "Usages of <{}>".format(word_under_cursor)) | python | def handle_source_positions(self, call_id, payload):
"""Handler for source positions"""
self.log.debug('handle_source_positions: in %s', Pretty(payload))
call_options = self.call_options[call_id]
word_under_cursor = call_options.get("word_under_cursor")
positions = payload["positions"]
if not positions:
self.editor.raw_message("No usages of <{}> found".format(word_under_cursor))
return
qf_list = []
for p in positions:
position = p["position"]
preview = str(p["preview"]) if "preview" in p else "<no preview>"
item = self.editor.to_quickfix_item(str(position["file"]),
position["line"],
preview,
"info")
qf_list.append(item)
qf_sorted = sorted(qf_list, key=itemgetter('filename', 'lnum'))
self.editor.write_quickfix_list(qf_sorted, "Usages of <{}>".format(word_under_cursor)) | [
"def",
"handle_source_positions",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'handle_source_positions: in %s'",
",",
"Pretty",
"(",
"payload",
")",
")",
"call_options",
"=",
"self",
".",
"call_options",
"[",
... | Handler for source positions | [
"Handler",
"for",
"source",
"positions"
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L268-L291 | train | 205,951 |
ensime/ensime-vim | ensime_shared/ticker.py | Ticker._start_refresh_timer | def _start_refresh_timer(self):
"""Start the Vim timer. """
if not self._timer:
self._timer = self._vim.eval(
"timer_start({}, 'EnTick', {{'repeat': -1}})"
.format(REFRESH_TIMER)
) | python | def _start_refresh_timer(self):
"""Start the Vim timer. """
if not self._timer:
self._timer = self._vim.eval(
"timer_start({}, 'EnTick', {{'repeat': -1}})"
.format(REFRESH_TIMER)
) | [
"def",
"_start_refresh_timer",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_timer",
":",
"self",
".",
"_timer",
"=",
"self",
".",
"_vim",
".",
"eval",
"(",
"\"timer_start({}, 'EnTick', {{'repeat': -1}})\"",
".",
"format",
"(",
"REFRESH_TIMER",
")",
")"
] | Start the Vim timer. | [
"Start",
"the",
"Vim",
"timer",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/ticker.py#L30-L36 | train | 205,952 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.queue_poll | def queue_poll(self, sleep_t=0.5):
"""Put new messages on the queue as they arrive. Blocking in a thread.
Value of sleep is low to improve responsiveness.
"""
connection_alive = True
while self.running:
if self.ws:
def logger_and_close(msg):
self.log.error('Websocket exception', exc_info=True)
if not self.running:
# Tear down has been invoked
# Prepare to exit the program
connection_alive = False # noqa: F841
else:
if not self.number_try_connection:
# Stop everything.
self.teardown()
self._display_ws_warning()
with catch(websocket.WebSocketException, logger_and_close):
result = self.ws.recv()
self.queue.put(result)
if connection_alive:
time.sleep(sleep_t) | python | def queue_poll(self, sleep_t=0.5):
"""Put new messages on the queue as they arrive. Blocking in a thread.
Value of sleep is low to improve responsiveness.
"""
connection_alive = True
while self.running:
if self.ws:
def logger_and_close(msg):
self.log.error('Websocket exception', exc_info=True)
if not self.running:
# Tear down has been invoked
# Prepare to exit the program
connection_alive = False # noqa: F841
else:
if not self.number_try_connection:
# Stop everything.
self.teardown()
self._display_ws_warning()
with catch(websocket.WebSocketException, logger_and_close):
result = self.ws.recv()
self.queue.put(result)
if connection_alive:
time.sleep(sleep_t) | [
"def",
"queue_poll",
"(",
"self",
",",
"sleep_t",
"=",
"0.5",
")",
":",
"connection_alive",
"=",
"True",
"while",
"self",
".",
"running",
":",
"if",
"self",
".",
"ws",
":",
"def",
"logger_and_close",
"(",
"msg",
")",
":",
"self",
".",
"log",
".",
"er... | Put new messages on the queue as they arrive. Blocking in a thread.
Value of sleep is low to improve responsiveness. | [
"Put",
"new",
"messages",
"on",
"the",
"queue",
"as",
"they",
"arrive",
".",
"Blocking",
"in",
"a",
"thread",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L126-L152 | train | 205,953 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.setup | def setup(self, quiet=False, bootstrap_server=False):
"""Check the classpath and connect to the server if necessary."""
def lazy_initialize_ensime():
if not self.ensime:
called_by = inspect.stack()[4][3]
self.log.debug(str(inspect.stack()))
self.log.debug('setup(quiet=%s, bootstrap_server=%s) called by %s()',
quiet, bootstrap_server, called_by)
installed = self.launcher.strategy.isinstalled()
if not installed and not bootstrap_server:
if not quiet:
scala = self.launcher.config.get('scala-version')
msg = feedback["prompt_server_install"].format(scala_version=scala)
self.editor.raw_message(msg)
return False
try:
self.ensime = self.launcher.launch()
except InvalidJavaPathError:
self.editor.message('invalid_java') # TODO: also disable plugin
return bool(self.ensime)
def ready_to_connect():
if not self.ws and self.ensime.is_ready():
self.connect_ensime_server()
return True
# True if ensime is up and connection is ok, otherwise False
return self.running and lazy_initialize_ensime() and ready_to_connect() | python | def setup(self, quiet=False, bootstrap_server=False):
"""Check the classpath and connect to the server if necessary."""
def lazy_initialize_ensime():
if not self.ensime:
called_by = inspect.stack()[4][3]
self.log.debug(str(inspect.stack()))
self.log.debug('setup(quiet=%s, bootstrap_server=%s) called by %s()',
quiet, bootstrap_server, called_by)
installed = self.launcher.strategy.isinstalled()
if not installed and not bootstrap_server:
if not quiet:
scala = self.launcher.config.get('scala-version')
msg = feedback["prompt_server_install"].format(scala_version=scala)
self.editor.raw_message(msg)
return False
try:
self.ensime = self.launcher.launch()
except InvalidJavaPathError:
self.editor.message('invalid_java') # TODO: also disable plugin
return bool(self.ensime)
def ready_to_connect():
if not self.ws and self.ensime.is_ready():
self.connect_ensime_server()
return True
# True if ensime is up and connection is ok, otherwise False
return self.running and lazy_initialize_ensime() and ready_to_connect() | [
"def",
"setup",
"(",
"self",
",",
"quiet",
"=",
"False",
",",
"bootstrap_server",
"=",
"False",
")",
":",
"def",
"lazy_initialize_ensime",
"(",
")",
":",
"if",
"not",
"self",
".",
"ensime",
":",
"called_by",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",... | Check the classpath and connect to the server if necessary. | [
"Check",
"the",
"classpath",
"and",
"connect",
"to",
"the",
"server",
"if",
"necessary",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L154-L184 | train | 205,954 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.send | def send(self, msg):
"""Send something to the ensime server."""
def reconnect(e):
self.log.error('send error, reconnecting...', exc_info=True)
self.connect_ensime_server()
if self.ws:
self.ws.send(msg + "\n")
self.log.debug('send: in')
if self.running and self.ws:
with catch(websocket.WebSocketException, reconnect):
self.log.debug('send: sending JSON on WebSocket')
self.ws.send(msg + "\n") | python | def send(self, msg):
"""Send something to the ensime server."""
def reconnect(e):
self.log.error('send error, reconnecting...', exc_info=True)
self.connect_ensime_server()
if self.ws:
self.ws.send(msg + "\n")
self.log.debug('send: in')
if self.running and self.ws:
with catch(websocket.WebSocketException, reconnect):
self.log.debug('send: sending JSON on WebSocket')
self.ws.send(msg + "\n") | [
"def",
"send",
"(",
"self",
",",
"msg",
")",
":",
"def",
"reconnect",
"(",
"e",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"'send error, reconnecting...'",
",",
"exc_info",
"=",
"True",
")",
"self",
".",
"connect_ensime_server",
"(",
")",
"if",
"... | Send something to the ensime server. | [
"Send",
"something",
"to",
"the",
"ensime",
"server",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L191-L203 | train | 205,955 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.connect_ensime_server | def connect_ensime_server(self):
"""Start initial connection with the server."""
self.log.debug('connect_ensime_server: in')
server_v2 = isinstance(self, EnsimeClientV2)
def disable_completely(e):
if e:
self.log.error('connection error: %s', e, exc_info=True)
self.shutdown_server()
self._display_ws_warning()
if self.running and self.number_try_connection:
self.number_try_connection -= 1
if not self.ensime_server:
port = self.ensime.http_port()
uri = "websocket" if server_v2 else "jerky"
self.ensime_server = gconfig["ensime_server"].format(port, uri)
with catch(websocket.WebSocketException, disable_completely):
# Use the default timeout (no timeout).
options = {"subprotocols": ["jerky"]} if server_v2 else {}
options['enable_multithread'] = True
self.log.debug("About to connect to %s with options %s",
self.ensime_server, options)
self.ws = websocket.create_connection(self.ensime_server, **options)
if self.ws:
self.send_request({"typehint": "ConnectionInfoReq"})
else:
# If it hits this, number_try_connection is 0
disable_completely(None) | python | def connect_ensime_server(self):
"""Start initial connection with the server."""
self.log.debug('connect_ensime_server: in')
server_v2 = isinstance(self, EnsimeClientV2)
def disable_completely(e):
if e:
self.log.error('connection error: %s', e, exc_info=True)
self.shutdown_server()
self._display_ws_warning()
if self.running and self.number_try_connection:
self.number_try_connection -= 1
if not self.ensime_server:
port = self.ensime.http_port()
uri = "websocket" if server_v2 else "jerky"
self.ensime_server = gconfig["ensime_server"].format(port, uri)
with catch(websocket.WebSocketException, disable_completely):
# Use the default timeout (no timeout).
options = {"subprotocols": ["jerky"]} if server_v2 else {}
options['enable_multithread'] = True
self.log.debug("About to connect to %s with options %s",
self.ensime_server, options)
self.ws = websocket.create_connection(self.ensime_server, **options)
if self.ws:
self.send_request({"typehint": "ConnectionInfoReq"})
else:
# If it hits this, number_try_connection is 0
disable_completely(None) | [
"def",
"connect_ensime_server",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'connect_ensime_server: in'",
")",
"server_v2",
"=",
"isinstance",
"(",
"self",
",",
"EnsimeClientV2",
")",
"def",
"disable_completely",
"(",
"e",
")",
":",
"if",
... | Start initial connection with the server. | [
"Start",
"initial",
"connection",
"with",
"the",
"server",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L205-L233 | train | 205,956 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.shutdown_server | def shutdown_server(self):
"""Shut down server if it is alive."""
self.log.debug('shutdown_server: in')
if self.ensime and self.toggle_teardown:
self.ensime.stop() | python | def shutdown_server(self):
"""Shut down server if it is alive."""
self.log.debug('shutdown_server: in')
if self.ensime and self.toggle_teardown:
self.ensime.stop() | [
"def",
"shutdown_server",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'shutdown_server: in'",
")",
"if",
"self",
".",
"ensime",
"and",
"self",
".",
"toggle_teardown",
":",
"self",
".",
"ensime",
".",
"stop",
"(",
")"
] | Shut down server if it is alive. | [
"Shut",
"down",
"server",
"if",
"it",
"is",
"alive",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L235-L239 | train | 205,957 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.teardown | def teardown(self):
"""Tear down the server or keep it alive."""
self.log.debug('teardown: in')
self.running = False
self.shutdown_server()
shutil.rmtree(self.tmp_diff_folder, ignore_errors=True) | python | def teardown(self):
"""Tear down the server or keep it alive."""
self.log.debug('teardown: in')
self.running = False
self.shutdown_server()
shutil.rmtree(self.tmp_diff_folder, ignore_errors=True) | [
"def",
"teardown",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'teardown: in'",
")",
"self",
".",
"running",
"=",
"False",
"self",
".",
"shutdown_server",
"(",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"tmp_diff_folder",
",",
"... | Tear down the server or keep it alive. | [
"Tear",
"down",
"the",
"server",
"or",
"keep",
"it",
"alive",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L241-L246 | train | 205,958 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.set_position | def set_position(self, decl_pos):
"""Set editor position from ENSIME declPos data."""
if decl_pos["typehint"] == "LineSourcePosition":
self.editor.set_cursor(decl_pos['line'], 0)
else: # OffsetSourcePosition
point = decl_pos["offset"]
row, col = self.editor.point2pos(point + 1)
self.editor.set_cursor(row, col) | python | def set_position(self, decl_pos):
"""Set editor position from ENSIME declPos data."""
if decl_pos["typehint"] == "LineSourcePosition":
self.editor.set_cursor(decl_pos['line'], 0)
else: # OffsetSourcePosition
point = decl_pos["offset"]
row, col = self.editor.point2pos(point + 1)
self.editor.set_cursor(row, col) | [
"def",
"set_position",
"(",
"self",
",",
"decl_pos",
")",
":",
"if",
"decl_pos",
"[",
"\"typehint\"",
"]",
"==",
"\"LineSourcePosition\"",
":",
"self",
".",
"editor",
".",
"set_cursor",
"(",
"decl_pos",
"[",
"'line'",
"]",
",",
"0",
")",
"else",
":",
"# ... | Set editor position from ENSIME declPos data. | [
"Set",
"editor",
"position",
"from",
"ENSIME",
"declPos",
"data",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L272-L279 | train | 205,959 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.get_position | def get_position(self, row, col):
"""Get char position in all the text from row and column."""
result = col
self.log.debug('%s %s', row, col)
lines = self.editor.getlines()[:row - 1]
result += sum([len(l) + 1 for l in lines])
self.log.debug(result)
return result | python | def get_position(self, row, col):
"""Get char position in all the text from row and column."""
result = col
self.log.debug('%s %s', row, col)
lines = self.editor.getlines()[:row - 1]
result += sum([len(l) + 1 for l in lines])
self.log.debug(result)
return result | [
"def",
"get_position",
"(",
"self",
",",
"row",
",",
"col",
")",
":",
"result",
"=",
"col",
"self",
".",
"log",
".",
"debug",
"(",
"'%s %s'",
",",
"row",
",",
"col",
")",
"lines",
"=",
"self",
".",
"editor",
".",
"getlines",
"(",
")",
"[",
":",
... | Get char position in all the text from row and column. | [
"Get",
"char",
"position",
"in",
"all",
"the",
"text",
"from",
"row",
"and",
"column",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L281-L288 | train | 205,960 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.send_at_point | def send_at_point(self, what, row, col):
"""Ask the server to perform an operation at a given point."""
pos = self.get_position(row, col)
self.send_request(
{"typehint": what + "AtPointReq",
"file": self._file_info(),
"point": pos}) | python | def send_at_point(self, what, row, col):
"""Ask the server to perform an operation at a given point."""
pos = self.get_position(row, col)
self.send_request(
{"typehint": what + "AtPointReq",
"file": self._file_info(),
"point": pos}) | [
"def",
"send_at_point",
"(",
"self",
",",
"what",
",",
"row",
",",
"col",
")",
":",
"pos",
"=",
"self",
".",
"get_position",
"(",
"row",
",",
"col",
")",
"self",
".",
"send_request",
"(",
"{",
"\"typehint\"",
":",
"what",
"+",
"\"AtPointReq\"",
",",
... | Ask the server to perform an operation at a given point. | [
"Ask",
"the",
"server",
"to",
"perform",
"an",
"operation",
"at",
"a",
"given",
"point",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L324-L330 | train | 205,961 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.type_check_cmd | def type_check_cmd(self, args, range=None):
"""Sets the flag to begin buffering typecheck notes & clears any
stale notes before requesting a typecheck from the server"""
self.log.debug('type_check_cmd: in')
self.start_typechecking()
self.type_check("")
self.editor.message('typechecking') | python | def type_check_cmd(self, args, range=None):
"""Sets the flag to begin buffering typecheck notes & clears any
stale notes before requesting a typecheck from the server"""
self.log.debug('type_check_cmd: in')
self.start_typechecking()
self.type_check("")
self.editor.message('typechecking') | [
"def",
"type_check_cmd",
"(",
"self",
",",
"args",
",",
"range",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'type_check_cmd: in'",
")",
"self",
".",
"start_typechecking",
"(",
")",
"self",
".",
"type_check",
"(",
"\"\"",
")",
"self",
... | Sets the flag to begin buffering typecheck notes & clears any
stale notes before requesting a typecheck from the server | [
"Sets",
"the",
"flag",
"to",
"begin",
"buffering",
"typecheck",
"notes",
"&",
"clears",
"any",
"stale",
"notes",
"before",
"requesting",
"a",
"typecheck",
"from",
"the",
"server"
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L336-L342 | train | 205,962 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.doc_uri | def doc_uri(self, args, range=None):
"""Request doc of whatever at cursor."""
self.log.debug('doc_uri: in')
self.send_at_position("DocUri", False, "point") | python | def doc_uri(self, args, range=None):
"""Request doc of whatever at cursor."""
self.log.debug('doc_uri: in')
self.send_at_position("DocUri", False, "point") | [
"def",
"doc_uri",
"(",
"self",
",",
"args",
",",
"range",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'doc_uri: in'",
")",
"self",
".",
"send_at_position",
"(",
"\"DocUri\"",
",",
"False",
",",
"\"point\"",
")"
] | Request doc of whatever at cursor. | [
"Request",
"doc",
"of",
"whatever",
"at",
"cursor",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L433-L436 | train | 205,963 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.usages | def usages(self):
"""Request usages of whatever at cursor."""
row, col = self.editor.cursor()
self.log.debug('usages: in')
self.call_options[self.call_id] = {
"word_under_cursor": self.editor.current_word(),
"false_resp_msg": "Not a valid symbol under the cursor"}
self.send_at_point("UsesOfSymbol", row, col) | python | def usages(self):
"""Request usages of whatever at cursor."""
row, col = self.editor.cursor()
self.log.debug('usages: in')
self.call_options[self.call_id] = {
"word_under_cursor": self.editor.current_word(),
"false_resp_msg": "Not a valid symbol under the cursor"}
self.send_at_point("UsesOfSymbol", row, col) | [
"def",
"usages",
"(",
"self",
")",
":",
"row",
",",
"col",
"=",
"self",
".",
"editor",
".",
"cursor",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'usages: in'",
")",
"self",
".",
"call_options",
"[",
"self",
".",
"call_id",
"]",
"=",
"{",
"... | Request usages of whatever at cursor. | [
"Request",
"usages",
"of",
"whatever",
"at",
"cursor",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L438-L445 | train | 205,964 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.doc_browse | def doc_browse(self, args, range=None):
"""Browse doc of whatever at cursor."""
self.log.debug('browse: in')
self.call_options[self.call_id] = {"browse": True}
self.send_at_position("DocUri", False, "point") | python | def doc_browse(self, args, range=None):
"""Browse doc of whatever at cursor."""
self.log.debug('browse: in')
self.call_options[self.call_id] = {"browse": True}
self.send_at_position("DocUri", False, "point") | [
"def",
"doc_browse",
"(",
"self",
",",
"args",
",",
"range",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'browse: in'",
")",
"self",
".",
"call_options",
"[",
"self",
".",
"call_id",
"]",
"=",
"{",
"\"browse\"",
":",
"True",
"}",
... | Browse doc of whatever at cursor. | [
"Browse",
"doc",
"of",
"whatever",
"at",
"cursor",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L447-L451 | train | 205,965 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.rename | def rename(self, new_name, range=None):
"""Request a rename to the server."""
self.log.debug('rename: in')
if not new_name:
new_name = self.editor.ask_input("Rename to:")
self.editor.write(noautocmd=True)
b, e = self.editor.word_under_cursor_pos()
current_file = self.editor.path()
self.editor.raw_message(current_file)
self.send_refactor_request(
"RefactorReq",
{
"typehint": "RenameRefactorDesc",
"newName": new_name,
"start": self.get_position(b[0], b[1]),
"end": self.get_position(e[0], e[1]) + 1,
"file": current_file,
},
{"interactive": False}
) | python | def rename(self, new_name, range=None):
"""Request a rename to the server."""
self.log.debug('rename: in')
if not new_name:
new_name = self.editor.ask_input("Rename to:")
self.editor.write(noautocmd=True)
b, e = self.editor.word_under_cursor_pos()
current_file = self.editor.path()
self.editor.raw_message(current_file)
self.send_refactor_request(
"RefactorReq",
{
"typehint": "RenameRefactorDesc",
"newName": new_name,
"start": self.get_position(b[0], b[1]),
"end": self.get_position(e[0], e[1]) + 1,
"file": current_file,
},
{"interactive": False}
) | [
"def",
"rename",
"(",
"self",
",",
"new_name",
",",
"range",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'rename: in'",
")",
"if",
"not",
"new_name",
":",
"new_name",
"=",
"self",
".",
"editor",
".",
"ask_input",
"(",
"\"Rename to:\"... | Request a rename to the server. | [
"Request",
"a",
"rename",
"to",
"the",
"server",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L453-L472 | train | 205,966 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.symbol_search | def symbol_search(self, search_terms):
"""Search for symbols matching a set of keywords"""
self.log.debug('symbol_search: in')
if not search_terms:
self.editor.message('symbol_search_symbol_required')
return
req = {
"typehint": "PublicSymbolSearchReq",
"keywords": search_terms,
"maxResults": 25
}
self.send_request(req) | python | def symbol_search(self, search_terms):
"""Search for symbols matching a set of keywords"""
self.log.debug('symbol_search: in')
if not search_terms:
self.editor.message('symbol_search_symbol_required')
return
req = {
"typehint": "PublicSymbolSearchReq",
"keywords": search_terms,
"maxResults": 25
}
self.send_request(req) | [
"def",
"symbol_search",
"(",
"self",
",",
"search_terms",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'symbol_search: in'",
")",
"if",
"not",
"search_terms",
":",
"self",
".",
"editor",
".",
"message",
"(",
"'symbol_search_symbol_required'",
")",
"return... | Search for symbols matching a set of keywords | [
"Search",
"for",
"symbols",
"matching",
"a",
"set",
"of",
"keywords"
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L518-L530 | train | 205,967 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.send_refactor_request | def send_refactor_request(self, ref_type, ref_params, ref_options):
"""Send a refactor request to the Ensime server.
The `ref_params` field will always have a field `type`.
"""
request = {
"typehint": ref_type,
"procId": self.refactor_id,
"params": ref_params
}
f = ref_params["file"]
self.refactorings[self.refactor_id] = f
self.refactor_id += 1
request.update(ref_options)
self.send_request(request) | python | def send_refactor_request(self, ref_type, ref_params, ref_options):
"""Send a refactor request to the Ensime server.
The `ref_params` field will always have a field `type`.
"""
request = {
"typehint": ref_type,
"procId": self.refactor_id,
"params": ref_params
}
f = ref_params["file"]
self.refactorings[self.refactor_id] = f
self.refactor_id += 1
request.update(ref_options)
self.send_request(request) | [
"def",
"send_refactor_request",
"(",
"self",
",",
"ref_type",
",",
"ref_params",
",",
"ref_options",
")",
":",
"request",
"=",
"{",
"\"typehint\"",
":",
"ref_type",
",",
"\"procId\"",
":",
"self",
".",
"refactor_id",
",",
"\"params\"",
":",
"ref_params",
"}",
... | Send a refactor request to the Ensime server.
The `ref_params` field will always have a field `type`. | [
"Send",
"a",
"refactor",
"request",
"to",
"the",
"Ensime",
"server",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L532-L546 | train | 205,968 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.apply_refactor | def apply_refactor(self, call_id, payload):
"""Apply a refactor depending on its type."""
supported_refactorings = ["Rename", "InlineLocal", "AddImport", "OrganizeImports"]
if payload["refactorType"]["typehint"] in supported_refactorings:
diff_filepath = payload["diff"]
path = self.editor.path()
bname = os.path.basename(path)
target = os.path.join(self.tmp_diff_folder, bname)
reject_arg = "--reject-file={}.rej".format(target)
backup_pref = "--prefix={}".format(self.tmp_diff_folder)
# Patch utility is prepackaged or installed with vim
cmd = ["patch", reject_arg, backup_pref, path, diff_filepath]
failed = Popen(cmd, stdout=PIPE, stderr=PIPE).wait()
if failed:
self.editor.message("failed_refactoring")
# Update file and reload highlighting
self.editor.edit(self.editor.path())
self.editor.doautocmd('BufReadPre', 'BufRead', 'BufEnter') | python | def apply_refactor(self, call_id, payload):
"""Apply a refactor depending on its type."""
supported_refactorings = ["Rename", "InlineLocal", "AddImport", "OrganizeImports"]
if payload["refactorType"]["typehint"] in supported_refactorings:
diff_filepath = payload["diff"]
path = self.editor.path()
bname = os.path.basename(path)
target = os.path.join(self.tmp_diff_folder, bname)
reject_arg = "--reject-file={}.rej".format(target)
backup_pref = "--prefix={}".format(self.tmp_diff_folder)
# Patch utility is prepackaged or installed with vim
cmd = ["patch", reject_arg, backup_pref, path, diff_filepath]
failed = Popen(cmd, stdout=PIPE, stderr=PIPE).wait()
if failed:
self.editor.message("failed_refactoring")
# Update file and reload highlighting
self.editor.edit(self.editor.path())
self.editor.doautocmd('BufReadPre', 'BufRead', 'BufEnter') | [
"def",
"apply_refactor",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"supported_refactorings",
"=",
"[",
"\"Rename\"",
",",
"\"InlineLocal\"",
",",
"\"AddImport\"",
",",
"\"OrganizeImports\"",
"]",
"if",
"payload",
"[",
"\"refactorType\"",
"]",
"[",
"... | Apply a refactor depending on its type. | [
"Apply",
"a",
"refactor",
"depending",
"on",
"its",
"type",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L549-L567 | train | 205,969 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.buffer_leave | def buffer_leave(self, filename):
"""User is changing of buffer."""
self.log.debug('buffer_leave: %s', filename)
# TODO: This is questionable, and we should use location list for
# single-file errors.
self.editor.clean_errors() | python | def buffer_leave(self, filename):
"""User is changing of buffer."""
self.log.debug('buffer_leave: %s', filename)
# TODO: This is questionable, and we should use location list for
# single-file errors.
self.editor.clean_errors() | [
"def",
"buffer_leave",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'buffer_leave: %s'",
",",
"filename",
")",
"# TODO: This is questionable, and we should use location list for",
"# single-file errors.",
"self",
".",
"editor",
".",
... | User is changing of buffer. | [
"User",
"is",
"changing",
"of",
"buffer",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L581-L586 | train | 205,970 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.type_check | def type_check(self, filename):
"""Update type checking when user saves buffer."""
self.log.debug('type_check: in')
self.editor.clean_errors()
self.send_request(
{"typehint": "TypecheckFilesReq",
"files": [self.editor.path()]}) | python | def type_check(self, filename):
"""Update type checking when user saves buffer."""
self.log.debug('type_check: in')
self.editor.clean_errors()
self.send_request(
{"typehint": "TypecheckFilesReq",
"files": [self.editor.path()]}) | [
"def",
"type_check",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'type_check: in'",
")",
"self",
".",
"editor",
".",
"clean_errors",
"(",
")",
"self",
".",
"send_request",
"(",
"{",
"\"typehint\"",
":",
"\"TypecheckFiles... | Update type checking when user saves buffer. | [
"Update",
"type",
"checking",
"when",
"user",
"saves",
"buffer",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L588-L594 | train | 205,971 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.unqueue | def unqueue(self, timeout=10, should_wait=False):
"""Unqueue all the received ensime responses for a given file."""
start, now = time.time(), time.time()
wait = self.queue.empty() and should_wait
while (not self.queue.empty() or wait) and (now - start) < timeout:
if wait and self.queue.empty():
time.sleep(0.25)
now = time.time()
else:
result = self.queue.get(False)
self.log.debug('unqueue: result received\n%s', result)
if result and result != "nil":
wait = None
# Restart timeout
start, now = time.time(), time.time()
_json = json.loads(result)
# Watch out, it may not have callId
call_id = _json.get("callId")
if _json["payload"]:
self.handle_incoming_response(call_id, _json["payload"])
else:
self.log.debug('unqueue: nil or None received')
if (now - start) >= timeout:
self.log.warning('unqueue: no reply from server for %ss', timeout) | python | def unqueue(self, timeout=10, should_wait=False):
"""Unqueue all the received ensime responses for a given file."""
start, now = time.time(), time.time()
wait = self.queue.empty() and should_wait
while (not self.queue.empty() or wait) and (now - start) < timeout:
if wait and self.queue.empty():
time.sleep(0.25)
now = time.time()
else:
result = self.queue.get(False)
self.log.debug('unqueue: result received\n%s', result)
if result and result != "nil":
wait = None
# Restart timeout
start, now = time.time(), time.time()
_json = json.loads(result)
# Watch out, it may not have callId
call_id = _json.get("callId")
if _json["payload"]:
self.handle_incoming_response(call_id, _json["payload"])
else:
self.log.debug('unqueue: nil or None received')
if (now - start) >= timeout:
self.log.warning('unqueue: no reply from server for %ss', timeout) | [
"def",
"unqueue",
"(",
"self",
",",
"timeout",
"=",
"10",
",",
"should_wait",
"=",
"False",
")",
":",
"start",
",",
"now",
"=",
"time",
".",
"time",
"(",
")",
",",
"time",
".",
"time",
"(",
")",
"wait",
"=",
"self",
".",
"queue",
".",
"empty",
... | Unqueue all the received ensime responses for a given file. | [
"Unqueue",
"all",
"the",
"received",
"ensime",
"responses",
"for",
"a",
"given",
"file",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L596-L621 | train | 205,972 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.tick | def tick(self, filename):
"""Try to connect and display messages in queue."""
if self.connection_attempts < 10:
# Trick to connect ASAP when
# plugin is started without
# user interaction (CursorMove)
self.setup(True, False)
self.connection_attempts += 1
self.unqueue_and_display(filename) | python | def tick(self, filename):
"""Try to connect and display messages in queue."""
if self.connection_attempts < 10:
# Trick to connect ASAP when
# plugin is started without
# user interaction (CursorMove)
self.setup(True, False)
self.connection_attempts += 1
self.unqueue_and_display(filename) | [
"def",
"tick",
"(",
"self",
",",
"filename",
")",
":",
"if",
"self",
".",
"connection_attempts",
"<",
"10",
":",
"# Trick to connect ASAP when",
"# plugin is started without",
"# user interaction (CursorMove)",
"self",
".",
"setup",
"(",
"True",
",",
"False",
")",
... | Try to connect and display messages in queue. | [
"Try",
"to",
"connect",
"and",
"display",
"messages",
"in",
"queue",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L629-L637 | train | 205,973 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.vim_enter | def vim_enter(self, filename):
"""Set up EnsimeClient when vim enters.
This is useful to start the EnsimeLauncher as soon as possible."""
success = self.setup(True, False)
if success:
self.editor.message("start_message") | python | def vim_enter(self, filename):
"""Set up EnsimeClient when vim enters.
This is useful to start the EnsimeLauncher as soon as possible."""
success = self.setup(True, False)
if success:
self.editor.message("start_message") | [
"def",
"vim_enter",
"(",
"self",
",",
"filename",
")",
":",
"success",
"=",
"self",
".",
"setup",
"(",
"True",
",",
"False",
")",
"if",
"success",
":",
"self",
".",
"editor",
".",
"message",
"(",
"\"start_message\"",
")"
] | Set up EnsimeClient when vim enters.
This is useful to start the EnsimeLauncher as soon as possible. | [
"Set",
"up",
"EnsimeClient",
"when",
"vim",
"enters",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L639-L645 | train | 205,974 |
ensime/ensime-vim | ensime_shared/client.py | EnsimeClient.complete_func | def complete_func(self, findstart, base):
"""Handle omni completion."""
self.log.debug('complete_func: in %s %s', findstart, base)
def detect_row_column_start():
row, col = self.editor.cursor()
start = col
line = self.editor.getline()
while start > 0 and line[start - 1] not in " .,([{":
start -= 1
# Start should be 1 when startcol is zero
return row, col, start if start else 1
if str(findstart) == "1":
row, col, startcol = detect_row_column_start()
# Make request to get response ASAP
self.complete(row, col)
self.completion_started = True
# We always allow autocompletion, even with empty seeds
return startcol
else:
result = []
# Only handle snd invocation if fst has already been done
if self.completion_started:
# Unqueing messages until we get suggestions
self.unqueue(timeout=self.completion_timeout, should_wait=True)
suggestions = self.suggestions or []
self.log.debug('complete_func: suggestions in')
for m in suggestions:
result.append(m)
self.suggestions = None
self.completion_started = False
return result | python | def complete_func(self, findstart, base):
"""Handle omni completion."""
self.log.debug('complete_func: in %s %s', findstart, base)
def detect_row_column_start():
row, col = self.editor.cursor()
start = col
line = self.editor.getline()
while start > 0 and line[start - 1] not in " .,([{":
start -= 1
# Start should be 1 when startcol is zero
return row, col, start if start else 1
if str(findstart) == "1":
row, col, startcol = detect_row_column_start()
# Make request to get response ASAP
self.complete(row, col)
self.completion_started = True
# We always allow autocompletion, even with empty seeds
return startcol
else:
result = []
# Only handle snd invocation if fst has already been done
if self.completion_started:
# Unqueing messages until we get suggestions
self.unqueue(timeout=self.completion_timeout, should_wait=True)
suggestions = self.suggestions or []
self.log.debug('complete_func: suggestions in')
for m in suggestions:
result.append(m)
self.suggestions = None
self.completion_started = False
return result | [
"def",
"complete_func",
"(",
"self",
",",
"findstart",
",",
"base",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'complete_func: in %s %s'",
",",
"findstart",
",",
"base",
")",
"def",
"detect_row_column_start",
"(",
")",
":",
"row",
",",
"col",
"=",
... | Handle omni completion. | [
"Handle",
"omni",
"completion",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/client.py#L647-L681 | train | 205,975 |
ensime/ensime-vim | ensime_shared/debugger.py | DebuggerClient.handle_debug_break | def handle_debug_break(self, call_id, payload):
"""Handle responses `DebugBreakEvent`."""
line = payload['line']
config = self.launcher.config # TODO: make an attribute of client
path = os.path.relpath(payload['file'], config['root-dir'])
self.editor.raw_message(feedback['notify_break'].format(line, path))
self.debug_thread_id = payload["threadId"] | python | def handle_debug_break(self, call_id, payload):
"""Handle responses `DebugBreakEvent`."""
line = payload['line']
config = self.launcher.config # TODO: make an attribute of client
path = os.path.relpath(payload['file'], config['root-dir'])
self.editor.raw_message(feedback['notify_break'].format(line, path))
self.debug_thread_id = payload["threadId"] | [
"def",
"handle_debug_break",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"line",
"=",
"payload",
"[",
"'line'",
"]",
"config",
"=",
"self",
".",
"launcher",
".",
"config",
"# TODO: make an attribute of client",
"path",
"=",
"os",
".",
"path",
".",... | Handle responses `DebugBreakEvent`. | [
"Handle",
"responses",
"DebugBreakEvent",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/debugger.py#L20-L27 | train | 205,976 |
ensime/ensime-vim | ensime_shared/debugger.py | DebuggerClient.handle_debug_backtrace | def handle_debug_backtrace(self, call_id, payload):
"""Handle responses `DebugBacktrace`."""
frames = payload["frames"]
fd, path = tempfile.mkstemp('.json', text=True, dir=self.tmp_diff_folder)
tmpfile = os.fdopen(fd, 'w')
tmpfile.write(json.dumps(frames, indent=2))
opts = {'readonly': True, 'bufhidden': 'wipe',
'buflisted': False, 'swapfile': False}
self.editor.split_window(path, size=20, bufopts=opts)
tmpfile.close() | python | def handle_debug_backtrace(self, call_id, payload):
"""Handle responses `DebugBacktrace`."""
frames = payload["frames"]
fd, path = tempfile.mkstemp('.json', text=True, dir=self.tmp_diff_folder)
tmpfile = os.fdopen(fd, 'w')
tmpfile.write(json.dumps(frames, indent=2))
opts = {'readonly': True, 'bufhidden': 'wipe',
'buflisted': False, 'swapfile': False}
self.editor.split_window(path, size=20, bufopts=opts)
tmpfile.close() | [
"def",
"handle_debug_backtrace",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"frames",
"=",
"payload",
"[",
"\"frames\"",
"]",
"fd",
",",
"path",
"=",
"tempfile",
".",
"mkstemp",
"(",
"'.json'",
",",
"text",
"=",
"True",
",",
"dir",
"=",
"se... | Handle responses `DebugBacktrace`. | [
"Handle",
"responses",
"DebugBacktrace",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/debugger.py#L30-L40 | train | 205,977 |
ensime/ensime-vim | ensime_shared/launcher.py | EnsimeLauncher._remove_legacy_bootstrap | def _remove_legacy_bootstrap():
"""Remove bootstrap projects from old path, they'd be really stale by now."""
home = os.environ['HOME']
old_base_dir = os.path.join(home, '.config', 'classpath_project_ensime')
if os.path.isdir(old_base_dir):
shutil.rmtree(old_base_dir, ignore_errors=True) | python | def _remove_legacy_bootstrap():
"""Remove bootstrap projects from old path, they'd be really stale by now."""
home = os.environ['HOME']
old_base_dir = os.path.join(home, '.config', 'classpath_project_ensime')
if os.path.isdir(old_base_dir):
shutil.rmtree(old_base_dir, ignore_errors=True) | [
"def",
"_remove_legacy_bootstrap",
"(",
")",
":",
"home",
"=",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
"old_base_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"'.config'",
",",
"'classpath_project_ensime'",
")",
"if",
"os",
".",
"path",
... | Remove bootstrap projects from old path, they'd be really stale by now. | [
"Remove",
"bootstrap",
"projects",
"from",
"old",
"path",
"they",
"d",
"be",
"really",
"stale",
"by",
"now",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/launcher.py#L96-L101 | train | 205,978 |
ensime/ensime-vim | ensime_shared/launcher.py | LaunchStrategy._start_process | def _start_process(self, classpath):
"""Given a classpath prepared for running ENSIME, spawns a server process
in a way that is otherwise agnostic to how the strategy installs ENSIME.
Args:
classpath (list of str): list of paths to jars or directories
(Within this function the list is joined with a system dependent
path separator to create a single string argument suitable to
pass to ``java -cp`` as a classpath)
Returns:
EnsimeProcess: A process handle for the launched server.
"""
cache_dir = self.config['cache-dir']
java_flags = self.config['java-flags']
iswindows = os.name == 'nt'
Util.mkdir_p(cache_dir)
log_path = os.path.join(cache_dir, "server.log")
log = open(log_path, "w")
null = open(os.devnull, "r")
java = os.path.join(self.config['java-home'], 'bin', 'java.exe' if iswindows else 'java')
if not os.path.exists(java):
raise InvalidJavaPathError(errno.ENOENT, 'No such file or directory', java)
elif not os.access(java, os.X_OK):
raise InvalidJavaPathError(errno.EACCES, 'Permission denied', java)
args = (
[java, "-cp", (';' if iswindows else ':').join(classpath)] +
[a for a in java_flags if a] +
["-Densime.config={}".format(self.config.filepath),
"org.ensime.server.Server"])
process = subprocess.Popen(
args,
stdin=null,
stdout=log,
stderr=subprocess.STDOUT)
pid_path = os.path.join(cache_dir, "server.pid")
Util.write_file(pid_path, str(process.pid))
def on_stop():
log.close()
null.close()
with catch(Exception):
os.remove(pid_path)
return EnsimeProcess(cache_dir, process, log_path, on_stop) | python | def _start_process(self, classpath):
"""Given a classpath prepared for running ENSIME, spawns a server process
in a way that is otherwise agnostic to how the strategy installs ENSIME.
Args:
classpath (list of str): list of paths to jars or directories
(Within this function the list is joined with a system dependent
path separator to create a single string argument suitable to
pass to ``java -cp`` as a classpath)
Returns:
EnsimeProcess: A process handle for the launched server.
"""
cache_dir = self.config['cache-dir']
java_flags = self.config['java-flags']
iswindows = os.name == 'nt'
Util.mkdir_p(cache_dir)
log_path = os.path.join(cache_dir, "server.log")
log = open(log_path, "w")
null = open(os.devnull, "r")
java = os.path.join(self.config['java-home'], 'bin', 'java.exe' if iswindows else 'java')
if not os.path.exists(java):
raise InvalidJavaPathError(errno.ENOENT, 'No such file or directory', java)
elif not os.access(java, os.X_OK):
raise InvalidJavaPathError(errno.EACCES, 'Permission denied', java)
args = (
[java, "-cp", (';' if iswindows else ':').join(classpath)] +
[a for a in java_flags if a] +
["-Densime.config={}".format(self.config.filepath),
"org.ensime.server.Server"])
process = subprocess.Popen(
args,
stdin=null,
stdout=log,
stderr=subprocess.STDOUT)
pid_path = os.path.join(cache_dir, "server.pid")
Util.write_file(pid_path, str(process.pid))
def on_stop():
log.close()
null.close()
with catch(Exception):
os.remove(pid_path)
return EnsimeProcess(cache_dir, process, log_path, on_stop) | [
"def",
"_start_process",
"(",
"self",
",",
"classpath",
")",
":",
"cache_dir",
"=",
"self",
".",
"config",
"[",
"'cache-dir'",
"]",
"java_flags",
"=",
"self",
".",
"config",
"[",
"'java-flags'",
"]",
"iswindows",
"=",
"os",
".",
"name",
"==",
"'nt'",
"Ut... | Given a classpath prepared for running ENSIME, spawns a server process
in a way that is otherwise agnostic to how the strategy installs ENSIME.
Args:
classpath (list of str): list of paths to jars or directories
(Within this function the list is joined with a system dependent
path separator to create a single string argument suitable to
pass to ``java -cp`` as a classpath)
Returns:
EnsimeProcess: A process handle for the launched server. | [
"Given",
"a",
"classpath",
"prepared",
"for",
"running",
"ENSIME",
"spawns",
"a",
"server",
"process",
"in",
"a",
"way",
"that",
"is",
"otherwise",
"agnostic",
"to",
"how",
"the",
"strategy",
"installs",
"ENSIME",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/launcher.py#L146-L193 | train | 205,979 |
ensime/ensime-vim | ensime_shared/launcher.py | SbtBootstrap.install | def install(self):
"""Installs ENSIME server with a bootstrap sbt project and generates its classpath."""
project_dir = os.path.dirname(self.classpath_file)
sbt_plugin = """addSbtPlugin("{0}" % "{1}" % "{2}")"""
Util.mkdir_p(project_dir)
Util.mkdir_p(os.path.join(project_dir, "project"))
Util.write_file(
os.path.join(project_dir, "build.sbt"),
self.build_sbt())
Util.write_file(
os.path.join(project_dir, "project", "build.properties"),
"sbt.version={}".format(self.SBT_VERSION))
Util.write_file(
os.path.join(project_dir, "project", "plugins.sbt"),
sbt_plugin.format(*self.SBT_COURSIER_COORDS))
# Synchronous update of the classpath via sbt
# see https://github.com/ensime/ensime-vim/issues/29
cd_cmd = "cd {}".format(project_dir)
sbt_cmd = "sbt -Dsbt.log.noformat=true -batch saveClasspath"
if int(self.vim.eval("has('nvim')")):
import tempfile
import re
tmp_dir = tempfile.gettempdir()
flag_file = "{}/ensime-vim-classpath.flag".format(tmp_dir)
self.vim.command("echo 'Waiting for generation of classpath...'")
if re.match(".+fish$", self.vim.eval("&shell")):
sbt_cmd += "; echo $status > {}".format(flag_file)
self.vim.command("terminal {}; and {}".format(cd_cmd, sbt_cmd))
else:
sbt_cmd += "; echo $? > {}".format(flag_file)
self.vim.command("terminal ({} && {})".format(cd_cmd, sbt_cmd))
# Block execution when sbt is run
waiting_for_flag = True
while waiting_for_flag:
waiting_for_flag = not os.path.isfile(flag_file)
if not waiting_for_flag:
with open(flag_file, "r") as f:
rtcode = f.readline()
os.remove(flag_file)
if rtcode and int(rtcode) != 0: # error
self.vim.command(
"echo 'Something wrong happened, check the "
"execution log...'")
return None
else:
time.sleep(0.2)
else:
self.vim.command("!({} && {})".format(cd_cmd, sbt_cmd))
success = self.reorder_classpath(self.classpath_file)
if not success:
self.vim.command("echo 'Classpath ordering failed.'")
return True | python | def install(self):
"""Installs ENSIME server with a bootstrap sbt project and generates its classpath."""
project_dir = os.path.dirname(self.classpath_file)
sbt_plugin = """addSbtPlugin("{0}" % "{1}" % "{2}")"""
Util.mkdir_p(project_dir)
Util.mkdir_p(os.path.join(project_dir, "project"))
Util.write_file(
os.path.join(project_dir, "build.sbt"),
self.build_sbt())
Util.write_file(
os.path.join(project_dir, "project", "build.properties"),
"sbt.version={}".format(self.SBT_VERSION))
Util.write_file(
os.path.join(project_dir, "project", "plugins.sbt"),
sbt_plugin.format(*self.SBT_COURSIER_COORDS))
# Synchronous update of the classpath via sbt
# see https://github.com/ensime/ensime-vim/issues/29
cd_cmd = "cd {}".format(project_dir)
sbt_cmd = "sbt -Dsbt.log.noformat=true -batch saveClasspath"
if int(self.vim.eval("has('nvim')")):
import tempfile
import re
tmp_dir = tempfile.gettempdir()
flag_file = "{}/ensime-vim-classpath.flag".format(tmp_dir)
self.vim.command("echo 'Waiting for generation of classpath...'")
if re.match(".+fish$", self.vim.eval("&shell")):
sbt_cmd += "; echo $status > {}".format(flag_file)
self.vim.command("terminal {}; and {}".format(cd_cmd, sbt_cmd))
else:
sbt_cmd += "; echo $? > {}".format(flag_file)
self.vim.command("terminal ({} && {})".format(cd_cmd, sbt_cmd))
# Block execution when sbt is run
waiting_for_flag = True
while waiting_for_flag:
waiting_for_flag = not os.path.isfile(flag_file)
if not waiting_for_flag:
with open(flag_file, "r") as f:
rtcode = f.readline()
os.remove(flag_file)
if rtcode and int(rtcode) != 0: # error
self.vim.command(
"echo 'Something wrong happened, check the "
"execution log...'")
return None
else:
time.sleep(0.2)
else:
self.vim.command("!({} && {})".format(cd_cmd, sbt_cmd))
success = self.reorder_classpath(self.classpath_file)
if not success:
self.vim.command("echo 'Classpath ordering failed.'")
return True | [
"def",
"install",
"(",
"self",
")",
":",
"project_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"classpath_file",
")",
"sbt_plugin",
"=",
"\"\"\"addSbtPlugin(\"{0}\" % \"{1}\" % \"{2}\")\"\"\"",
"Util",
".",
"mkdir_p",
"(",
"project_dir",
")",
... | Installs ENSIME server with a bootstrap sbt project and generates its classpath. | [
"Installs",
"ENSIME",
"server",
"with",
"a",
"bootstrap",
"sbt",
"project",
"and",
"generates",
"its",
"classpath",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/launcher.py#L295-L352 | train | 205,980 |
ensime/ensime-vim | ensime_shared/launcher.py | SbtBootstrap.reorder_classpath | def reorder_classpath(self, classpath_file):
"""Reorder classpath and put monkeys-jar in the first place."""
success = False
with catch((IOError, OSError)):
with open(classpath_file, "r") as f:
classpath = f.readline()
# Proceed if classpath is non-empty
if classpath:
units = classpath.split(":")
reordered_units = []
for unit in units:
if "monkeys" in unit:
reordered_units.insert(0, unit)
else:
reordered_units.append(unit)
reordered_classpath = ":".join(reordered_units)
with open(classpath_file, "w") as f:
f.write(reordered_classpath)
success = True
return success | python | def reorder_classpath(self, classpath_file):
"""Reorder classpath and put monkeys-jar in the first place."""
success = False
with catch((IOError, OSError)):
with open(classpath_file, "r") as f:
classpath = f.readline()
# Proceed if classpath is non-empty
if classpath:
units = classpath.split(":")
reordered_units = []
for unit in units:
if "monkeys" in unit:
reordered_units.insert(0, unit)
else:
reordered_units.append(unit)
reordered_classpath = ":".join(reordered_units)
with open(classpath_file, "w") as f:
f.write(reordered_classpath)
success = True
return success | [
"def",
"reorder_classpath",
"(",
"self",
",",
"classpath_file",
")",
":",
"success",
"=",
"False",
"with",
"catch",
"(",
"(",
"IOError",
",",
"OSError",
")",
")",
":",
"with",
"open",
"(",
"classpath_file",
",",
"\"r\"",
")",
"as",
"f",
":",
"classpath",... | Reorder classpath and put monkeys-jar in the first place. | [
"Reorder",
"classpath",
"and",
"put",
"monkeys",
"-",
"jar",
"in",
"the",
"first",
"place",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/launcher.py#L394-L418 | train | 205,981 |
ensime/ensime-vim | ensime_shared/config.py | ProjectConfig.find_from | def find_from(path):
"""Find path of an .ensime config, searching recursively upward from path.
Args:
path (str): Path of a file or directory from where to start searching.
Returns:
str: Canonical path of nearest ``.ensime``, or ``None`` if not found.
"""
realpath = os.path.realpath(path)
config_path = os.path.join(realpath, '.ensime')
if os.path.isfile(config_path):
return config_path
elif realpath == os.path.abspath('/'):
return None
else:
dirname = os.path.dirname(realpath)
return ProjectConfig.find_from(dirname) | python | def find_from(path):
"""Find path of an .ensime config, searching recursively upward from path.
Args:
path (str): Path of a file or directory from where to start searching.
Returns:
str: Canonical path of nearest ``.ensime``, or ``None`` if not found.
"""
realpath = os.path.realpath(path)
config_path = os.path.join(realpath, '.ensime')
if os.path.isfile(config_path):
return config_path
elif realpath == os.path.abspath('/'):
return None
else:
dirname = os.path.dirname(realpath)
return ProjectConfig.find_from(dirname) | [
"def",
"find_from",
"(",
"path",
")",
":",
"realpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"realpath",
",",
"'.ensime'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(... | Find path of an .ensime config, searching recursively upward from path.
Args:
path (str): Path of a file or directory from where to start searching.
Returns:
str: Canonical path of nearest ``.ensime``, or ``None`` if not found. | [
"Find",
"path",
"of",
"an",
".",
"ensime",
"config",
"searching",
"recursively",
"upward",
"from",
"path",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/config.py#L79-L97 | train | 205,982 |
ensime/ensime-vim | ensime_shared/config.py | ProjectConfig.parse | def parse(path):
"""Parse an ``.ensime`` config file from S-expressions.
Args:
path (str): Path of an ``.ensime`` file to parse.
Returns:
dict: Configuration values with string keys.
"""
def paired(iterable):
"""s -> (s0, s1), (s2, s3), (s4, s5), ..."""
cursor = iter(iterable)
return zip(cursor, cursor)
def unwrap_if_sexp_symbol(datum):
"""Convert Symbol(':key') to ':key' (Symbol isn't hashable for dict keys).
"""
return datum.value() if isinstance(datum, sexpdata.Symbol) else datum
def sexp2dict(sexps):
"""Transforms a nested list structure from sexpdata to dict."""
newdict = {}
# Turn flat list into associative pairs
for key, value in paired(sexps):
key = str(unwrap_if_sexp_symbol(key)).lstrip(':')
# Recursively transform nested lists
if isinstance(value, list) and value:
if isinstance(value[0], list):
newdict[key] = [sexp2dict(val) for val in value]
elif isinstance(value[0], sexpdata.Symbol):
newdict[key] = sexp2dict(value)
else:
newdict[key] = value
else:
newdict[key] = value
return newdict
conf = sexpdata.loads(Util.read_file(path))
return sexp2dict(conf) | python | def parse(path):
"""Parse an ``.ensime`` config file from S-expressions.
Args:
path (str): Path of an ``.ensime`` file to parse.
Returns:
dict: Configuration values with string keys.
"""
def paired(iterable):
"""s -> (s0, s1), (s2, s3), (s4, s5), ..."""
cursor = iter(iterable)
return zip(cursor, cursor)
def unwrap_if_sexp_symbol(datum):
"""Convert Symbol(':key') to ':key' (Symbol isn't hashable for dict keys).
"""
return datum.value() if isinstance(datum, sexpdata.Symbol) else datum
def sexp2dict(sexps):
"""Transforms a nested list structure from sexpdata to dict."""
newdict = {}
# Turn flat list into associative pairs
for key, value in paired(sexps):
key = str(unwrap_if_sexp_symbol(key)).lstrip(':')
# Recursively transform nested lists
if isinstance(value, list) and value:
if isinstance(value[0], list):
newdict[key] = [sexp2dict(val) for val in value]
elif isinstance(value[0], sexpdata.Symbol):
newdict[key] = sexp2dict(value)
else:
newdict[key] = value
else:
newdict[key] = value
return newdict
conf = sexpdata.loads(Util.read_file(path))
return sexp2dict(conf) | [
"def",
"parse",
"(",
"path",
")",
":",
"def",
"paired",
"(",
"iterable",
")",
":",
"\"\"\"s -> (s0, s1), (s2, s3), (s4, s5), ...\"\"\"",
"cursor",
"=",
"iter",
"(",
"iterable",
")",
"return",
"zip",
"(",
"cursor",
",",
"cursor",
")",
"def",
"unwrap_if_sexp_symbo... | Parse an ``.ensime`` config file from S-expressions.
Args:
path (str): Path of an ``.ensime`` file to parse.
Returns:
dict: Configuration values with string keys. | [
"Parse",
"an",
".",
"ensime",
"config",
"file",
"from",
"S",
"-",
"expressions",
"."
] | caa734e84f002b25446c615706283a74edd4ecfe | https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/config.py#L100-L142 | train | 205,983 |
algorithmiaio/algorithmia-python | Algorithmia/acl.py | Acl.from_acl_response | def from_acl_response(acl_response):
'''Takes JSON response from API and converts to ACL object'''
if 'read' in acl_response:
read_acl = AclType.from_acl_response(acl_response['read'])
return Acl(read_acl)
else:
raise ValueError('Response does not contain read ACL') | python | def from_acl_response(acl_response):
'''Takes JSON response from API and converts to ACL object'''
if 'read' in acl_response:
read_acl = AclType.from_acl_response(acl_response['read'])
return Acl(read_acl)
else:
raise ValueError('Response does not contain read ACL') | [
"def",
"from_acl_response",
"(",
"acl_response",
")",
":",
"if",
"'read'",
"in",
"acl_response",
":",
"read_acl",
"=",
"AclType",
".",
"from_acl_response",
"(",
"acl_response",
"[",
"'read'",
"]",
")",
"return",
"Acl",
"(",
"read_acl",
")",
"else",
":",
"rai... | Takes JSON response from API and converts to ACL object | [
"Takes",
"JSON",
"response",
"from",
"API",
"and",
"converts",
"to",
"ACL",
"object"
] | fe33e6524272ff7ca11c43d1d6985890e6c48a79 | https://github.com/algorithmiaio/algorithmia-python/blob/fe33e6524272ff7ca11c43d1d6985890e6c48a79/Algorithmia/acl.py#L6-L12 | train | 205,984 |
algorithmiaio/algorithmia-python | Algorithmia/datadirectory.py | DataDirectory.create | def create(self, acl=None):
'''Creates a directory, optionally include Acl argument to set permissions'''
parent, name = getParentAndBase(self.path)
json = { 'name': name }
if acl is not None:
json['acl'] = acl.to_api_param()
response = self.client.postJsonHelper(DataDirectory._getUrl(parent), json, False)
if (response.status_code != 200):
raise DataApiError("Directory creation failed: " + str(response.content)) | python | def create(self, acl=None):
'''Creates a directory, optionally include Acl argument to set permissions'''
parent, name = getParentAndBase(self.path)
json = { 'name': name }
if acl is not None:
json['acl'] = acl.to_api_param()
response = self.client.postJsonHelper(DataDirectory._getUrl(parent), json, False)
if (response.status_code != 200):
raise DataApiError("Directory creation failed: " + str(response.content)) | [
"def",
"create",
"(",
"self",
",",
"acl",
"=",
"None",
")",
":",
"parent",
",",
"name",
"=",
"getParentAndBase",
"(",
"self",
".",
"path",
")",
"json",
"=",
"{",
"'name'",
":",
"name",
"}",
"if",
"acl",
"is",
"not",
"None",
":",
"json",
"[",
"'ac... | Creates a directory, optionally include Acl argument to set permissions | [
"Creates",
"a",
"directory",
"optionally",
"include",
"Acl",
"argument",
"to",
"set",
"permissions"
] | fe33e6524272ff7ca11c43d1d6985890e6c48a79 | https://github.com/algorithmiaio/algorithmia-python/blob/fe33e6524272ff7ca11c43d1d6985890e6c48a79/Algorithmia/datadirectory.py#L40-L48 | train | 205,985 |
algorithmiaio/algorithmia-python | Algorithmia/datadirectory.py | DataDirectory.get_permissions | def get_permissions(self):
'''
Returns permissions for this directory or None if it's a special collection such as
.session or .algo
'''
response = self.client.getHelper(self.url, acl='true')
if response.status_code != 200:
raise DataApiError('Unable to get permissions:' + str(response.content))
content = response.json()
if 'acl' in content:
return Acl.from_acl_response(content['acl'])
else:
return None | python | def get_permissions(self):
'''
Returns permissions for this directory or None if it's a special collection such as
.session or .algo
'''
response = self.client.getHelper(self.url, acl='true')
if response.status_code != 200:
raise DataApiError('Unable to get permissions:' + str(response.content))
content = response.json()
if 'acl' in content:
return Acl.from_acl_response(content['acl'])
else:
return None | [
"def",
"get_permissions",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"getHelper",
"(",
"self",
".",
"url",
",",
"acl",
"=",
"'true'",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"raise",
"DataApiError",
"(",
"'... | Returns permissions for this directory or None if it's a special collection such as
.session or .algo | [
"Returns",
"permissions",
"for",
"this",
"directory",
"or",
"None",
"if",
"it",
"s",
"a",
"special",
"collection",
"such",
"as",
".",
"session",
"or",
".",
"algo"
] | fe33e6524272ff7ca11c43d1d6985890e6c48a79 | https://github.com/algorithmiaio/algorithmia-python/blob/fe33e6524272ff7ca11c43d1d6985890e6c48a79/Algorithmia/datadirectory.py#L77-L89 | train | 205,986 |
heitzmann/gdspy | gdspy/__init__.py | _eight_byte_real | def _eight_byte_real(value):
"""
Convert a number into the GDSII 8 byte real format.
Parameters
----------
value : number
The number to be converted.
Returns
-------
out : string
The GDSII binary string that represents ``value``.
"""
if value == 0:
return b'\x00\x00\x00\x00\x00\x00\x00\x00'
if value < 0:
byte1 = 0x80
value = -value
else:
byte1 = 0x00
fexp = numpy.log2(value) / 4
exponent = int(numpy.ceil(fexp))
if fexp == exponent:
exponent += 1
mantissa = int(value * 16.**(14 - exponent))
byte1 += exponent + 64
byte2 = (mantissa // 281474976710656)
short3 = (mantissa % 281474976710656) // 4294967296
long4 = mantissa % 4294967296
return struct.pack(">HHL", byte1 * 256 + byte2, short3, long4) | python | def _eight_byte_real(value):
"""
Convert a number into the GDSII 8 byte real format.
Parameters
----------
value : number
The number to be converted.
Returns
-------
out : string
The GDSII binary string that represents ``value``.
"""
if value == 0:
return b'\x00\x00\x00\x00\x00\x00\x00\x00'
if value < 0:
byte1 = 0x80
value = -value
else:
byte1 = 0x00
fexp = numpy.log2(value) / 4
exponent = int(numpy.ceil(fexp))
if fexp == exponent:
exponent += 1
mantissa = int(value * 16.**(14 - exponent))
byte1 += exponent + 64
byte2 = (mantissa // 281474976710656)
short3 = (mantissa % 281474976710656) // 4294967296
long4 = mantissa % 4294967296
return struct.pack(">HHL", byte1 * 256 + byte2, short3, long4) | [
"def",
"_eight_byte_real",
"(",
"value",
")",
":",
"if",
"value",
"==",
"0",
":",
"return",
"b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'",
"if",
"value",
"<",
"0",
":",
"byte1",
"=",
"0x80",
"value",
"=",
"-",
"value",
"else",
":",
"byte1",
"=",
"0x00",
"f... | Convert a number into the GDSII 8 byte real format.
Parameters
----------
value : number
The number to be converted.
Returns
-------
out : string
The GDSII binary string that represents ``value``. | [
"Convert",
"a",
"number",
"into",
"the",
"GDSII",
"8",
"byte",
"real",
"format",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L67-L97 | train | 205,987 |
heitzmann/gdspy | gdspy/__init__.py | _eight_byte_real_to_float | def _eight_byte_real_to_float(value):
"""
Convert a number from GDSII 8 byte real format to float.
Parameters
----------
value : string
The GDSII binary string representation of the number.
Returns
-------
out : float
The number represented by ``value``.
"""
short1, short2, long3 = struct.unpack('>HHL', value)
exponent = (short1 & 0x7f00) // 256 - 64
mantissa = (((short1 & 0x00ff) * 65536 + short2) * 4294967296 +
long3) / 72057594037927936.0
if short1 & 0x8000:
return -mantissa * 16.**exponent
return mantissa * 16.**exponent | python | def _eight_byte_real_to_float(value):
"""
Convert a number from GDSII 8 byte real format to float.
Parameters
----------
value : string
The GDSII binary string representation of the number.
Returns
-------
out : float
The number represented by ``value``.
"""
short1, short2, long3 = struct.unpack('>HHL', value)
exponent = (short1 & 0x7f00) // 256 - 64
mantissa = (((short1 & 0x00ff) * 65536 + short2) * 4294967296 +
long3) / 72057594037927936.0
if short1 & 0x8000:
return -mantissa * 16.**exponent
return mantissa * 16.**exponent | [
"def",
"_eight_byte_real_to_float",
"(",
"value",
")",
":",
"short1",
",",
"short2",
",",
"long3",
"=",
"struct",
".",
"unpack",
"(",
"'>HHL'",
",",
"value",
")",
"exponent",
"=",
"(",
"short1",
"&",
"0x7f00",
")",
"//",
"256",
"-",
"64",
"mantissa",
"... | Convert a number from GDSII 8 byte real format to float.
Parameters
----------
value : string
The GDSII binary string representation of the number.
Returns
-------
out : float
The number represented by ``value``. | [
"Convert",
"a",
"number",
"from",
"GDSII",
"8",
"byte",
"real",
"format",
"to",
"float",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L100-L120 | train | 205,988 |
heitzmann/gdspy | gdspy/__init__.py | slice | def slice(objects, position, axis, precision=1e-3, layer=0, datatype=0):
"""
Slice polygons and polygon sets at given positions along an axis.
Parameters
----------
objects : ``PolygonSet``, or list
Operand of the slice operation. If this is a list, each element
must be a ``PolygonSet``, ``CellReference``, ``CellArray``, or
an array-like[N][2] of vertices of a polygon.
position : number or list of numbers
Positions to perform the slicing operation along the specified
axis.
axis : 0 or 1
Axis along which the polygon will be sliced.
precision : float
Desired precision for rounding vertice coordinates.
layer : integer, list
The GDSII layer numbers for the elements between each division.
If the number of layers in the list is less than the number of
divided regions, the list is repeated.
datatype : integer
The GDSII datatype for the resulting element (between 0 and
255).
Returns
-------
out : list[N] of PolygonSet
Result of the slicing operation, with N = len(positions) + 1.
Each PolygonSet comprises all polygons between 2 adjacent
slicing positions, in crescent order.
Examples
--------
>>> ring = gdspy.Round((0, 0), 10, inner_radius = 5)
>>> result = gdspy.slice(ring, [-7, 7], 0)
>>> cell.add(result[1])
"""
if not isinstance(layer, list):
layer = [layer]
if not isinstance(objects, list):
objects = [objects]
if not isinstance(position, list):
pos = [position]
else:
pos = sorted(position)
result = [[] for _ in range(len(pos) + 1)]
polygons = []
for obj in objects:
if isinstance(obj, PolygonSet):
polygons.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
polygons.extend(obj.get_polygons())
else:
polygons.append(obj)
scaling = 1 / precision
for pol in polygons:
for r, p in zip(result, clipper._chop(pol, pos, axis, scaling)):
r.extend(p)
for i in range(len(result)):
result[i] = PolygonSet(result[i], layer[i % len(layer)], datatype)
return result | python | def slice(objects, position, axis, precision=1e-3, layer=0, datatype=0):
"""
Slice polygons and polygon sets at given positions along an axis.
Parameters
----------
objects : ``PolygonSet``, or list
Operand of the slice operation. If this is a list, each element
must be a ``PolygonSet``, ``CellReference``, ``CellArray``, or
an array-like[N][2] of vertices of a polygon.
position : number or list of numbers
Positions to perform the slicing operation along the specified
axis.
axis : 0 or 1
Axis along which the polygon will be sliced.
precision : float
Desired precision for rounding vertice coordinates.
layer : integer, list
The GDSII layer numbers for the elements between each division.
If the number of layers in the list is less than the number of
divided regions, the list is repeated.
datatype : integer
The GDSII datatype for the resulting element (between 0 and
255).
Returns
-------
out : list[N] of PolygonSet
Result of the slicing operation, with N = len(positions) + 1.
Each PolygonSet comprises all polygons between 2 adjacent
slicing positions, in crescent order.
Examples
--------
>>> ring = gdspy.Round((0, 0), 10, inner_radius = 5)
>>> result = gdspy.slice(ring, [-7, 7], 0)
>>> cell.add(result[1])
"""
if not isinstance(layer, list):
layer = [layer]
if not isinstance(objects, list):
objects = [objects]
if not isinstance(position, list):
pos = [position]
else:
pos = sorted(position)
result = [[] for _ in range(len(pos) + 1)]
polygons = []
for obj in objects:
if isinstance(obj, PolygonSet):
polygons.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
polygons.extend(obj.get_polygons())
else:
polygons.append(obj)
scaling = 1 / precision
for pol in polygons:
for r, p in zip(result, clipper._chop(pol, pos, axis, scaling)):
r.extend(p)
for i in range(len(result)):
result[i] = PolygonSet(result[i], layer[i % len(layer)], datatype)
return result | [
"def",
"slice",
"(",
"objects",
",",
"position",
",",
"axis",
",",
"precision",
"=",
"1e-3",
",",
"layer",
"=",
"0",
",",
"datatype",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"layer",
",",
"list",
")",
":",
"layer",
"=",
"[",
"layer",
... | Slice polygons and polygon sets at given positions along an axis.
Parameters
----------
objects : ``PolygonSet``, or list
Operand of the slice operation. If this is a list, each element
must be a ``PolygonSet``, ``CellReference``, ``CellArray``, or
an array-like[N][2] of vertices of a polygon.
position : number or list of numbers
Positions to perform the slicing operation along the specified
axis.
axis : 0 or 1
Axis along which the polygon will be sliced.
precision : float
Desired precision for rounding vertice coordinates.
layer : integer, list
The GDSII layer numbers for the elements between each division.
If the number of layers in the list is less than the number of
divided regions, the list is repeated.
datatype : integer
The GDSII datatype for the resulting element (between 0 and
255).
Returns
-------
out : list[N] of PolygonSet
Result of the slicing operation, with N = len(positions) + 1.
Each PolygonSet comprises all polygons between 2 adjacent
slicing positions, in crescent order.
Examples
--------
>>> ring = gdspy.Round((0, 0), 10, inner_radius = 5)
>>> result = gdspy.slice(ring, [-7, 7], 0)
>>> cell.add(result[1]) | [
"Slice",
"polygons",
"and",
"polygon",
"sets",
"at",
"given",
"positions",
"along",
"an",
"axis",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L3843-L3904 | train | 205,989 |
heitzmann/gdspy | gdspy/__init__.py | offset | def offset(polygons,
distance,
join='miter',
tolerance=2,
precision=0.001,
join_first=False,
max_points=199,
layer=0,
datatype=0):
"""
Shrink or expand a polygon or polygon set.
Parameters
----------
polygons : polygon or array-like
Polygons to be offset. Must be a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
vertices of a polygon.
distance : number
Offset distance. Positive to expand, negative to shrink.
join : {'miter', 'bevel', 'round'}
Type of join used to create the offset polygon.
tolerance : number
For miter joints, this number must be at least 2 and it
represents the maximun distance in multiples of offset betwen
new vertices and their original position before beveling to
avoid spikes at acute joints. For round joints, it indicates
the curvature resolution in number of points per full circle.
precision : float
Desired precision for rounding vertice coordinates.
join_first : bool
Join all paths before offseting to avoid unecessary joins in
adjacent polygon sides.
max_points : integer
If greater than 4, fracture the resulting polygons to ensure
they have at most ``max_points`` vertices. This is not a
tessellating function, so this number should be as high as
possible. For example, it should be set to 199 for polygons
being drawn in GDSII files.
layer : integer
The GDSII layer number for the resulting element.
datatype : integer
The GDSII datatype for the resulting element (between 0 and
255).
Returns
-------
out : ``PolygonSet`` or ``None``
Return the offset shape as a set of polygons.
"""
poly = []
if isinstance(polygons, PolygonSet):
poly.extend(polygons.polygons)
elif isinstance(polygons, CellReference) or isinstance(
polygons, CellArray):
poly.extend(polygons.get_polygons())
else:
for obj in polygons:
if isinstance(obj, PolygonSet):
poly.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
poly.extend(obj.get_polygons())
else:
poly.append(obj)
result = clipper.offset(poly, distance, join, tolerance, 1 / precision, 1
if join_first else 0)
return None if len(result) == 0 else PolygonSet(
result, layer, datatype, verbose=False).fracture(
max_points, precision) | python | def offset(polygons,
distance,
join='miter',
tolerance=2,
precision=0.001,
join_first=False,
max_points=199,
layer=0,
datatype=0):
"""
Shrink or expand a polygon or polygon set.
Parameters
----------
polygons : polygon or array-like
Polygons to be offset. Must be a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
vertices of a polygon.
distance : number
Offset distance. Positive to expand, negative to shrink.
join : {'miter', 'bevel', 'round'}
Type of join used to create the offset polygon.
tolerance : number
For miter joints, this number must be at least 2 and it
represents the maximun distance in multiples of offset betwen
new vertices and their original position before beveling to
avoid spikes at acute joints. For round joints, it indicates
the curvature resolution in number of points per full circle.
precision : float
Desired precision for rounding vertice coordinates.
join_first : bool
Join all paths before offseting to avoid unecessary joins in
adjacent polygon sides.
max_points : integer
If greater than 4, fracture the resulting polygons to ensure
they have at most ``max_points`` vertices. This is not a
tessellating function, so this number should be as high as
possible. For example, it should be set to 199 for polygons
being drawn in GDSII files.
layer : integer
The GDSII layer number for the resulting element.
datatype : integer
The GDSII datatype for the resulting element (between 0 and
255).
Returns
-------
out : ``PolygonSet`` or ``None``
Return the offset shape as a set of polygons.
"""
poly = []
if isinstance(polygons, PolygonSet):
poly.extend(polygons.polygons)
elif isinstance(polygons, CellReference) or isinstance(
polygons, CellArray):
poly.extend(polygons.get_polygons())
else:
for obj in polygons:
if isinstance(obj, PolygonSet):
poly.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
poly.extend(obj.get_polygons())
else:
poly.append(obj)
result = clipper.offset(poly, distance, join, tolerance, 1 / precision, 1
if join_first else 0)
return None if len(result) == 0 else PolygonSet(
result, layer, datatype, verbose=False).fracture(
max_points, precision) | [
"def",
"offset",
"(",
"polygons",
",",
"distance",
",",
"join",
"=",
"'miter'",
",",
"tolerance",
"=",
"2",
",",
"precision",
"=",
"0.001",
",",
"join_first",
"=",
"False",
",",
"max_points",
"=",
"199",
",",
"layer",
"=",
"0",
",",
"datatype",
"=",
... | Shrink or expand a polygon or polygon set.
Parameters
----------
polygons : polygon or array-like
Polygons to be offset. Must be a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
vertices of a polygon.
distance : number
Offset distance. Positive to expand, negative to shrink.
join : {'miter', 'bevel', 'round'}
Type of join used to create the offset polygon.
tolerance : number
For miter joints, this number must be at least 2 and it
represents the maximun distance in multiples of offset betwen
new vertices and their original position before beveling to
avoid spikes at acute joints. For round joints, it indicates
the curvature resolution in number of points per full circle.
precision : float
Desired precision for rounding vertice coordinates.
join_first : bool
Join all paths before offseting to avoid unecessary joins in
adjacent polygon sides.
max_points : integer
If greater than 4, fracture the resulting polygons to ensure
they have at most ``max_points`` vertices. This is not a
tessellating function, so this number should be as high as
possible. For example, it should be set to 199 for polygons
being drawn in GDSII files.
layer : integer
The GDSII layer number for the resulting element.
datatype : integer
The GDSII datatype for the resulting element (between 0 and
255).
Returns
-------
out : ``PolygonSet`` or ``None``
Return the offset shape as a set of polygons. | [
"Shrink",
"or",
"expand",
"a",
"polygon",
"or",
"polygon",
"set",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L3907-L3976 | train | 205,990 |
heitzmann/gdspy | gdspy/__init__.py | fast_boolean | def fast_boolean(operandA,
operandB,
operation,
precision=0.001,
max_points=199,
layer=0,
datatype=0):
"""
Execute any boolean operation between 2 polygons or polygon sets.
Parameters
----------
operandA : polygon or array-like
First operand. Must be a ``PolygonSet``, ``CellReference``,
``CellArray``, or an array. The array may contain any of the
previous objects or an array-like[N][2] of vertices of a
polygon.
operandB : polygon, array-like or ``None``
Second operand. Must be ``None``, a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
vertices of a polygon.
operation : {'or', 'and', 'xor', 'not'}
Boolean operation to be executed. The 'not' operation returns
the difference ``operandA - operandB``.
precision : float
Desired precision for rounding vertice coordinates.
max_points : integer
If greater than 4, fracture the resulting polygons to ensure
they have at most ``max_points`` vertices. This is not a
tessellating function, so this number should be as high as
possible. For example, it should be set to 199 for polygons
being drawn in GDSII files.
layer : integer
The GDSII layer number for the resulting element.
datatype : integer
The GDSII datatype for the resulting element (between 0 and
255).
Returns
-------
out : PolygonSet or ``None``
Result of the boolean operation.
"""
polyA = []
polyB = []
for poly, obj in zip((polyA, polyB), (operandA, operandB)):
if isinstance(obj, PolygonSet):
poly.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
poly.extend(obj.get_polygons())
elif obj is not None:
for inobj in obj:
if isinstance(inobj, PolygonSet):
poly.extend(inobj.polygons)
elif isinstance(inobj, CellReference) or isinstance(
inobj, CellArray):
poly.extend(inobj.get_polygons())
else:
poly.append(inobj)
if len(polyB) == 0:
polyB.append(polyA.pop())
result = clipper.clip(polyA, polyB, operation, 1 / precision)
return None if len(result) == 0 else PolygonSet(
result, layer, datatype, verbose=False).fracture(
max_points, precision) | python | def fast_boolean(operandA,
operandB,
operation,
precision=0.001,
max_points=199,
layer=0,
datatype=0):
"""
Execute any boolean operation between 2 polygons or polygon sets.
Parameters
----------
operandA : polygon or array-like
First operand. Must be a ``PolygonSet``, ``CellReference``,
``CellArray``, or an array. The array may contain any of the
previous objects or an array-like[N][2] of vertices of a
polygon.
operandB : polygon, array-like or ``None``
Second operand. Must be ``None``, a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
vertices of a polygon.
operation : {'or', 'and', 'xor', 'not'}
Boolean operation to be executed. The 'not' operation returns
the difference ``operandA - operandB``.
precision : float
Desired precision for rounding vertice coordinates.
max_points : integer
If greater than 4, fracture the resulting polygons to ensure
they have at most ``max_points`` vertices. This is not a
tessellating function, so this number should be as high as
possible. For example, it should be set to 199 for polygons
being drawn in GDSII files.
layer : integer
The GDSII layer number for the resulting element.
datatype : integer
The GDSII datatype for the resulting element (between 0 and
255).
Returns
-------
out : PolygonSet or ``None``
Result of the boolean operation.
"""
polyA = []
polyB = []
for poly, obj in zip((polyA, polyB), (operandA, operandB)):
if isinstance(obj, PolygonSet):
poly.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
poly.extend(obj.get_polygons())
elif obj is not None:
for inobj in obj:
if isinstance(inobj, PolygonSet):
poly.extend(inobj.polygons)
elif isinstance(inobj, CellReference) or isinstance(
inobj, CellArray):
poly.extend(inobj.get_polygons())
else:
poly.append(inobj)
if len(polyB) == 0:
polyB.append(polyA.pop())
result = clipper.clip(polyA, polyB, operation, 1 / precision)
return None if len(result) == 0 else PolygonSet(
result, layer, datatype, verbose=False).fracture(
max_points, precision) | [
"def",
"fast_boolean",
"(",
"operandA",
",",
"operandB",
",",
"operation",
",",
"precision",
"=",
"0.001",
",",
"max_points",
"=",
"199",
",",
"layer",
"=",
"0",
",",
"datatype",
"=",
"0",
")",
":",
"polyA",
"=",
"[",
"]",
"polyB",
"=",
"[",
"]",
"... | Execute any boolean operation between 2 polygons or polygon sets.
Parameters
----------
operandA : polygon or array-like
First operand. Must be a ``PolygonSet``, ``CellReference``,
``CellArray``, or an array. The array may contain any of the
previous objects or an array-like[N][2] of vertices of a
polygon.
operandB : polygon, array-like or ``None``
Second operand. Must be ``None``, a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
vertices of a polygon.
operation : {'or', 'and', 'xor', 'not'}
Boolean operation to be executed. The 'not' operation returns
the difference ``operandA - operandB``.
precision : float
Desired precision for rounding vertice coordinates.
max_points : integer
If greater than 4, fracture the resulting polygons to ensure
they have at most ``max_points`` vertices. This is not a
tessellating function, so this number should be as high as
possible. For example, it should be set to 199 for polygons
being drawn in GDSII files.
layer : integer
The GDSII layer number for the resulting element.
datatype : integer
The GDSII datatype for the resulting element (between 0 and
255).
Returns
-------
out : PolygonSet or ``None``
Result of the boolean operation. | [
"Execute",
"any",
"boolean",
"operation",
"between",
"2",
"polygons",
"or",
"polygon",
"sets",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L3979-L4044 | train | 205,991 |
heitzmann/gdspy | gdspy/__init__.py | inside | def inside(points, polygons, short_circuit='any', precision=0.001):
"""
Test whether each of the points is within the given set of polygons.
Parameters
----------
points : array-like[N][2] or list of array-like[N][2]
Coordinates of the points to be tested or groups of points to be
tested together.
polygons : polygon or array-like
Polygons to be tested against. Must be a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
vertices of a polygon.
short_circuit : {'any', 'all'}
If `points` is a list of point groups, testing within each group
will be short-circuited if any of the points in the group is
inside ('any') or outside ('all') the polygons. If `points` is
simply a list of points, this parameter has no effect.
precision : float
Desired precision for rounding vertice coordinates.
Returns
-------
out : tuple
Tuple of booleans indicating if each of the points or point
groups is inside the set of polygons.
"""
poly = []
if isinstance(polygons, PolygonSet):
poly.extend(polygons.polygons)
elif isinstance(polygons, CellReference) or isinstance(
polygons, CellArray):
poly.extend(polygons.get_polygons())
else:
for obj in polygons:
if isinstance(obj, PolygonSet):
poly.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
poly.extend(obj.get_polygons())
else:
poly.append(obj)
if hasattr(points[0][0], '__iter__'):
pts = points
sc = 1 if short_circuit == 'any' else -1
else:
pts = (points, )
sc = 0
return clipper.inside(pts, poly, sc, 1 / precision) | python | def inside(points, polygons, short_circuit='any', precision=0.001):
"""
Test whether each of the points is within the given set of polygons.
Parameters
----------
points : array-like[N][2] or list of array-like[N][2]
Coordinates of the points to be tested or groups of points to be
tested together.
polygons : polygon or array-like
Polygons to be tested against. Must be a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
vertices of a polygon.
short_circuit : {'any', 'all'}
If `points` is a list of point groups, testing within each group
will be short-circuited if any of the points in the group is
inside ('any') or outside ('all') the polygons. If `points` is
simply a list of points, this parameter has no effect.
precision : float
Desired precision for rounding vertice coordinates.
Returns
-------
out : tuple
Tuple of booleans indicating if each of the points or point
groups is inside the set of polygons.
"""
poly = []
if isinstance(polygons, PolygonSet):
poly.extend(polygons.polygons)
elif isinstance(polygons, CellReference) or isinstance(
polygons, CellArray):
poly.extend(polygons.get_polygons())
else:
for obj in polygons:
if isinstance(obj, PolygonSet):
poly.extend(obj.polygons)
elif isinstance(obj, CellReference) or isinstance(obj, CellArray):
poly.extend(obj.get_polygons())
else:
poly.append(obj)
if hasattr(points[0][0], '__iter__'):
pts = points
sc = 1 if short_circuit == 'any' else -1
else:
pts = (points, )
sc = 0
return clipper.inside(pts, poly, sc, 1 / precision) | [
"def",
"inside",
"(",
"points",
",",
"polygons",
",",
"short_circuit",
"=",
"'any'",
",",
"precision",
"=",
"0.001",
")",
":",
"poly",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"polygons",
",",
"PolygonSet",
")",
":",
"poly",
".",
"extend",
"(",
"polygon... | Test whether each of the points is within the given set of polygons.
Parameters
----------
points : array-like[N][2] or list of array-like[N][2]
Coordinates of the points to be tested or groups of points to be
tested together.
polygons : polygon or array-like
Polygons to be tested against. Must be a ``PolygonSet``,
``CellReference``, ``CellArray``, or an array. The array may
contain any of the previous objects or an array-like[N][2] of
vertices of a polygon.
short_circuit : {'any', 'all'}
If `points` is a list of point groups, testing within each group
will be short-circuited if any of the points in the group is
inside ('any') or outside ('all') the polygons. If `points` is
simply a list of points, this parameter has no effect.
precision : float
Desired precision for rounding vertice coordinates.
Returns
-------
out : tuple
Tuple of booleans indicating if each of the points or point
groups is inside the set of polygons. | [
"Test",
"whether",
"each",
"of",
"the",
"points",
"is",
"within",
"the",
"given",
"set",
"of",
"polygons",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L4047-L4095 | train | 205,992 |
heitzmann/gdspy | gdspy/__init__.py | copy | def copy(obj, dx, dy):
"""
Creates a copy of ``obj`` and translates the new object to a new
location.
Parameters
----------
obj : ``obj``
any translatable geometery object.
dx : float
distance to move in the x-direction
dy : float
distance to move in the y-direction
Returns
-------
out : ``obj``
Translated copy of original ``obj``
Examples
--------
>>> rectangle = gdspy.Rectangle((0, 0), (10, 20))
>>> rectangle2 = gdspy.copy(rectangle, 2,0)
>>> myCell.add(rectangle)
>>> myCell.add(rectangle2)
"""
newObj = libCopy.deepcopy(obj)
newObj.translate(dx, dy)
return newObj | python | def copy(obj, dx, dy):
"""
Creates a copy of ``obj`` and translates the new object to a new
location.
Parameters
----------
obj : ``obj``
any translatable geometery object.
dx : float
distance to move in the x-direction
dy : float
distance to move in the y-direction
Returns
-------
out : ``obj``
Translated copy of original ``obj``
Examples
--------
>>> rectangle = gdspy.Rectangle((0, 0), (10, 20))
>>> rectangle2 = gdspy.copy(rectangle, 2,0)
>>> myCell.add(rectangle)
>>> myCell.add(rectangle2)
"""
newObj = libCopy.deepcopy(obj)
newObj.translate(dx, dy)
return newObj | [
"def",
"copy",
"(",
"obj",
",",
"dx",
",",
"dy",
")",
":",
"newObj",
"=",
"libCopy",
".",
"deepcopy",
"(",
"obj",
")",
"newObj",
".",
"translate",
"(",
"dx",
",",
"dy",
")",
"return",
"newObj"
] | Creates a copy of ``obj`` and translates the new object to a new
location.
Parameters
----------
obj : ``obj``
any translatable geometery object.
dx : float
distance to move in the x-direction
dy : float
distance to move in the y-direction
Returns
-------
out : ``obj``
Translated copy of original ``obj``
Examples
--------
>>> rectangle = gdspy.Rectangle((0, 0), (10, 20))
>>> rectangle2 = gdspy.copy(rectangle, 2,0)
>>> myCell.add(rectangle)
>>> myCell.add(rectangle2) | [
"Creates",
"a",
"copy",
"of",
"obj",
"and",
"translates",
"the",
"new",
"object",
"to",
"a",
"new",
"location",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L4098-L4128 | train | 205,993 |
heitzmann/gdspy | gdspy/__init__.py | write_gds | def write_gds(outfile,
cells=None,
name='library',
unit=1.0e-6,
precision=1.0e-9):
"""
Write the current GDSII library to a file.
The dimensions actually written on the GDSII file will be the
dimensions of the objects created times the ratio
``unit/precision``. For example, if a circle with radius 1.5 is
created and we set ``unit=1.0e-6`` (1 um) and ``precision=1.0e-9``
(1 nm), the radius of the circle will be 1.5 um and the GDSII file
will contain the dimension 1500 nm.
Parameters
----------
outfile : file or string
The file (or path) where the GDSII stream will be written. It
must be opened for writing operations in binary format.
cells : array-like
The list of cells or cell names to be included in the library.
If ``None``, all cells are used.
name : string
Name of the GDSII library.
unit : number
Unit size for the objects in the library (in *meters*).
precision : number
Precision for the dimensions of the objects in the library (in
*meters*).
"""
current_library.name = name
current_library.unit = unit
current_library.precision = precision
current_library.write_gds(outfile, cells) | python | def write_gds(outfile,
cells=None,
name='library',
unit=1.0e-6,
precision=1.0e-9):
"""
Write the current GDSII library to a file.
The dimensions actually written on the GDSII file will be the
dimensions of the objects created times the ratio
``unit/precision``. For example, if a circle with radius 1.5 is
created and we set ``unit=1.0e-6`` (1 um) and ``precision=1.0e-9``
(1 nm), the radius of the circle will be 1.5 um and the GDSII file
will contain the dimension 1500 nm.
Parameters
----------
outfile : file or string
The file (or path) where the GDSII stream will be written. It
must be opened for writing operations in binary format.
cells : array-like
The list of cells or cell names to be included in the library.
If ``None``, all cells are used.
name : string
Name of the GDSII library.
unit : number
Unit size for the objects in the library (in *meters*).
precision : number
Precision for the dimensions of the objects in the library (in
*meters*).
"""
current_library.name = name
current_library.unit = unit
current_library.precision = precision
current_library.write_gds(outfile, cells) | [
"def",
"write_gds",
"(",
"outfile",
",",
"cells",
"=",
"None",
",",
"name",
"=",
"'library'",
",",
"unit",
"=",
"1.0e-6",
",",
"precision",
"=",
"1.0e-9",
")",
":",
"current_library",
".",
"name",
"=",
"name",
"current_library",
".",
"unit",
"=",
"unit",... | Write the current GDSII library to a file.
The dimensions actually written on the GDSII file will be the
dimensions of the objects created times the ratio
``unit/precision``. For example, if a circle with radius 1.5 is
created and we set ``unit=1.0e-6`` (1 um) and ``precision=1.0e-9``
(1 nm), the radius of the circle will be 1.5 um and the GDSII file
will contain the dimension 1500 nm.
Parameters
----------
outfile : file or string
The file (or path) where the GDSII stream will be written. It
must be opened for writing operations in binary format.
cells : array-like
The list of cells or cell names to be included in the library.
If ``None``, all cells are used.
name : string
Name of the GDSII library.
unit : number
Unit size for the objects in the library (in *meters*).
precision : number
Precision for the dimensions of the objects in the library (in
*meters*). | [
"Write",
"the",
"current",
"GDSII",
"library",
"to",
"a",
"file",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L4131-L4165 | train | 205,994 |
heitzmann/gdspy | gdspy/__init__.py | gdsii_hash | def gdsii_hash(filename, engine=None):
"""
Calculate the a hash value for a GDSII file.
The hash is generated based only on the contents of the cells in the
GDSII library, ignoring any timestamp records present in the file
structure.
Parameters
----------
filename : string
Full path to the GDSII file.
engine : hashlib-like engine
The engine that executes the hashing algorithm. It must provide
the methods ``update`` and ``hexdigest`` as defined in the
hashlib module. If ``None``, the dafault ``hashlib.sha1()`` is
used.
Returns
-------
out : string
The hash correponding to the library contents in hex format.
"""
with open(filename, 'rb') as fin:
data = fin.read()
contents = []
start = pos = 0
while pos < len(data):
size, rec = struct.unpack('>HH', data[pos:pos + 4])
if rec == 0x0502:
start = pos + 28
elif rec == 0x0700:
contents.append(data[start:pos])
pos += size
h = hashlib.sha1() if engine is None else engine
for x in sorted(contents):
h.update(x)
return h.hexdigest() | python | def gdsii_hash(filename, engine=None):
"""
Calculate the a hash value for a GDSII file.
The hash is generated based only on the contents of the cells in the
GDSII library, ignoring any timestamp records present in the file
structure.
Parameters
----------
filename : string
Full path to the GDSII file.
engine : hashlib-like engine
The engine that executes the hashing algorithm. It must provide
the methods ``update`` and ``hexdigest`` as defined in the
hashlib module. If ``None``, the dafault ``hashlib.sha1()`` is
used.
Returns
-------
out : string
The hash correponding to the library contents in hex format.
"""
with open(filename, 'rb') as fin:
data = fin.read()
contents = []
start = pos = 0
while pos < len(data):
size, rec = struct.unpack('>HH', data[pos:pos + 4])
if rec == 0x0502:
start = pos + 28
elif rec == 0x0700:
contents.append(data[start:pos])
pos += size
h = hashlib.sha1() if engine is None else engine
for x in sorted(contents):
h.update(x)
return h.hexdigest() | [
"def",
"gdsii_hash",
"(",
"filename",
",",
"engine",
"=",
"None",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fin",
":",
"data",
"=",
"fin",
".",
"read",
"(",
")",
"contents",
"=",
"[",
"]",
"start",
"=",
"pos",
"=",
"0",
... | Calculate the a hash value for a GDSII file.
The hash is generated based only on the contents of the cells in the
GDSII library, ignoring any timestamp records present in the file
structure.
Parameters
----------
filename : string
Full path to the GDSII file.
engine : hashlib-like engine
The engine that executes the hashing algorithm. It must provide
the methods ``update`` and ``hexdigest`` as defined in the
hashlib module. If ``None``, the dafault ``hashlib.sha1()`` is
used.
Returns
-------
out : string
The hash correponding to the library contents in hex format. | [
"Calculate",
"the",
"a",
"hash",
"value",
"for",
"a",
"GDSII",
"file",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L4168-L4205 | train | 205,995 |
heitzmann/gdspy | gdspy/__init__.py | PolygonSet.get_bounding_box | def get_bounding_box(self):
"""
Returns the bounding box of the polygons.
Returns
-------
out : Numpy array[2,2] or ``None``
Bounding box of this polygon in the form [[x_min, y_min],
[x_max, y_max]], or ``None`` if the polygon is empty.
"""
if len(self.polygons) == 0:
return None
return numpy.array(((min(pts[:, 0].min() for pts in self.polygons),
min(pts[:, 1].min() for pts in self.polygons)),
(max(pts[:, 0].max() for pts in self.polygons),
max(pts[:, 1].max() for pts in self.polygons)))) | python | def get_bounding_box(self):
"""
Returns the bounding box of the polygons.
Returns
-------
out : Numpy array[2,2] or ``None``
Bounding box of this polygon in the form [[x_min, y_min],
[x_max, y_max]], or ``None`` if the polygon is empty.
"""
if len(self.polygons) == 0:
return None
return numpy.array(((min(pts[:, 0].min() for pts in self.polygons),
min(pts[:, 1].min() for pts in self.polygons)),
(max(pts[:, 0].max() for pts in self.polygons),
max(pts[:, 1].max() for pts in self.polygons)))) | [
"def",
"get_bounding_box",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"polygons",
")",
"==",
"0",
":",
"return",
"None",
"return",
"numpy",
".",
"array",
"(",
"(",
"(",
"min",
"(",
"pts",
"[",
":",
",",
"0",
"]",
".",
"min",
"(",
")"... | Returns the bounding box of the polygons.
Returns
-------
out : Numpy array[2,2] or ``None``
Bounding box of this polygon in the form [[x_min, y_min],
[x_max, y_max]], or ``None`` if the polygon is empty. | [
"Returns",
"the",
"bounding",
"box",
"of",
"the",
"polygons",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L180-L195 | train | 205,996 |
heitzmann/gdspy | gdspy/__init__.py | PolygonSet.scale | def scale(self, scalex, scaley=None, center=(0, 0)):
"""
Scale this object.
Parameters
----------
scalex : number
Scaling factor along the first axis.
scaley : number or ``None``
Scaling factor along the second axis. If ``None``, same as
``scalex``.
center : array-like[2]
Center point for the scaling operation.
Returns
-------
out : ``PolygonSet``
This object.
"""
c0 = numpy.array(center)
s = scalex if scaley is None else numpy.array((scalex, scaley))
self.polygons = [(points - c0) * s + c0 for points in self.polygons]
return self | python | def scale(self, scalex, scaley=None, center=(0, 0)):
"""
Scale this object.
Parameters
----------
scalex : number
Scaling factor along the first axis.
scaley : number or ``None``
Scaling factor along the second axis. If ``None``, same as
``scalex``.
center : array-like[2]
Center point for the scaling operation.
Returns
-------
out : ``PolygonSet``
This object.
"""
c0 = numpy.array(center)
s = scalex if scaley is None else numpy.array((scalex, scaley))
self.polygons = [(points - c0) * s + c0 for points in self.polygons]
return self | [
"def",
"scale",
"(",
"self",
",",
"scalex",
",",
"scaley",
"=",
"None",
",",
"center",
"=",
"(",
"0",
",",
"0",
")",
")",
":",
"c0",
"=",
"numpy",
".",
"array",
"(",
"center",
")",
"s",
"=",
"scalex",
"if",
"scaley",
"is",
"None",
"else",
"nump... | Scale this object.
Parameters
----------
scalex : number
Scaling factor along the first axis.
scaley : number or ``None``
Scaling factor along the second axis. If ``None``, same as
``scalex``.
center : array-like[2]
Center point for the scaling operation.
Returns
-------
out : ``PolygonSet``
This object. | [
"Scale",
"this",
"object",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L221-L243 | train | 205,997 |
heitzmann/gdspy | gdspy/__init__.py | PolygonSet.to_gds | def to_gds(self, multiplier):
"""
Convert this object to a series of GDSII elements.
Parameters
----------
multiplier : number
A number that multiplies all dimensions written in the GDSII
elements.
Returns
-------
out : string
The GDSII binary string that represents this object.
"""
data = []
for ii in range(len(self.polygons)):
if len(self.polygons[ii]) > 4094:
raise ValueError("[GDSPY] Polygons with more than 4094 are "
"not supported by the GDSII format.")
data.append(
struct.pack('>10h', 4, 0x0800, 6, 0x0D02, self.layers[ii], 6,
0x0E02, self.datatypes[ii],
12 + 8 * len(self.polygons[ii]), 0x1003))
data.extend(
struct.pack('>2l', int(round(point[0] * multiplier)),
int(round(point[1] * multiplier)))
for point in self.polygons[ii])
data.append(
struct.pack('>2l2h',
int(round(self.polygons[ii][0][0] * multiplier)),
int(round(self.polygons[ii][0][1] * multiplier)),
4, 0x1100))
return b''.join(data) | python | def to_gds(self, multiplier):
"""
Convert this object to a series of GDSII elements.
Parameters
----------
multiplier : number
A number that multiplies all dimensions written in the GDSII
elements.
Returns
-------
out : string
The GDSII binary string that represents this object.
"""
data = []
for ii in range(len(self.polygons)):
if len(self.polygons[ii]) > 4094:
raise ValueError("[GDSPY] Polygons with more than 4094 are "
"not supported by the GDSII format.")
data.append(
struct.pack('>10h', 4, 0x0800, 6, 0x0D02, self.layers[ii], 6,
0x0E02, self.datatypes[ii],
12 + 8 * len(self.polygons[ii]), 0x1003))
data.extend(
struct.pack('>2l', int(round(point[0] * multiplier)),
int(round(point[1] * multiplier)))
for point in self.polygons[ii])
data.append(
struct.pack('>2l2h',
int(round(self.polygons[ii][0][0] * multiplier)),
int(round(self.polygons[ii][0][1] * multiplier)),
4, 0x1100))
return b''.join(data) | [
"def",
"to_gds",
"(",
"self",
",",
"multiplier",
")",
":",
"data",
"=",
"[",
"]",
"for",
"ii",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"polygons",
")",
")",
":",
"if",
"len",
"(",
"self",
".",
"polygons",
"[",
"ii",
"]",
")",
">",
"4094",
... | Convert this object to a series of GDSII elements.
Parameters
----------
multiplier : number
A number that multiplies all dimensions written in the GDSII
elements.
Returns
-------
out : string
The GDSII binary string that represents this object. | [
"Convert",
"this",
"object",
"to",
"a",
"series",
"of",
"GDSII",
"elements",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L245-L278 | train | 205,998 |
heitzmann/gdspy | gdspy/__init__.py | PolygonSet.fracture | def fracture(self, max_points=199, precision=1e-3):
"""
Slice these polygons in the horizontal and vertical directions
so that each resulting piece has at most ``max_points``. This
operation occurs in place.
Parameters
----------
max_points : integer
Maximal number of points in each resulting polygon (must be
greater than 4).
precision : float
Desired precision for rounding vertice coordinates.
Returns
-------
out : ``PolygonSet``
This object.
"""
if max_points > 4:
ii = 0
while ii < len(self.polygons):
if len(self.polygons[ii]) > max_points:
pts0 = sorted(self.polygons[ii][:, 0])
pts1 = sorted(self.polygons[ii][:, 1])
ncuts = len(pts0) // max_points
if pts0[-1] - pts0[0] > pts1[-1] - pts1[0]:
# Vertical cuts
cuts = [
pts0[int(i * len(pts0) / (ncuts + 1.0) + 0.5)]
for i in range(1, ncuts + 1)
]
chopped = clipper._chop(self.polygons[ii], cuts, 0,
1 / precision)
else:
# Horizontal cuts
cuts = [
pts1[int(i * len(pts1) / (ncuts + 1.0) + 0.5)]
for i in range(1, ncuts + 1)
]
chopped = clipper._chop(self.polygons[ii], cuts, 1,
1 / precision)
self.polygons.pop(ii)
layer = self.layers.pop(ii)
datatype = self.datatypes.pop(ii)
self.polygons.extend(
numpy.array(x)
for x in itertools.chain.from_iterable(chopped))
npols = sum(len(c) for c in chopped)
self.layers.extend(layer for _ in range(npols))
self.datatypes.extend(datatype for _ in range(npols))
else:
ii += 1
return self | python | def fracture(self, max_points=199, precision=1e-3):
"""
Slice these polygons in the horizontal and vertical directions
so that each resulting piece has at most ``max_points``. This
operation occurs in place.
Parameters
----------
max_points : integer
Maximal number of points in each resulting polygon (must be
greater than 4).
precision : float
Desired precision for rounding vertice coordinates.
Returns
-------
out : ``PolygonSet``
This object.
"""
if max_points > 4:
ii = 0
while ii < len(self.polygons):
if len(self.polygons[ii]) > max_points:
pts0 = sorted(self.polygons[ii][:, 0])
pts1 = sorted(self.polygons[ii][:, 1])
ncuts = len(pts0) // max_points
if pts0[-1] - pts0[0] > pts1[-1] - pts1[0]:
# Vertical cuts
cuts = [
pts0[int(i * len(pts0) / (ncuts + 1.0) + 0.5)]
for i in range(1, ncuts + 1)
]
chopped = clipper._chop(self.polygons[ii], cuts, 0,
1 / precision)
else:
# Horizontal cuts
cuts = [
pts1[int(i * len(pts1) / (ncuts + 1.0) + 0.5)]
for i in range(1, ncuts + 1)
]
chopped = clipper._chop(self.polygons[ii], cuts, 1,
1 / precision)
self.polygons.pop(ii)
layer = self.layers.pop(ii)
datatype = self.datatypes.pop(ii)
self.polygons.extend(
numpy.array(x)
for x in itertools.chain.from_iterable(chopped))
npols = sum(len(c) for c in chopped)
self.layers.extend(layer for _ in range(npols))
self.datatypes.extend(datatype for _ in range(npols))
else:
ii += 1
return self | [
"def",
"fracture",
"(",
"self",
",",
"max_points",
"=",
"199",
",",
"precision",
"=",
"1e-3",
")",
":",
"if",
"max_points",
">",
"4",
":",
"ii",
"=",
"0",
"while",
"ii",
"<",
"len",
"(",
"self",
".",
"polygons",
")",
":",
"if",
"len",
"(",
"self"... | Slice these polygons in the horizontal and vertical directions
so that each resulting piece has at most ``max_points``. This
operation occurs in place.
Parameters
----------
max_points : integer
Maximal number of points in each resulting polygon (must be
greater than 4).
precision : float
Desired precision for rounding vertice coordinates.
Returns
-------
out : ``PolygonSet``
This object. | [
"Slice",
"these",
"polygons",
"in",
"the",
"horizontal",
"and",
"vertical",
"directions",
"so",
"that",
"each",
"resulting",
"piece",
"has",
"at",
"most",
"max_points",
".",
"This",
"operation",
"occurs",
"in",
"place",
"."
] | 2c8d1313248c544e2066d19095b7ad7158c79bc9 | https://github.com/heitzmann/gdspy/blob/2c8d1313248c544e2066d19095b7ad7158c79bc9/gdspy/__init__.py#L321-L374 | train | 205,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.