text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Applies various filtering and processing options on token.
<END_TASK>
<USER_TASK:>
Description:
def _apply_options(self, token):
"""Applies various filtering and processing options on token.
Returns:
The processed token. None if filtered.
""" |
# Apply work token filtering.
if token.is_punct and self.remove_punct:
return None
if token.is_stop and self.remove_stop_words:
return None
if token.is_digit and self.remove_digits:
return None
if token.is_oov and self.exclude_oov:
return None
if token.pos_ in self.exclude_pos_tags:
return None
if token.ent_type_ in self.exclude_entities:
return None
# Lemmatized ones are already lowered.
if self.lemmatize:
return token.lemma_
if self.lower:
return token.lower_
return token.orth_ |
<SYSTEM_TASK:>
Adds `value` to `lst` list indexed by `indices`. Will create sub lists as required.
<END_TASK>
<USER_TASK:>
Description:
def _append(lst, indices, value):
"""Adds `value` to `lst` list indexed by `indices`. Will create sub lists as required.
""" |
for i, idx in enumerate(indices):
# We need to loop because sometimes indices can increment by more than 1 due to missing tokens.
# Example: Sentence with no words after filtering words.
while len(lst) <= idx:
# Update max counts whenever a new sublist is created.
# There is no need to worry about indices beyond `i` since they will end up creating new lists as well.
lst.append([])
lst = lst[idx]
# Add token and update token max count.
lst.append(value) |
<SYSTEM_TASK:>
Updates counts based on indices. The algorithm tracks the index change at i and
<END_TASK>
<USER_TASK:>
Description:
def update(self, indices):
"""Updates counts based on indices. The algorithm tracks the index change at i and
update global counts for all indices beyond i with local counts tracked so far.
""" |
# Initialize various lists for the first time based on length of indices.
if self._prev_indices is None:
self._prev_indices = indices
# +1 to track token counts in the last index.
self._local_counts = np.full(len(indices) + 1, 1)
self._local_counts[-1] = 0
self.counts = [[] for _ in range(len(self._local_counts))]
has_reset = False
for i in range(len(indices)):
# index value changed. Push all local values beyond i to count and reset those local_counts.
# For example, if document index changed, push counts on sentences and tokens and reset their local_counts
# to indicate that we are tracking those for new document. We need to do this at all document hierarchies.
if indices[i] > self._prev_indices[i]:
self._local_counts[i] += 1
has_reset = True
for j in range(i + 1, len(self.counts)):
self.counts[j].append(self._local_counts[j])
self._local_counts[j] = 1
# If none of the aux indices changed, update token count.
if not has_reset:
self._local_counts[-1] += 1
self._prev_indices = indices[:] |
<SYSTEM_TASK:>
read text files in directory and returns them as array
<END_TASK>
<USER_TASK:>
Description:
def read_folder(directory):
"""read text files in directory and returns them as array
Args:
directory: where the text files are
Returns:
Array of text
""" |
res = []
for filename in os.listdir(directory):
with io.open(os.path.join(directory, filename), encoding="utf-8") as f:
content = f.read()
res.append(content)
return res |
<SYSTEM_TASK:>
returns array with positive and negative examples
<END_TASK>
<USER_TASK:>
Description:
def read_pos_neg_data(path, folder, limit):
"""returns array with positive and negative examples""" |
training_pos_path = os.path.join(path, folder, 'pos')
training_neg_path = os.path.join(path, folder, 'neg')
X_pos = read_folder(training_pos_path)
X_neg = read_folder(training_neg_path)
if limit is None:
X = X_pos + X_neg
else:
X = X_pos[:limit] + X_neg[:limit]
y = [1] * int(len(X) / 2) + [0] * int(len(X) / 2)
return X, y |
<SYSTEM_TASK:>
Sets the value of the graphic
<END_TASK>
<USER_TASK:>
Description:
def set_value(self, number: (float, int)):
"""
Sets the value of the graphic
:param number: the number (must be between 0 and \
'max_range' or the scale will peg the limits
:return: None
""" |
self.canvas.delete('all')
self.canvas.create_image(0, 0, image=self.image, anchor='nw')
number = number if number <= self.max_value else self.max_value
number = 0.0 if number < 0.0 else number
radius = 0.9 * self.size/2.0
angle_in_radians = (2.0 * cmath.pi / 3.0) \
+ number / self.max_value * (5.0 * cmath.pi / 3.0)
center = cmath.rect(0, 0)
outer = cmath.rect(radius, angle_in_radians)
if self.needle_thickness == 0:
line_width = int(5 * self.size / 200)
line_width = 1 if line_width < 1 else line_width
else:
line_width = self.needle_thickness
self.canvas.create_line(
*self.to_absolute(center.real, center.imag),
*self.to_absolute(outer.real, outer.imag),
width=line_width,
fill=self.needle_color
)
self.readout['text'] = '{}{}'.format(number, self.unit) |
<SYSTEM_TASK:>
Draws the background of the dial
<END_TASK>
<USER_TASK:>
Description:
def _draw_background(self, divisions=10):
"""
Draws the background of the dial
:param divisions: the number of divisions
between 'ticks' shown on the dial
:return: None
""" |
self.canvas.create_arc(2, 2, self.size-2, self.size-2,
style=tk.PIESLICE, start=-60, extent=30,
fill='red')
self.canvas.create_arc(2, 2, self.size-2, self.size-2,
style=tk.PIESLICE, start=-30, extent=60,
fill='yellow')
self.canvas.create_arc(2, 2, self.size-2, self.size-2,
style=tk.PIESLICE, start=30, extent=210,
fill='green')
# find the distance between the center and the inner tick radius
inner_tick_radius = int(self.size * 0.4)
outer_tick_radius = int(self.size * 0.5)
for tick in range(divisions):
angle_in_radians = (2.0 * cmath.pi / 3.0) \
+ tick/divisions * (5.0 * cmath.pi / 3.0)
inner_point = cmath.rect(inner_tick_radius, angle_in_radians)
outer_point = cmath.rect(outer_tick_radius, angle_in_radians)
self.canvas.create_line(
*self.to_absolute(inner_point.real, inner_point.imag),
*self.to_absolute(outer_point.real, outer_point.imag),
width=1
) |
<SYSTEM_TASK:>
Removes all existing series and re-draws the axes.
<END_TASK>
<USER_TASK:>
Description:
def draw_axes(self):
"""
Removes all existing series and re-draws the axes.
:return: None
""" |
self.canvas.delete('all')
rect = 50, 50, self.w - 50, self.h - 50
self.canvas.create_rectangle(rect, outline="black")
for x in self.frange(0, self.x_max - self.x_min + 1, self.x_tick):
value = Decimal(self.x_min + x)
if self.x_min <= value <= self.x_max:
x_step = (self.px_x * x) / self.x_tick
coord = 50 + x_step, self.h - 50, 50 + x_step, self.h - 45
self.canvas.create_line(coord, fill="black")
coord = 50 + x_step, self.h - 40
label = round(Decimal(self.x_min + x), 1)
self.canvas.create_text(coord, fill="black", text=label)
for y in self.frange(0, self.y_max - self.y_min + 1, self.y_tick):
value = Decimal(self.y_max - y)
if self.y_min <= value <= self.y_max:
y_step = (self.px_y * y) / self.y_tick
coord = 45, 50 + y_step, 50, 50 + y_step
self.canvas.create_line(coord, fill="black")
coord = 35, 50 + y_step
label = round(value, 1)
self.canvas.create_text(coord, fill="black", text=label) |
<SYSTEM_TASK:>
Places a single point on the grid
<END_TASK>
<USER_TASK:>
Description:
def plot_point(self, x, y, visible=True, color='black', size=5):
"""
Places a single point on the grid
:param x: the x coordinate
:param y: the y coordinate
:param visible: True if the individual point should be visible
:param color: the color of the point
:param size: the point size in pixels
:return: The absolute coordinates as a tuple
""" |
xp = (self.px_x * (x - self.x_min)) / self.x_tick
yp = (self.px_y * (self.y_max - y)) / self.y_tick
coord = 50 + xp, 50 + yp
if visible:
# divide down to an appropriate size
size = int(size/2) if int(size/2) > 1 else 1
x, y = coord
self.canvas.create_oval(
x-size, y-size,
x+size, y+size,
fill=color
)
return coord |
<SYSTEM_TASK:>
Plot a line of points
<END_TASK>
<USER_TASK:>
Description:
def plot_line(self, points: list, color='black', point_visibility=False):
"""
Plot a line of points
:param points: a list of tuples, each tuple containing an (x, y) point
:param color: the color of the line
:param point_visibility: True if the points \
should be individually visible
:return: None
""" |
last_point = ()
for point in points:
this_point = self.plot_point(point[0], point[1],
color=color, visible=point_visibility)
if last_point:
self.canvas.create_line(last_point + this_point, fill=color)
last_point = this_point |
<SYSTEM_TASK:>
Works like range for doubles
<END_TASK>
<USER_TASK:>
Description:
def frange(start, stop, step, digits_to_round=3):
"""
Works like range for doubles
:param start: starting value
:param stop: ending value
:param step: the increment_value
:param digits_to_round: the digits to which to round \
(makes floating-point numbers much easier to work with)
:return: generator
""" |
while start < stop:
yield round(start, digits_to_round)
start += step |
<SYSTEM_TASK:>
Load a new image.
<END_TASK>
<USER_TASK:>
Description:
def _load_new(self, img_data: str):
"""
Load a new image.
:param img_data: the image data as a base64 string
:return: None
""" |
self._image = tk.PhotoImage(data=img_data)
self._image = self._image.subsample(int(200 / self._size),
int(200 / self._size))
self._canvas.delete('all')
self._canvas.create_image(0, 0, image=self._image, anchor='nw')
if self._user_click_callback is not None:
self._user_click_callback(self._on) |
<SYSTEM_TASK:>
Change the LED to grey.
<END_TASK>
<USER_TASK:>
Description:
def to_grey(self, on: bool=False):
"""
Change the LED to grey.
:param on: Unused, here for API consistency with the other states
:return: None
""" |
self._on = False
self._load_new(led_grey) |
<SYSTEM_TASK:>
Forgets the current layout and redraws with the most recent information
<END_TASK>
<USER_TASK:>
Description:
def _redraw(self):
"""
Forgets the current layout and redraws with the most recent information
:return: None
""" |
for row in self._rows:
for widget in row:
widget.grid_forget()
offset = 0 if not self.headers else 1
for i, row in enumerate(self._rows):
for j, widget in enumerate(row):
widget.grid(row=i+offset, column=j) |
<SYSTEM_TASK:>
Removes a specified row of data
<END_TASK>
<USER_TASK:>
Description:
def remove_row(self, row_number: int=-1):
"""
Removes a specified row of data
:param row_number: the row to remove (defaults to the last row)
:return: None
""" |
if len(self._rows) == 0:
return
row = self._rows.pop(row_number)
for widget in row:
widget.destroy() |
<SYSTEM_TASK:>
Add a row of data to the current widget
<END_TASK>
<USER_TASK:>
Description:
def add_row(self, data: list):
"""
Add a row of data to the current widget
:param data: a row of data
:return: None
""" |
# validation
if self.headers:
if len(self.headers) != len(data):
raise ValueError
if len(data) != self.num_of_columns:
raise ValueError
offset = 0 if not self.headers else 1
row = list()
for i, element in enumerate(data):
label = ttk.Label(self, text=str(element), relief=tk.GROOVE,
padding=self.padding)
label.grid(row=len(self._rows) + offset, column=i, sticky='E,W')
row.append(label)
self._rows.append(row) |
<SYSTEM_TASK:>
Read the data contained in all entries as a list of
<END_TASK>
<USER_TASK:>
Description:
def _read_as_dict(self):
"""
Read the data contained in all entries as a list of
dictionaries with the headers as the dictionary keys
:return: list of dicts containing all tabular data
""" |
data = list()
for row in self._rows:
row_data = OrderedDict()
for i, header in enumerate(self.headers):
row_data[header.cget('text')] = row[i].get()
data.append(row_data)
return data |
<SYSTEM_TASK:>
Read the data contained in all entries as a list of
<END_TASK>
<USER_TASK:>
Description:
def _read_as_table(self):
"""
Read the data contained in all entries as a list of
lists containing all of the data
:return: list of dicts containing all tabular data
""" |
rows = list()
for row in self._rows:
rows.append([row[i].get() for i in range(self.num_of_columns)])
return rows |
<SYSTEM_TASK:>
Add a single row and re-draw as necessary
<END_TASK>
<USER_TASK:>
Description:
def add_row(self, key: str, default: str=None,
unit_label: str=None, enable: bool=None):
"""
Add a single row and re-draw as necessary
:param key: the name and dict accessor
:param default: the default value
:param unit_label: the label that should be \
applied at the right of the entry
:param enable: the 'enabled' state (defaults to True)
:return:
""" |
self.keys.append(ttk.Label(self, text=key))
self.defaults.append(default)
self.unit_labels.append(
ttk.Label(self, text=unit_label if unit_label else '')
)
self.enables.append(enable)
self.values.append(ttk.Entry(self))
row_offset = 1 if self.title is not None else 0
for i in range(len(self.keys)):
self.keys[i].grid_forget()
self.keys[i].grid(row=row_offset, column=0, sticky='e')
self.values[i].grid(row=row_offset, column=1)
if self.unit_labels[i]:
self.unit_labels[i].grid(row=row_offset, column=3, sticky='w')
if self.defaults[i]:
self.values[i].config(state=tk.NORMAL)
self.values[i].delete(0, tk.END)
self.values[i].insert(0, self.defaults[i])
if self.enables[i] in [True, None]:
self.values[i].config(state=tk.NORMAL)
elif self.enables[i] is False:
self.values[i].config(state=tk.DISABLED)
row_offset += 1
# strip <Return> and <Tab> bindings, add callbacks to all entries
self.values[i].unbind('<Return>')
self.values[i].unbind('<Tab>')
if self.callback is not None:
def callback(event):
self.callback()
self.values[i].bind('<Return>', callback)
self.values[i].bind('<Tab>', callback) |
<SYSTEM_TASK:>
Retrieve the GUI elements for program use.
<END_TASK>
<USER_TASK:>
Description:
def get(self):
"""
Retrieve the GUI elements for program use.
:return: a dictionary containing all \
of the data from the key/value entries
""" |
data = dict()
for label, entry in zip(self.keys, self.values):
data[label.cget('text')] = entry.get()
return data |
<SYSTEM_TASK:>
Clear the contents of the entry field and
<END_TASK>
<USER_TASK:>
Description:
def add(self, string: (str, list)):
"""
Clear the contents of the entry field and
insert the contents of string.
:param string: an str containing the text to display
:return:
""" |
if len(self._entries) == 1:
self._entries[0].delete(0, 'end')
self._entries[0].insert(0, string)
else:
if len(string) != len(self._entries):
raise ValueError('the "string" list must be '
'equal to the number of entries')
for i, e in enumerate(self._entries):
self._entries[i].delete(0, 'end')
self._entries[i].insert(0, string[i]) |
<SYSTEM_TASK:>
Set the current value
<END_TASK>
<USER_TASK:>
Description:
def set(self, value: int):
"""
Set the current value
:param value:
:return: None
""" |
max_value = int(''.join(['1' for _ in range(self._bit_width)]), 2)
if value > max_value:
raise ValueError('the value {} is larger than '
'the maximum value {}'.format(value, max_value))
self._value = value
self._text_update() |
<SYSTEM_TASK:>
Returns the bit value at position
<END_TASK>
<USER_TASK:>
Description:
def get_bit(self, position: int):
"""
Returns the bit value at position
:param position: integer between 0 and <width>, inclusive
:return: the value at position as a integer
""" |
if position > (self._bit_width - 1):
raise ValueError('position greater than the bit width')
if self._value & (1 << position):
return 1
else:
return 0 |
<SYSTEM_TASK:>
Toggles the value at position
<END_TASK>
<USER_TASK:>
Description:
def toggle_bit(self, position: int):
"""
Toggles the value at position
:param position: integer between 0 and 7, inclusive
:return: None
""" |
if position > (self._bit_width - 1):
raise ValueError('position greater than the bit width')
self._value ^= (1 << position)
self._text_update() |
<SYSTEM_TASK:>
Sets the value at position
<END_TASK>
<USER_TASK:>
Description:
def set_bit(self, position: int):
"""
Sets the value at position
:param position: integer between 0 and 7, inclusive
:return: None
""" |
if position > (self._bit_width - 1):
raise ValueError('position greater than the bit width')
self._value |= (1 << position)
self._text_update() |
<SYSTEM_TASK:>
Clears the value at position
<END_TASK>
<USER_TASK:>
Description:
def clear_bit(self, position: int):
"""
Clears the value at position
:param position: integer between 0 and 7, inclusive
:return: None
""" |
if position > (self._bit_width - 1):
raise ValueError('position greater than the bit width')
self._value &= ~(1 << position)
self._text_update() |
<SYSTEM_TASK:>
Register model in the admin, ignoring any previously registered models.
<END_TASK>
<USER_TASK:>
Description:
def _register_admin(admin_site, model, admin_class):
""" Register model in the admin, ignoring any previously registered models.
Alternatively it could be used in the future to replace a previously
registered model.
""" |
try:
admin_site.register(model, admin_class)
except admin.sites.AlreadyRegistered:
pass |
<SYSTEM_TASK:>
Monkey patch the inline onto the given admin_class instance.
<END_TASK>
<USER_TASK:>
Description:
def _monkey_inline(model, admin_class_instance, metadata_class, inline_class, admin_site):
""" Monkey patch the inline onto the given admin_class instance. """ |
if model in metadata_class._meta.seo_models:
# *Not* adding to the class attribute "inlines", as this will affect
# all instances from this class. Explicitly adding to instance attribute.
admin_class_instance.__dict__['inlines'] = admin_class_instance.inlines + [inline_class]
# Because we've missed the registration, we need to perform actions
# that were done then (on admin class instantiation)
inline_instance = inline_class(admin_class_instance.model, admin_site)
admin_class_instance.inline_instances.append(inline_instance) |
<SYSTEM_TASK:>
Decorator for register function that adds an appropriate inline.
<END_TASK>
<USER_TASK:>
Description:
def _with_inline(func, admin_site, metadata_class, inline_class):
""" Decorator for register function that adds an appropriate inline.""" |
def register(model_or_iterable, admin_class=None, **options):
# Call the (bound) function we were given.
# We have to assume it will be bound to admin_site
func(model_or_iterable, admin_class, **options)
_monkey_inline(model_or_iterable, admin_site._registry[model_or_iterable], metadata_class, inline_class, admin_site)
return register |
<SYSTEM_TASK:>
This is a questionable function that automatically adds our metadata
<END_TASK>
<USER_TASK:>
Description:
def auto_register_inlines(admin_site, metadata_class):
""" This is a questionable function that automatically adds our metadata
inline to all relevant models in the site.
""" |
inline_class = get_inline(metadata_class)
for model, admin_class_instance in admin_site._registry.items():
_monkey_inline(model, admin_class_instance, metadata_class, inline_class, admin_site)
# Monkey patch the register method to automatically add an inline for this site.
# _with_inline() is a decorator that wraps the register function with the same injection code
# used above (_monkey_inline).
admin_site.register = _with_inline(admin_site.register, admin_site, metadata_class, inline_class) |
<SYSTEM_TASK:>
Cache instances, allowing generators to be used and reused.
<END_TASK>
<USER_TASK:>
Description:
def __instances(self):
""" Cache instances, allowing generators to be used and reused.
This fills a cache as the generator gets emptied, eventually
reading exclusively from the cache.
""" |
for instance in self.__instances_cache:
yield instance
for instance in self.__instances_original:
self.__instances_cache.append(instance)
yield instance |
<SYSTEM_TASK:>
Returns an appropriate value for the given name.
<END_TASK>
<USER_TASK:>
Description:
def _resolve_value(self, name):
""" Returns an appropriate value for the given name.
This simply asks each of the instances for a value.
""" |
for instance in self.__instances():
value = instance._resolve_value(name)
if value:
return value
# Otherwise, return an appropriate default value (populate_from)
# TODO: This is duplicated in meta_models. Move this to a common home.
if name in self.__metadata._meta.elements:
populate_from = self.__metadata._meta.elements[name].populate_from
if callable(populate_from):
return populate_from(None)
elif isinstance(populate_from, Literal):
return populate_from.value
elif populate_from is not NotSet:
return self._resolve_value(populate_from) |
<SYSTEM_TASK:>
Return an object to conveniently access the appropriate values.
<END_TASK>
<USER_TASK:>
Description:
def _get_formatted_data(cls, path, context=None, site=None, language=None):
""" Return an object to conveniently access the appropriate values. """ |
return FormattedMetadata(cls(), cls._get_instances(path, context, site, language), path, site, language) |
<SYSTEM_TASK:>
Validates the application of this backend to a given metadata
<END_TASK>
<USER_TASK:>
Description:
def validate(options):
""" Validates the application of this backend to a given metadata
""" |
try:
if options.backends.index('modelinstance') > options.backends.index('model'):
raise Exception("Metadata backend 'modelinstance' must come before 'model' backend")
except ValueError:
raise Exception("Metadata backend 'modelinstance' must be installed in order to use 'model' backend") |
<SYSTEM_TASK:>
Takes elements from the metadata class and creates a base model for all backend models .
<END_TASK>
<USER_TASK:>
Description:
def _register_elements(self, elements):
""" Takes elements from the metadata class and creates a base model for all backend models .
""" |
self.elements = elements
for key, obj in elements.items():
obj.contribute_to_class(self.metadata, key)
# Create the common Django fields
fields = {}
for key, obj in elements.items():
if obj.editable:
field = obj.get_field()
if not field.help_text:
if key in self.bulk_help_text:
field.help_text = self.bulk_help_text[key]
fields[key] = field
# 0. Abstract base model with common fields
base_meta = type('Meta', (), self.original_meta)
class BaseMeta(base_meta):
abstract = True
app_label = 'seo'
fields['Meta'] = BaseMeta
# Do we need this?
fields['__module__'] = __name__ #attrs['__module__']
self.MetadataBaseModel = type('%sBase' % self.name, (models.Model,), fields) |
<SYSTEM_TASK:>
Builds a subclass model for the given backend
<END_TASK>
<USER_TASK:>
Description:
def _add_backend(self, backend):
""" Builds a subclass model for the given backend """ |
md_type = backend.verbose_name
base = backend().get_model(self)
# TODO: Rename this field
new_md_attrs = {'_metadata': self.metadata, '__module__': __name__ }
new_md_meta = {}
new_md_meta['verbose_name'] = '%s (%s)' % (self.verbose_name, md_type)
new_md_meta['verbose_name_plural'] = '%s (%s)' % (self.verbose_name_plural, md_type)
new_md_meta['unique_together'] = base._meta.unique_together
new_md_attrs['Meta'] = type("Meta", (), new_md_meta)
new_md_attrs['_metadata_type'] = backend.name
model = type("%s%s"%(self.name,"".join(md_type.split())), (base, self.MetadataBaseModel), new_md_attrs.copy())
self.models[backend.name] = model
# This is a little dangerous, but because we set __module__ to __name__, the model needs tobe accessible here
globals()[model.__name__] = model |
<SYSTEM_TASK:>
Create metadata instances for all models in seo_models if empty.
<END_TASK>
<USER_TASK:>
Description:
def populate_all_metadata():
""" Create metadata instances for all models in seo_models if empty.
Once you have created a single metadata instance, this will not run.
This is because it is a potentially slow operation that need only be
done once. If you want to ensure that everything is populated, run the
populate_metadata management command.
""" |
for Metadata in registry.values():
InstanceMetadata = Metadata._meta.get_model('modelinstance')
if InstanceMetadata is not None:
for model in Metadata._meta.seo_models:
populate_metadata(model, InstanceMetadata) |
<SYSTEM_TASK:>
Populate this list with all views that take no arguments.
<END_TASK>
<USER_TASK:>
Description:
def populate(self):
""" Populate this list with all views that take no arguments.
""" |
from django.conf import settings
from django.core import urlresolvers
self.append(("", ""))
urlconf = settings.ROOT_URLCONF
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
# Collect base level views
for key, value in resolver.reverse_dict.items():
if isinstance(key, basestring):
args = value[0][0][1]
url = "/" + value[0][0][0]
self.append((key, " ".join(key.split("_"))))
# Collect namespaces (TODO: merge these two sections into one)
for namespace, url in resolver.namespace_dict.items():
for key, value in url[1].reverse_dict.items():
if isinstance(key, basestring):
args = value[0][0][1]
full_key = '%s:%s' % (namespace, key)
self.append((full_key, "%s: %s" % (namespace, " ".join(key.split("_")))))
self.sort() |
<SYSTEM_TASK:>
Creates a generator by slicing ``data`` into chunks of ``block_size``.
<END_TASK>
<USER_TASK:>
Description:
def block_splitter(data, block_size):
"""
Creates a generator by slicing ``data`` into chunks of ``block_size``.
>>> data = range(10)
>>> list(block_splitter(data, 2))
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
If ``data`` cannot be evenly divided by ``block_size``, the last block will
simply be the remainder of the data. Example:
>>> data = range(10)
>>> list(block_splitter(data, 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
If the ``block_size`` is greater than the total length of ``data``, a
single block will be generated:
>>> data = range(3)
>>> list(block_splitter(data, 4))
[[0, 1, 2]]
:param data:
Any iterable. If ``data`` is a generator, it will be exhausted,
obviously.
:param int block_site:
Desired (maximum) block size.
""" |
buf = []
for i, datum in enumerate(data):
buf.append(datum)
if len(buf) == block_size:
yield buf
buf = []
# If there's anything leftover (a partial block),
# yield it as well.
if buf:
yield buf |
<SYSTEM_TASK:>
Round coordinates of a geometric object to given precision.
<END_TASK>
<USER_TASK:>
Description:
def round_geom(geom, precision=None):
"""Round coordinates of a geometric object to given precision.""" |
if geom['type'] == 'Point':
x, y = geom['coordinates']
xp, yp = [x], [y]
if precision is not None:
xp = [round(v, precision) for v in xp]
yp = [round(v, precision) for v in yp]
new_coords = tuple(zip(xp, yp))[0]
if geom['type'] in ['LineString', 'MultiPoint']:
xp, yp = zip(*geom['coordinates'])
if precision is not None:
xp = [round(v, precision) for v in xp]
yp = [round(v, precision) for v in yp]
new_coords = tuple(zip(xp, yp))
elif geom['type'] in ['Polygon', 'MultiLineString']:
new_coords = []
for piece in geom['coordinates']:
xp, yp = zip(*piece)
if precision is not None:
xp = [round(v, precision) for v in xp]
yp = [round(v, precision) for v in yp]
new_coords.append(tuple(zip(xp, yp)))
elif geom['type'] == 'MultiPolygon':
parts = geom['coordinates']
new_coords = []
for part in parts:
inner_coords = []
for ring in part:
xp, yp = zip(*ring)
if precision is not None:
xp = [round(v, precision) for v in xp]
yp = [round(v, precision) for v in yp]
inner_coords.append(tuple(zip(xp, yp)))
new_coords.append(inner_coords)
return {'type': geom['type'], 'coordinates': new_coords} |
<SYSTEM_TASK:>
Convert text read from the first positional argument, stdin, or
<END_TASK>
<USER_TASK:>
Description:
def cli(input, verbose, quiet, output_format, precision, indent):
"""Convert text read from the first positional argument, stdin, or
a file to GeoJSON and write to stdout.""" |
verbosity = verbose - quiet
configure_logging(verbosity)
logger = logging.getLogger('geomet')
# Handle the case of file, stream, or string input.
try:
src = click.open_file(input).readlines()
except IOError:
src = [input]
stdout = click.get_text_stream('stdout')
# Read-write loop.
try:
for line in src:
text = line.strip()
logger.debug("Input: %r", text)
output = translate(
text,
output_format=output_format,
indent=indent,
precision=precision
)
logger.debug("Output: %r", output)
stdout.write(output)
stdout.write('\n')
sys.exit(0)
except Exception:
logger.exception("Failed. Exception caught")
sys.exit(1) |
<SYSTEM_TASK:>
Get the GeoJSON geometry type label from a WKB type byte string.
<END_TASK>
<USER_TASK:>
Description:
def _get_geom_type(type_bytes):
"""Get the GeoJSON geometry type label from a WKB type byte string.
:param type_bytes:
4 byte string in big endian byte order containing a WKB type number.
It may also contain a "has SRID" flag in the high byte (the first type,
since this is big endian byte order), indicated as 0x20. If the SRID
flag is not set, the high byte will always be null (0x00).
:returns:
3-tuple ofGeoJSON geometry type label, the bytes resprenting the
geometry type, and a separate "has SRID" flag. If the input
`type_bytes` contains an SRID flag, it will be removed.
>>> # Z Point, with SRID flag
>>> _get_geom_type(b'\\x20\\x00\\x03\\xe9') == (
... 'Point', b'\\x00\\x00\\x03\\xe9', True)
True
>>> # 2D MultiLineString, without SRID flag
>>> _get_geom_type(b'\\x00\\x00\\x00\\x05') == (
... 'MultiLineString', b'\\x00\\x00\\x00\\x05', False)
True
""" |
# slice off the high byte, which may contain the SRID flag
high_byte = type_bytes[0]
if six.PY3:
high_byte = bytes([high_byte])
has_srid = high_byte == b'\x20'
if has_srid:
# replace the high byte with a null byte
type_bytes = as_bin_str(b'\x00' + type_bytes[1:])
else:
type_bytes = as_bin_str(type_bytes)
# look up the geometry type
geom_type = _BINARY_TO_GEOM_TYPE.get(type_bytes)
return geom_type, type_bytes, has_srid |
<SYSTEM_TASK:>
Dump a GeoJSON-like `dict` to a WKB string.
<END_TASK>
<USER_TASK:>
Description:
def dumps(obj, big_endian=True):
"""
Dump a GeoJSON-like `dict` to a WKB string.
.. note::
The dimensions of the generated WKB will be inferred from the first
vertex in the GeoJSON `coordinates`. It will be assumed that all
vertices are uniform. There are 4 types:
- 2D (X, Y): 2-dimensional geometry
- Z (X, Y, Z): 3-dimensional geometry
- M (X, Y, M): 2-dimensional geometry with a "Measure"
- ZM (X, Y, Z, M): 3-dimensional geometry with a "Measure"
If the first vertex contains 2 values, we assume a 2D geometry.
If the first vertex contains 3 values, this is slightly ambiguous and
so the most common case is chosen: Z.
If the first vertex contains 4 values, we assume a ZM geometry.
The WKT/WKB standards provide a way of differentiating normal (2D), Z,
M, and ZM geometries (http://en.wikipedia.org/wiki/Well-known_text),
but the GeoJSON spec does not. Therefore, for the sake of interface
simplicity, we assume that geometry that looks 3D contains XYZ
components, instead of XYM.
If the coordinates list has no coordinate values (this includes nested
lists, for example, `[[[[],[]], []]]`, the geometry is considered to be
empty. Geometries, with the exception of points, have a reasonable
"empty" representation in WKB; however, without knowing the number of
coordinate values per vertex, the type is ambigious, and thus we don't
know if the geometry type is 2D, Z, M, or ZM. Therefore in this case
we expect a `ValueError` to be raised.
:param dict obj:
GeoJson-like `dict` object.
:param bool big_endian:
Defaults to `True`. If `True`, data values in the generated WKB will
be represented using big endian byte order. Else, little endian.
TODO: remove this
:param str dims:
Indicates to WKB representation desired from converting the given
GeoJSON `dict` ``obj``. The accepted values are:
* '2D': 2-dimensional geometry (X, Y)
* 'Z': 3-dimensional geometry (X, Y, Z)
* 'M': 3-dimensional geometry (X, Y, M)
* 'ZM': 4-dimensional geometry (X, Y, Z, M)
:returns:
A WKB binary string representing of the ``obj``.
""" |
geom_type = obj['type']
meta = obj.get('meta', {})
exporter = _dumps_registry.get(geom_type)
if exporter is None:
_unsupported_geom_type(geom_type)
# Check for empty geometries. GeometryCollections have a slightly different
# JSON/dict structure, but that's handled.
coords_or_geoms = obj.get('coordinates', obj.get('geometries'))
if len(list(flatten_multi_dim(coords_or_geoms))) == 0:
raise ValueError(
'Empty geometries cannot be represented in WKB. Reason: The '
'dimensionality of the WKB would be ambiguous.'
)
return exporter(obj, big_endian, meta) |
<SYSTEM_TASK:>
Dump a GeoJSON-like `dict` to a point WKB string.
<END_TASK>
<USER_TASK:>
Description:
def _dump_point(obj, big_endian, meta):
"""
Dump a GeoJSON-like `dict` to a point WKB string.
:param dict obj:
GeoJson-like `dict` object.
:param bool big_endian:
If `True`, data values in the generated WKB will be represented using
big endian byte order. Else, little endian.
:param dict meta:
Metadata associated with the GeoJSON object. Currently supported
metadata:
- srid: Used to support EWKT/EWKB. For example, ``meta`` equal to
``{'srid': '4326'}`` indicates that the geometry is defined using
Extended WKT/WKB and that it bears a Spatial Reference System
Identifier of 4326. This ID will be encoded into the resulting
binary.
Any other meta data objects will simply be ignored by this function.
:returns:
A WKB binary string representing of the Point ``obj``.
""" |
coords = obj['coordinates']
num_dims = len(coords)
wkb_string, byte_fmt, _ = _header_bytefmt_byteorder(
'Point', num_dims, big_endian, meta
)
wkb_string += struct.pack(byte_fmt, *coords)
return wkb_string |
<SYSTEM_TASK:>
Dump a GeoJSON-like `dict` to a linestring WKB string.
<END_TASK>
<USER_TASK:>
Description:
def _dump_linestring(obj, big_endian, meta):
"""
Dump a GeoJSON-like `dict` to a linestring WKB string.
Input parameters and output are similar to :func:`_dump_point`.
""" |
coords = obj['coordinates']
vertex = coords[0]
# Infer the number of dimensions from the first vertex
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
'LineString', num_dims, big_endian, meta
)
# append number of vertices in linestring
wkb_string += struct.pack('%sl' % byte_order, len(coords))
for vertex in coords:
wkb_string += struct.pack(byte_fmt, *vertex)
return wkb_string |
<SYSTEM_TASK:>
Dump a GeoJSON-like `dict` to a multipoint WKB string.
<END_TASK>
<USER_TASK:>
Description:
def _dump_multipoint(obj, big_endian, meta):
"""
Dump a GeoJSON-like `dict` to a multipoint WKB string.
Input parameters and output are similar to :funct:`_dump_point`.
""" |
coords = obj['coordinates']
vertex = coords[0]
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
'MultiPoint', num_dims, big_endian, meta
)
point_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['Point']
if big_endian:
point_type = BIG_ENDIAN + point_type
else:
point_type = LITTLE_ENDIAN + point_type[::-1]
wkb_string += struct.pack('%sl' % byte_order, len(coords))
for vertex in coords:
# POINT type strings
wkb_string += point_type
wkb_string += struct.pack(byte_fmt, *vertex)
return wkb_string |
<SYSTEM_TASK:>
Dump a GeoJSON-like `dict` to a multilinestring WKB string.
<END_TASK>
<USER_TASK:>
Description:
def _dump_multilinestring(obj, big_endian, meta):
"""
Dump a GeoJSON-like `dict` to a multilinestring WKB string.
Input parameters and output are similar to :funct:`_dump_point`.
""" |
coords = obj['coordinates']
vertex = coords[0][0]
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
'MultiLineString', num_dims, big_endian, meta
)
ls_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['LineString']
if big_endian:
ls_type = BIG_ENDIAN + ls_type
else:
ls_type = LITTLE_ENDIAN + ls_type[::-1]
# append the number of linestrings
wkb_string += struct.pack('%sl' % byte_order, len(coords))
for linestring in coords:
wkb_string += ls_type
# append the number of vertices in each linestring
wkb_string += struct.pack('%sl' % byte_order, len(linestring))
for vertex in linestring:
wkb_string += struct.pack(byte_fmt, *vertex)
return wkb_string |
<SYSTEM_TASK:>
Dump a GeoJSON-like `dict` to a multipolygon WKB string.
<END_TASK>
<USER_TASK:>
Description:
def _dump_multipolygon(obj, big_endian, meta):
"""
Dump a GeoJSON-like `dict` to a multipolygon WKB string.
Input parameters and output are similar to :funct:`_dump_point`.
""" |
coords = obj['coordinates']
vertex = coords[0][0][0]
num_dims = len(vertex)
wkb_string, byte_fmt, byte_order = _header_bytefmt_byteorder(
'MultiPolygon', num_dims, big_endian, meta
)
poly_type = _WKB[_INT_TO_DIM_LABEL.get(num_dims)]['Polygon']
if big_endian:
poly_type = BIG_ENDIAN + poly_type
else:
poly_type = LITTLE_ENDIAN + poly_type[::-1]
# apped the number of polygons
wkb_string += struct.pack('%sl' % byte_order, len(coords))
for polygon in coords:
# append polygon header
wkb_string += poly_type
# append the number of rings in this polygon
wkb_string += struct.pack('%sl' % byte_order, len(polygon))
for ring in polygon:
# append the number of vertices in this ring
wkb_string += struct.pack('%sl' % byte_order, len(ring))
for vertex in ring:
wkb_string += struct.pack(byte_fmt, *vertex)
return wkb_string |
<SYSTEM_TASK:>
Convert byte data for a Point to a GeoJSON `dict`.
<END_TASK>
<USER_TASK:>
Description:
def _load_point(big_endian, type_bytes, data_bytes):
"""
Convert byte data for a Point to a GeoJSON `dict`.
:param bool big_endian:
If `True`, interpret the ``data_bytes`` in big endian order, else
little endian.
:param str type_bytes:
4-byte integer (as a binary string) indicating the geometry type
(Point) and the dimensions (2D, Z, M or ZM). For consistency, these
bytes are expected to always be in big endian order, regardless of the
value of ``big_endian``.
:param str data_bytes:
Coordinate data in a binary string.
:returns:
GeoJSON `dict` representing the Point geometry.
""" |
endian_token = '>' if big_endian else '<'
if type_bytes == WKB_2D['Point']:
coords = struct.unpack('%sdd' % endian_token,
as_bin_str(take(16, data_bytes)))
elif type_bytes == WKB_Z['Point']:
coords = struct.unpack('%sddd' % endian_token,
as_bin_str(take(24, data_bytes)))
elif type_bytes == WKB_M['Point']:
# NOTE: The use of XYM types geometries is quite rare. In the interest
# of removing ambiguity, we will treat all XYM geometries as XYZM when
# generate the GeoJSON. A default Z value of `0.0` will be given in
# this case.
coords = list(struct.unpack('%sddd' % endian_token,
as_bin_str(take(24, data_bytes))))
coords.insert(2, 0.0)
elif type_bytes == WKB_ZM['Point']:
coords = struct.unpack('%sdddd' % endian_token,
as_bin_str(take(32, data_bytes)))
return dict(type='Point', coordinates=list(coords)) |
<SYSTEM_TASK:>
Since the tokenizer treats "-" and numeric strings as separate values,
<END_TASK>
<USER_TASK:>
Description:
def _tokenize_wkt(tokens):
"""
Since the tokenizer treats "-" and numeric strings as separate values,
combine them and yield them as a single token. This utility encapsulates
parsing of negative numeric values from WKT can be used generically in all
parsers.
""" |
negative = False
for t in tokens:
if t == '-':
negative = True
continue
else:
if negative:
yield '-%s' % t
else:
yield t
negative = False |
<SYSTEM_TASK:>
Round the input value to `decimals` places, and pad with 0's
<END_TASK>
<USER_TASK:>
Description:
def _round_and_pad(value, decimals):
"""
Round the input value to `decimals` places, and pad with 0's
if the resulting value is less than `decimals`.
:param value:
The value to round
:param decimals:
Number of decimals places which should be displayed after the rounding.
:return:
str of the rounded value
""" |
if isinstance(value, int) and decimals != 0:
# if we get an int coordinate and we have a non-zero value for
# `decimals`, we want to create a float to pad out.
value = float(value)
elif decimals == 0:
# if get a `decimals` value of 0, we want to return an int.
return repr(int(round(value, decimals)))
rounded = repr(round(value, decimals))
rounded += '0' * (decimals - len(rounded.split('.')[1]))
return rounded |
<SYSTEM_TASK:>
Dump a GeoJSON-like Point object to WKT.
<END_TASK>
<USER_TASK:>
Description:
def _dump_point(obj, decimals):
"""
Dump a GeoJSON-like Point object to WKT.
:param dict obj:
A GeoJSON-like `dict` representing a Point.
:param int decimals:
int which indicates the number of digits to display after the
decimal point when formatting coordinates.
:returns:
WKT representation of the input GeoJSON Point ``obj``.
""" |
coords = obj['coordinates']
pt = 'POINT (%s)' % ' '.join(_round_and_pad(c, decimals)
for c in coords)
return pt |
<SYSTEM_TASK:>
Dump a GeoJSON-like LineString object to WKT.
<END_TASK>
<USER_TASK:>
Description:
def _dump_linestring(obj, decimals):
"""
Dump a GeoJSON-like LineString object to WKT.
Input parameters and return value are the LINESTRING equivalent to
:func:`_dump_point`.
""" |
coords = obj['coordinates']
ls = 'LINESTRING (%s)'
ls %= ', '.join(' '.join(_round_and_pad(c, decimals)
for c in pt) for pt in coords)
return ls |
<SYSTEM_TASK:>
Dump a GeoJSON-like Polygon object to WKT.
<END_TASK>
<USER_TASK:>
Description:
def _dump_polygon(obj, decimals):
"""
Dump a GeoJSON-like Polygon object to WKT.
Input parameters and return value are the POLYGON equivalent to
:func:`_dump_point`.
""" |
coords = obj['coordinates']
poly = 'POLYGON (%s)'
rings = (', '.join(' '.join(_round_and_pad(c, decimals)
for c in pt) for pt in ring)
for ring in coords)
rings = ('(%s)' % r for r in rings)
poly %= ', '.join(rings)
return poly |
<SYSTEM_TASK:>
Dump a GeoJSON-like MultiPoint object to WKT.
<END_TASK>
<USER_TASK:>
Description:
def _dump_multipoint(obj, decimals):
"""
Dump a GeoJSON-like MultiPoint object to WKT.
Input parameters and return value are the MULTIPOINT equivalent to
:func:`_dump_point`.
""" |
coords = obj['coordinates']
mp = 'MULTIPOINT (%s)'
points = (' '.join(_round_and_pad(c, decimals)
for c in pt) for pt in coords)
# Add parens around each point.
points = ('(%s)' % pt for pt in points)
mp %= ', '.join(points)
return mp |
<SYSTEM_TASK:>
Dump a GeoJSON-like MultiLineString object to WKT.
<END_TASK>
<USER_TASK:>
Description:
def _dump_multilinestring(obj, decimals):
"""
Dump a GeoJSON-like MultiLineString object to WKT.
Input parameters and return value are the MULTILINESTRING equivalent to
:func:`_dump_point`.
""" |
coords = obj['coordinates']
mlls = 'MULTILINESTRING (%s)'
linestrs = ('(%s)' % ', '.join(' '.join(_round_and_pad(c, decimals)
for c in pt) for pt in linestr) for linestr in coords)
mlls %= ', '.join(ls for ls in linestrs)
return mlls |
<SYSTEM_TASK:>
Dump a GeoJSON-like MultiPolygon object to WKT.
<END_TASK>
<USER_TASK:>
Description:
def _dump_multipolygon(obj, decimals):
"""
Dump a GeoJSON-like MultiPolygon object to WKT.
Input parameters and return value are the MULTIPOLYGON equivalent to
:func:`_dump_point`.
""" |
coords = obj['coordinates']
mp = 'MULTIPOLYGON (%s)'
polys = (
# join the polygons in the multipolygon
', '.join(
# join the rings in a polygon,
# and wrap in parens
'(%s)' % ', '.join(
# join the points in a ring,
# and wrap in parens
'(%s)' % ', '.join(
# join coordinate values of a vertex
' '.join(_round_and_pad(c, decimals) for c in pt)
for pt in ring)
for ring in poly)
for poly in coords)
)
mp %= polys
return mp |
<SYSTEM_TASK:>
Dump a GeoJSON-like GeometryCollection object to WKT.
<END_TASK>
<USER_TASK:>
Description:
def _dump_geometrycollection(obj, decimals):
"""
Dump a GeoJSON-like GeometryCollection object to WKT.
Input parameters and return value are the GEOMETRYCOLLECTION equivalent to
:func:`_dump_point`.
The WKT conversions for each geometry in the collection are delegated to
their respective functions.
""" |
gc = 'GEOMETRYCOLLECTION (%s)'
geoms = obj['geometries']
geoms_wkt = []
for geom in geoms:
geom_type = geom['type']
geoms_wkt.append(_dumps_registry.get(geom_type)(geom, decimals))
gc %= ','.join(geoms_wkt)
return gc |
<SYSTEM_TASK:>
Merge shared params and new params.
<END_TASK>
<USER_TASK:>
Description:
def _get_request_params(self, **kwargs):
"""Merge shared params and new params.""" |
request_params = copy.deepcopy(self._shared_request_params)
for key, value in iteritems(kwargs):
if isinstance(value, dict) and key in request_params:
# ensure we don't lose dict values like headers or cookies
request_params[key].update(value)
else:
request_params[key] = value
return request_params |
<SYSTEM_TASK:>
Remove keyword arguments not used by `requests`
<END_TASK>
<USER_TASK:>
Description:
def _sanitize_request_params(self, request_params):
"""Remove keyword arguments not used by `requests`""" |
if 'verify_ssl' in request_params:
request_params['verify'] = request_params.pop('verify_ssl')
return dict((key, val) for key, val in request_params.items()
if key in self._VALID_REQUEST_ARGS) |
<SYSTEM_TASK:>
Override this method to modify sent request parameters
<END_TASK>
<USER_TASK:>
Description:
def pre_send(self, request_params):
"""Override this method to modify sent request parameters""" |
for adapter in itervalues(self.adapters):
adapter.max_retries = request_params.get('max_retries', 0)
return request_params |
<SYSTEM_TASK:>
Rounds a signed list over the last element and removes it.
<END_TASK>
<USER_TASK:>
Description:
def _roundSlist(slist):
""" Rounds a signed list over the last element and removes it. """ |
slist[-1] = 60 if slist[-1] >= 30 else 0
for i in range(len(slist)-1, 1, -1):
if slist[i] == 60:
slist[i] = 0
slist[i-1] += 1
return slist[:-1] |
<SYSTEM_TASK:>
Converts signed list to angle string.
<END_TASK>
<USER_TASK:>
Description:
def slistStr(slist):
""" Converts signed list to angle string. """ |
slist = _fixSlist(slist)
string = ':'.join(['%02d' % x for x in slist[1:]])
return slist[0] + string |
<SYSTEM_TASK:>
Converts signed list to float.
<END_TASK>
<USER_TASK:>
Description:
def slistFloat(slist):
""" Converts signed list to float. """ |
values = [v / 60**(i) for (i,v) in enumerate(slist[1:])]
value = sum(values)
return -value if slist[0] == '-' else value |
<SYSTEM_TASK:>
Converts float to signed list.
<END_TASK>
<USER_TASK:>
Description:
def floatSlist(value):
""" Converts float to signed list. """ |
slist = ['+', 0, 0, 0, 0]
if value < 0:
slist[0] = '-'
value = abs(value)
for i in range(1,5):
slist[i] = math.floor(value)
value = (value - slist[i]) * 60
return _roundSlist(slist) |
<SYSTEM_TASK:>
Converts string or signed list to float.
<END_TASK>
<USER_TASK:>
Description:
def toFloat(value):
""" Converts string or signed list to float. """ |
if isinstance(value, str):
return strFloat(value)
elif isinstance(value, list):
return slistFloat(value)
else:
return value |
<SYSTEM_TASK:>
Returns the dignities of A which belong to B.
<END_TASK>
<USER_TASK:>
Description:
def inDignities(self, idA, idB):
""" Returns the dignities of A which belong to B. """ |
objA = self.chart.get(idA)
info = essential.getInfo(objA.sign, objA.signlon)
# Should we ignore exile and fall?
return [dign for (dign, ID) in info.items() if ID == idB] |
<SYSTEM_TASK:>
Returns all pairs of dignities in mutual reception.
<END_TASK>
<USER_TASK:>
Description:
def mutualReceptions(self, idA, idB):
""" Returns all pairs of dignities in mutual reception. """ |
AB = self.receives(idA, idB)
BA = self.receives(idB, idA)
# Returns a product of both lists
return [(a,b) for a in AB for b in BA] |
<SYSTEM_TASK:>
Returns ruler and exaltation mutual receptions.
<END_TASK>
<USER_TASK:>
Description:
def reMutualReceptions(self, idA, idB):
""" Returns ruler and exaltation mutual receptions. """ |
mr = self.mutualReceptions(idA, idB)
filter_ = ['ruler', 'exalt']
# Each pair of dignities must be 'ruler' or 'exalt'
return [(a,b) for (a,b) in mr if (a in filter_ and b in filter_)] |
<SYSTEM_TASK:>
Returns a list with the aspects an object
<END_TASK>
<USER_TASK:>
Description:
def validAspects(self, ID, aspList):
""" Returns a list with the aspects an object
makes with the other six planets, considering a
list of possible aspects.
""" |
obj = self.chart.getObject(ID)
res = []
for otherID in const.LIST_SEVEN_PLANETS:
if ID == otherID:
continue
otherObj = self.chart.getObject(otherID)
aspType = aspects.aspectType(obj, otherObj, aspList)
if aspType != const.NO_ASPECT:
res.append({
'id': otherID,
'asp': aspType,
})
return res |
<SYSTEM_TASK:>
Returns the last separation and next application
<END_TASK>
<USER_TASK:>
Description:
def immediateAspects(self, ID, aspList):
""" Returns the last separation and next application
considering a list of possible aspects.
""" |
asps = self.aspectsByCat(ID, aspList)
applications = asps[const.APPLICATIVE]
separations = asps[const.SEPARATIVE]
exact = asps[const.EXACT]
# Get applications and separations sorted by orb
applications = applications + [val for val in exact if val['orb'] >= 0]
applications = sorted(applications, key=lambda var: var['orb'])
separations = sorted(separations, key=lambda var: var['orb'])
return (
separations[0] if separations else None,
applications[0] if applications else None
) |
<SYSTEM_TASK:>
Single factor for the table.
<END_TASK>
<USER_TASK:>
Description:
def singleFactor(factors, chart, factor, obj, aspect=None):
"""" Single factor for the table. """ |
objID = obj if type(obj) == str else obj.id
res = {
'factor': factor,
'objID': objID,
'aspect': aspect
}
# For signs (obj as string) return sign element
if type(obj) == str:
res['element'] = props.sign.element[obj]
# For Sun return sign and sunseason element
elif objID == const.SUN:
sunseason = props.sign.sunseason[obj.sign]
res['sign'] = obj.sign
res['sunseason'] = sunseason
res['element'] = props.base.sunseasonElement[sunseason]
# For Moon return phase and phase element
elif objID == const.MOON:
phase = chart.getMoonPhase()
res['phase'] = phase
res['element'] = props.base.moonphaseElement[phase]
# For regular planets return element or sign/sign element
# if there's an aspect involved
elif objID in const.LIST_SEVEN_PLANETS:
if aspect:
res['sign'] = obj.sign
res['element'] = props.sign.element[obj.sign]
else:
res['element'] = obj.element()
try:
# If there's element, insert into list
res['element']
factors.append(res)
except KeyError:
pass
return res |
<SYSTEM_TASK:>
Returns the factors for the temperament.
<END_TASK>
<USER_TASK:>
Description:
def getFactors(chart):
""" Returns the factors for the temperament. """ |
factors = []
# Asc sign
asc = chart.getAngle(const.ASC)
singleFactor(factors, chart, ASC_SIGN, asc.sign)
# Asc ruler
ascRulerID = essential.ruler(asc.sign)
ascRuler = chart.getObject(ascRulerID)
singleFactor(factors, chart, ASC_RULER, ascRuler)
singleFactor(factors, chart, ASC_RULER_SIGN, ascRuler.sign)
# Planets in House 1
house1 = chart.getHouse(const.HOUSE1)
planetsHouse1 = chart.objects.getObjectsInHouse(house1)
for obj in planetsHouse1:
singleFactor(factors, chart, HOUSE1_PLANETS_IN, obj)
# Planets conjunct Asc
planetsConjAsc = chart.objects.getObjectsAspecting(asc, [0])
for obj in planetsConjAsc:
# Ignore planets already in house 1
if obj not in planetsHouse1:
singleFactor(factors, chart, ASC_PLANETS_CONJ, obj)
# Planets aspecting Asc cusp
aspList = [60, 90, 120, 180]
planetsAspAsc = chart.objects.getObjectsAspecting(asc, aspList)
for obj in planetsAspAsc:
aspect = aspects.aspectType(obj, asc, aspList)
singleFactor(factors, chart, ASC_PLANETS_ASP, obj, aspect)
# Moon sign and phase
moon = chart.getObject(const.MOON)
singleFactor(factors, chart, MOON_SIGN, moon.sign)
singleFactor(factors, chart, MOON_PHASE, moon)
# Moon dispositor
moonRulerID = essential.ruler(moon.sign)
moonRuler = chart.getObject(moonRulerID)
moonFactor = singleFactor(factors, chart, MOON_DISPOSITOR_SIGN, moonRuler.sign)
moonFactor['planetID'] = moonRulerID # Append moon dispositor ID
# Planets conjunct Moon
planetsConjMoon = chart.objects.getObjectsAspecting(moon, [0])
for obj in planetsConjMoon:
singleFactor(factors, chart, MOON_PLANETS_CONJ, obj)
# Planets aspecting Moon
aspList = [60, 90, 120, 180]
planetsAspMoon = chart.objects.getObjectsAspecting(moon, aspList)
for obj in planetsAspMoon:
aspect = aspects.aspectType(obj, moon, aspList)
singleFactor(factors, chart, MOON_PLANETS_ASP, obj, aspect)
# Sun season
sun = chart.getObject(const.SUN)
singleFactor(factors, chart, SUN_SEASON, sun)
return factors |
<SYSTEM_TASK:>
Returns the factors of the temperament modifiers.
<END_TASK>
<USER_TASK:>
Description:
def getModifiers(chart):
""" Returns the factors of the temperament modifiers. """ |
modifiers = []
# Factors which can be affected
asc = chart.getAngle(const.ASC)
ascRulerID = essential.ruler(asc.sign)
ascRuler = chart.getObject(ascRulerID)
moon = chart.getObject(const.MOON)
factors = [
[MOD_ASC, asc],
[MOD_ASC_RULER, ascRuler],
[MOD_MOON, moon]
]
# Factors of affliction
mars = chart.getObject(const.MARS)
saturn = chart.getObject(const.SATURN)
sun = chart.getObject(const.SUN)
affect = [
[mars, [0, 90, 180]],
[saturn, [0, 90, 180]],
[sun, [0]]
]
# Do calculations of afflictions
for affectingObj, affectingAsps in affect:
for factor, affectedObj in factors:
modf = modifierFactor(chart,
factor,
affectedObj,
affectingObj,
affectingAsps)
if modf:
modifiers.append(modf)
return modifiers |
<SYSTEM_TASK:>
Computes the score of temperaments
<END_TASK>
<USER_TASK:>
Description:
def scores(factors):
""" Computes the score of temperaments
and elements.
""" |
temperaments = {
const.CHOLERIC: 0,
const.MELANCHOLIC: 0,
const.SANGUINE: 0,
const.PHLEGMATIC: 0
}
qualities = {
const.HOT: 0,
const.COLD: 0,
const.DRY: 0,
const.HUMID: 0
}
for factor in factors:
element = factor['element']
# Score temperament
temperament = props.base.elementTemperament[element]
temperaments[temperament] += 1
# Score qualities
tqualities = props.base.temperamentQuality[temperament]
qualities[tqualities[0]] += 1
qualities[tqualities[1]] += 1
return {
'temperaments': temperaments,
'qualities': qualities
} |
<SYSTEM_TASK:>
Returns the lists of houses and angles.
<END_TASK>
<USER_TASK:>
Description:
def getHouses(date, pos, hsys):
""" Returns the lists of houses and angles.
Since houses and angles are computed at the
same time, this function should be fast.
""" |
houses, angles = eph.getHouses(date.jd, pos.lat, pos.lon, hsys)
hList = [House.fromDict(house) for house in houses]
aList = [GenericObject.fromDict(angle) for angle in angles]
return (HouseList(hList), GenericList(aList)) |
<SYSTEM_TASK:>
Returns a fixed star from the ephemeris.
<END_TASK>
<USER_TASK:>
Description:
def getFixedStar(ID, date):
""" Returns a fixed star from the ephemeris. """ |
star = eph.getFixedStar(ID, date.jd)
return FixedStar.fromDict(star) |
<SYSTEM_TASK:>
Returns the next date when sun is at longitude 'lon'.
<END_TASK>
<USER_TASK:>
Description:
def nextSolarReturn(date, lon):
""" Returns the next date when sun is at longitude 'lon'. """ |
jd = eph.nextSolarReturn(date.jd, lon)
return Datetime.fromJD(jd, date.utcoffset) |
<SYSTEM_TASK:>
Returns the previous date when sun is at longitude 'lon'.
<END_TASK>
<USER_TASK:>
Description:
def prevSolarReturn(date, lon):
""" Returns the previous date when sun is at longitude 'lon'. """ |
jd = eph.prevSolarReturn(date.jd, lon)
return Datetime.fromJD(jd, date.utcoffset) |
<SYSTEM_TASK:>
Returns the date of the next sunrise.
<END_TASK>
<USER_TASK:>
Description:
def nextSunrise(date, pos):
""" Returns the date of the next sunrise. """ |
jd = eph.nextSunrise(date.jd, pos.lat, pos.lon)
return Datetime.fromJD(jd, date.utcoffset) |
<SYSTEM_TASK:>
Returns the Datetime of the maximum phase of the
<END_TASK>
<USER_TASK:>
Description:
def prevSolarEclipse(date):
""" Returns the Datetime of the maximum phase of the
previous global solar eclipse.
""" |
eclipse = swe.solarEclipseGlobal(date.jd, backward=True)
return Datetime.fromJD(eclipse['maximum'], date.utcoffset) |
<SYSTEM_TASK:>
Returns the Datetime of the maximum phase of the
<END_TASK>
<USER_TASK:>
Description:
def nextSolarEclipse(date):
""" Returns the Datetime of the maximum phase of the
next global solar eclipse.
""" |
eclipse = swe.solarEclipseGlobal(date.jd, backward=False)
return Datetime.fromJD(eclipse['maximum'], date.utcoffset) |
<SYSTEM_TASK:>
Returns the Datetime of the maximum phase of the
<END_TASK>
<USER_TASK:>
Description:
def prevLunarEclipse(date):
""" Returns the Datetime of the maximum phase of the
previous global lunar eclipse.
""" |
eclipse = swe.lunarEclipseGlobal(date.jd, backward=True)
return Datetime.fromJD(eclipse['maximum'], date.utcoffset) |
<SYSTEM_TASK:>
Returns the Datetime of the maximum phase of the
<END_TASK>
<USER_TASK:>
Description:
def nextLunarEclipse(date):
""" Returns the Datetime of the maximum phase of the
next global lunar eclipse.
""" |
eclipse = swe.lunarEclipseGlobal(date.jd, backward=False)
return Datetime.fromJD(eclipse['maximum'], date.utcoffset) |
<SYSTEM_TASK:>
Plots the tropical solar length
<END_TASK>
<USER_TASK:>
Description:
def plot(hdiff, title):
""" Plots the tropical solar length
by year.
""" |
import matplotlib.pyplot as plt
years = [elem[0] for elem in hdiff]
diffs = [elem[1] for elem in hdiff]
plt.plot(years, diffs)
plt.ylabel('Distance in minutes')
plt.xlabel('Year')
plt.title(title)
plt.axhline(y=0, c='red')
plt.show() |
<SYSTEM_TASK:>
Returns the Ascensional Difference of a point.
<END_TASK>
<USER_TASK:>
Description:
def ascdiff(decl, lat):
""" Returns the Ascensional Difference of a point. """ |
delta = math.radians(decl)
phi = math.radians(lat)
ad = math.asin(math.tan(delta) * math.tan(phi))
return math.degrees(ad) |
<SYSTEM_TASK:>
Returns the diurnal and nocturnal arcs of a point.
<END_TASK>
<USER_TASK:>
Description:
def dnarcs(decl, lat):
""" Returns the diurnal and nocturnal arcs of a point. """ |
dArc = 180 + 2 * ascdiff(decl, lat)
nArc = 360 - dArc
return (dArc, nArc) |
<SYSTEM_TASK:>
Returns if an object's 'ra' and 'decl'
<END_TASK>
<USER_TASK:>
Description:
def isAboveHorizon(ra, decl, mcRA, lat):
""" Returns if an object's 'ra' and 'decl'
is above the horizon at a specific latitude,
given the MC's right ascension.
""" |
# This function checks if the equatorial distance from
# the object to the MC is within its diurnal semi-arc.
dArc, _ = dnarcs(decl, lat)
dist = abs(angle.closestdistance(mcRA, ra))
return dist <= dArc/2.0 + 0.0003 |
<SYSTEM_TASK:>
Converts from ecliptical to equatorial coordinates.
<END_TASK>
<USER_TASK:>
Description:
def eqCoords(lon, lat):
""" Converts from ecliptical to equatorial coordinates.
This algorithm is described in book 'Primary Directions',
pp. 147-150.
""" |
# Convert to radians
_lambda = math.radians(lon)
_beta = math.radians(lat)
_epson = math.radians(23.44) # The earth's inclination
# Declination in radians
decl = math.asin(math.sin(_epson) * math.sin(_lambda) * math.cos(_beta) + \
math.cos(_epson) * math.sin(_beta))
# Equatorial Distance in radians
ED = math.acos(math.cos(_lambda) * math.cos(_beta) / math.cos(decl))
# RA in radians
ra = ED if lon < 180 else math.radians(360) - ED
# Correctness of RA if longitude is close to 0º or 180º in a radius of 5º
if (abs(angle.closestdistance(lon, 0)) < 5 or
abs(angle.closestdistance(lon, 180)) < 5):
a = math.sin(ra) * math.cos(decl)
b = math.cos(_epson) * math.sin(_lambda) * math.cos(_beta) - \
math.sin(_epson) * math.sin(_beta)
if (math.fabs(a-b) > 0.0003):
ra = math.radians(360) - ra
return (math.degrees(ra), math.degrees(decl)) |
<SYSTEM_TASK:>
Returns an object's relation with the sun.
<END_TASK>
<USER_TASK:>
Description:
def sunRelation(obj, sun):
""" Returns an object's relation with the sun. """ |
if obj.id == const.SUN:
return None
dist = abs(angle.closestdistance(sun.lon, obj.lon))
if dist < 0.2833: return CAZIMI
elif dist < 8.0: return COMBUST
elif dist < 16.0: return UNDER_SUN
else:
return None |
<SYSTEM_TASK:>
Returns if an object is augmenting or diminishing light.
<END_TASK>
<USER_TASK:>
Description:
def light(obj, sun):
""" Returns if an object is augmenting or diminishing light. """ |
dist = angle.distance(sun.lon, obj.lon)
faster = sun if sun.lonspeed > obj.lonspeed else obj
if faster == sun:
return LIGHT_DIMINISHING if dist < 180 else LIGHT_AUGMENTING
else:
return LIGHT_AUGMENTING if dist < 180 else LIGHT_DIMINISHING |
<SYSTEM_TASK:>
Returns if an object is oriental or
<END_TASK>
<USER_TASK:>
Description:
def orientality(obj, sun):
""" Returns if an object is oriental or
occidental to the sun.
""" |
dist = angle.distance(sun.lon, obj.lon)
return OCCIDENTAL if dist < 180 else ORIENTAL |
<SYSTEM_TASK:>
Returns if an object is in Haiz.
<END_TASK>
<USER_TASK:>
Description:
def haiz(obj, chart):
""" Returns if an object is in Haiz. """ |
objGender = obj.gender()
objFaction = obj.faction()
if obj.id == const.MERCURY:
# Gender and faction of mercury depends on orientality
sun = chart.getObject(const.SUN)
orientalityM = orientality(obj, sun)
if orientalityM == ORIENTAL:
objGender = const.MASCULINE
objFaction = const.DIURNAL
else:
objGender = const.FEMININE
objFaction = const.NOCTURNAL
# Object gender match sign gender?
signGender = props.sign.gender[obj.sign]
genderConformity = (objGender == signGender)
# Match faction
factionConformity = False
diurnalChart = chart.isDiurnal()
if obj.id == const.SUN and not diurnalChart:
# Sun is in conformity only when above horizon
factionConformity = False
else:
# Get list of houses in the chart's diurnal faction
if diurnalChart:
diurnalFaction = props.house.aboveHorizon
nocturnalFaction = props.house.belowHorizon
else:
diurnalFaction = props.house.belowHorizon
nocturnalFaction = props.house.aboveHorizon
# Get the object's house and match factions
objHouse = chart.houses.getObjectHouse(obj)
if (objFaction == const.DIURNAL and objHouse.id in diurnalFaction or
objFaction == const.NOCTURNAL and objHouse.id in nocturnalFaction):
factionConformity = True
# Match things
if (genderConformity and factionConformity):
return HAIZ
elif (not genderConformity and not factionConformity):
return CHAIZ
else:
return None |
<SYSTEM_TASK:>
Returns the relation of the object with the sun.
<END_TASK>
<USER_TASK:>
Description:
def sunRelation(self):
""" Returns the relation of the object with the sun. """ |
sun = self.chart.getObject(const.SUN)
return sunRelation(self.obj, sun) |
<SYSTEM_TASK:>
Returns if object is augmenting or diminishing its
<END_TASK>
<USER_TASK:>
Description:
def light(self):
""" Returns if object is augmenting or diminishing its
light.
""" |
sun = self.chart.getObject(const.SUN)
return light(self.obj, sun) |
<SYSTEM_TASK:>
Returns if the object is in its house of joy.
<END_TASK>
<USER_TASK:>
Description:
def inHouseJoy(self):
""" Returns if the object is in its house of joy. """ |
house = self.house()
return props.object.houseJoy[self.obj.id] == house.id |
<SYSTEM_TASK:>
Returns if the object is in its sign of joy.
<END_TASK>
<USER_TASK:>
Description:
def inSignJoy(self):
""" Returns if the object is in its sign of joy. """ |
return props.object.signJoy[self.obj.id] == self.obj.sign |
<SYSTEM_TASK:>
Returns all mutual receptions with the object
<END_TASK>
<USER_TASK:>
Description:
def reMutualReceptions(self):
""" Returns all mutual receptions with the object
and other planets, indexed by planet ID.
It only includes ruler and exaltation receptions.
""" |
planets = copy(const.LIST_SEVEN_PLANETS)
planets.remove(self.obj.id)
mrs = {}
for ID in planets:
mr = self.dyn.reMutualReceptions(self.obj.id, ID)
if mr:
mrs[ID] = mr
return mrs |
<SYSTEM_TASK:>
Returns a list with the good aspects the object
<END_TASK>
<USER_TASK:>
Description:
def aspectBenefics(self):
""" Returns a list with the good aspects the object
makes to the benefics.
""" |
benefics = [const.VENUS, const.JUPITER]
return self.__aspectLists(benefics, aspList=[0, 60, 120]) |
<SYSTEM_TASK:>
Returns a list with the bad aspects the object
<END_TASK>
<USER_TASK:>
Description:
def aspectMalefics(self):
""" Returns a list with the bad aspects the object
makes to the malefics.
""" |
malefics = [const.MARS, const.SATURN]
return self.__aspectLists(malefics, aspList=[0, 90, 180]) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.