code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if room_id:
return self.__call_api_post('channels.delete', roomId=room_id, kwargs=kwargs)
elif channel:
return self.__call_api_post('channels.delete', roomName=channel, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or channel required... | def channels_delete(self, room_id=None, channel=None, **kwargs) | Delete a public channel. | 2.756653 | 2.679939 | 1.028625 |
return self.__call_api_get('channels.getAllUserMentionsByChannel', roomId=room_id, kwargs=kwargs) | def channels_get_all_user_mentions_by_channel(self, room_id, **kwargs) | Gets all the mentions of a channel. | 4.377769 | 4.140876 | 1.057209 |
return self.__call_api_get('groups.history', roomId=room_id, kwargs=kwargs) | def groups_history(self, room_id, **kwargs) | Retrieves the messages from a private group. | 5.854474 | 5.330288 | 1.098341 |
return self.__call_api_post('groups.addModerator', roomId=room_id, userId=user_id, kwargs=kwargs) | def groups_add_moderator(self, room_id, user_id, **kwargs) | Gives the role of moderator for a user in the current groups. | 3.690042 | 3.341672 | 1.10425 |
return self.__call_api_post('groups.removeModerator', roomId=room_id, userId=user_id, kwargs=kwargs) | def groups_remove_moderator(self, room_id, user_id, **kwargs) | Removes the role of moderator from a user in the current groups. | 3.730152 | 3.444452 | 1.082945 |
if room_id:
return self.__call_api_get('groups.moderators', roomId=room_id, kwargs=kwargs)
elif group:
return self.__call_api_get('groups.moderators', roomName=group, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or group required') | def groups_moderators(self, room_id=None, group=None, **kwargs) | Lists all moderators of a group. | 2.622371 | 2.511507 | 1.044142 |
return self.__call_api_post('groups.addOwner', roomId=room_id, userId=user_id, kwargs=kwargs) | def groups_add_owner(self, room_id, user_id, **kwargs) | Gives the role of owner for a user in the current Group. | 3.943183 | 3.392405 | 1.162356 |
return self.__call_api_post('groups.removeOwner', roomId=room_id, userId=user_id, kwargs=kwargs) | def groups_remove_owner(self, room_id, user_id, **kwargs) | Removes the role of owner from a user in the current Group. | 3.973243 | 3.483124 | 1.140713 |
return self.__call_api_post('groups.archive', roomId=room_id, kwargs=kwargs) | def groups_archive(self, room_id, **kwargs) | Archives a private group, only if you’re part of the group. | 5.690638 | 5.134408 | 1.108334 |
return self.__call_api_post('groups.unarchive', roomId=room_id, kwargs=kwargs) | def groups_unarchive(self, room_id, **kwargs) | Unarchives a private group. | 5.149138 | 5.033928 | 1.022887 |
return self.__call_api_post('groups.close', roomId=room_id, kwargs=kwargs) | def groups_close(self, room_id, **kwargs) | Removes the private group from the user’s list of groups, only if you’re part of the group. | 5.67804 | 5.143129 | 1.104005 |
return self.__call_api_post('groups.create', name=name, kwargs=kwargs) | def groups_create(self, name, **kwargs) | Creates a new private group, optionally including users, only if you’re part of the group. | 6.111189 | 5.679131 | 1.076078 |
return self.__call_api_get('groups.getIntegrations', roomId=room_id, kwargs=kwargs) | def groups_get_integrations(self, room_id, **kwargs) | Retrieves the integrations which the group has | 5.415339 | 5.620336 | 0.963526 |
return self.__call_api_post('groups.invite', roomId=room_id, userId=user_id, kwargs=kwargs) | def groups_invite(self, room_id, user_id, **kwargs) | Adds a user to the private group. | 4.425707 | 4.030272 | 1.098116 |
return self.__call_api_post('groups.kick', roomId=room_id, userId=user_id, kwargs=kwargs) | def groups_kick(self, room_id, user_id, **kwargs) | Removes a user from the private group. | 4.261219 | 3.985797 | 1.069101 |
return self.__call_api_post('groups.leave', roomId=room_id, kwargs=kwargs) | def groups_leave(self, room_id, **kwargs) | Causes the callee to be removed from the private group, if they’re part of it and are not the last owner. | 5.716791 | 4.768307 | 1.198914 |
return self.__call_api_post('groups.open', roomId=room_id, kwargs=kwargs) | def groups_open(self, room_id, **kwargs) | Adds the private group back to the user’s list of private groups. | 5.731664 | 5.107437 | 1.122219 |
return self.__call_api_post('groups.rename', roomId=room_id, name=name, kwargs=kwargs) | def groups_rename(self, room_id, name, **kwargs) | Changes the name of the private group. | 4.533659 | 4.533113 | 1.000121 |
return self.__call_api_post('groups.setDescription', roomId=room_id, description=description, kwargs=kwargs) | def groups_set_description(self, room_id, description, **kwargs) | Sets the description for the private group. | 4.794064 | 4.847684 | 0.988939 |
return self.__call_api_post('groups.setReadOnly', roomId=room_id, readOnly=bool(read_only), kwargs=kwargs) | def groups_set_read_only(self, room_id, read_only, **kwargs) | Sets whether the group is read only or not. | 4.388665 | 4.230291 | 1.037438 |
return self.__call_api_post('groups.setTopic', roomId=room_id, topic=topic, kwargs=kwargs) | def groups_set_topic(self, room_id, topic, **kwargs) | Sets the topic for the private group. | 4.314339 | 4.179096 | 1.032362 |
return self.__call_api_post('groups.setType', roomId=room_id, type=a_type, kwargs=kwargs) | def groups_set_type(self, room_id, a_type, **kwargs) | Sets the type of room this group should be. The type of room this channel should be, either c or p. | 4.256302 | 4.266284 | 0.99766 |
if room_id:
return self.__call_api_post('groups.delete', roomId=room_id, kwargs=kwargs)
elif group:
return self.__call_api_post('groups.delete', roomName=group, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or group required') | def groups_delete(self, room_id=None, group=None, **kwargs) | Delete a private group. | 2.76714 | 2.622507 | 1.055151 |
if room_id:
return self.__call_api_get('groups.roles', roomId=room_id, kwargs=kwargs)
elif room_name:
return self.__call_api_get('groups.roles', roomName=room_name, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or room_name required') | def groups_roles(self, room_id=None, room_name=None, **kwargs) | Lists all user’s roles in the private group. | 2.541738 | 2.378877 | 1.068461 |
return self.__call_api_get('im.history', roomId=room_id, kwargs=kwargs) | def im_history(self, room_id, **kwargs) | Retrieves the history for a private im chat | 5.655671 | 5.493024 | 1.02961 |
return self.__call_api_post('im.create', username=username, kwargs=kwargs) | def im_create(self, username, **kwargs) | Create a direct message session with another user. | 5.788579 | 4.779486 | 1.21113 |
return self.__call_api_post('im.open', roomId=room_id, kwargs=kwargs) | def im_open(self, room_id, **kwargs) | Adds the direct message back to the user’s list of direct messages. | 6.230993 | 4.585489 | 1.35885 |
return self.__call_api_post('im.close', roomId=room_id, kwargs=kwargs) | def im_close(self, room_id, **kwargs) | Removes the direct message from the user’s list of direct messages. | 5.78098 | 4.853274 | 1.191151 |
return self.__call_api_get('im.messages.others', roomId=room_id, kwargs=kwargs) | def im_messages_others(self, room_id, **kwargs) | Retrieves the messages from any direct message in the server | 4.707244 | 4.630423 | 1.01659 |
return self.__call_api_post('im.setTopic', roomId=room_id, topic=topic, kwargs=kwargs) | def im_set_topic(self, room_id, topic, **kwargs) | Sets the topic for the direct message | 4.456068 | 4.586219 | 0.971621 |
if room_id:
return self.__call_api_get('im.files', roomId=room_id, kwargs=kwargs)
elif user_name:
return self.__call_api_get('im.files', username=user_name, kwargs=kwargs)
else:
raise RocketMissingParamException('roomId or username required') | def im_files(self, room_id=None, user_name=None, **kwargs) | Retrieves the files from a direct message. | 2.775707 | 2.495604 | 1.112239 |
files = {
'file': (os.path.basename(file), open(file, 'rb'), mimetypes.guess_type(file)[0]),
}
return self.__call_api_post('rooms.upload/' + rid, kwargs=kwargs, use_json=False, files=files) | def rooms_upload(self, rid, file, **kwargs) | Post a message with attached file to a dedicated room. | 3.286328 | 3.21257 | 1.022959 |
return self.__call_api_post('rooms.cleanHistory', roomId=room_id, latest=latest, oldest=oldest, kwargs=kwargs) | def rooms_clean_history(self, room_id, latest, oldest, **kwargs) | Cleans up a room, removing messages from the provided time range. | 3.43874 | 3.444644 | 0.998286 |
if room_id is not None:
return self.__call_api_post('rooms.favorite', roomId=room_id, favorite=favorite)
elif room_name is not None:
return self.__call_api_post('rooms.favorite', roomName=room_name, favorite=favorite)
else:
raise RocketMissingParamExc... | def rooms_favorite(self, room_id=None, room_name=None, favorite=True) | Favorite or unfavorite room. | 2.299528 | 2.187635 | 1.051148 |
if room_id is not None:
return self.__call_api_get('rooms.info', roomId=room_id)
elif room_name is not None:
return self.__call_api_get('rooms.info', roomName=room_name)
else:
raise RocketMissingParamException('roomId or roomName required') | def rooms_info(self, room_id=None, room_name=None) | Retrieves the information about the room. | 2.488284 | 2.32995 | 1.067956 |
return self.__call_api_get('subscriptions.getOne', roomId=room_id, kwargs=kwargs) | def subscriptions_get_one(self, room_id, **kwargs) | Get the subscription by room id. | 6.401041 | 5.7115 | 1.120729 |
return self.__call_api_post('subscriptions.unread', roomId=room_id, kwargs=kwargs) | def subscriptions_unread(self, room_id, **kwargs) | Mark messages as unread by roomId or from a message | 6.908472 | 5.654141 | 1.221843 |
return self.__call_api_post('subscriptions.read', rid=rid, kwargs=kwargs) | def subscriptions_read(self, rid, **kwargs) | Mark room as read | 6.280517 | 5.517169 | 1.138359 |
content_type = mimetypes.MimeTypes().guess_type(file)
files = {
asset_name: (file, open(file, 'rb'), content_type[0], {'Expires': '0'}),
}
return self.__call_api_post('assets.setAsset', kwargs=kwargs, use_json=False, files=files) | def assets_set_asset(self, asset_name, file, **kwargs) | Set an asset image by name. | 3.45176 | 3.496068 | 0.987326 |
'Return callback whether passed as a last argument or as a keyword'
if args and callable(args[-1]):
return args[-1], args[:-1]
try:
return kw['callback'], args
except (KeyError, TypeError):
return None, args | def find_callback(args, kw=None) | Return callback whether passed as a last argument or as a keyword | 5.363865 | 2.878982 | 1.863112 |
'Define a callback to handle the first event emitted by the server'
self._once_events.add(event)
self.on(event, callback) | def once(self, event, callback) | Define a callback to handle the first event emitted by the server | 8.860281 | 4.642481 | 1.908523 |
'Remove an event handler'
try:
self._once_events.remove(event)
except KeyError:
pass
self._callback_by_event.pop(event, None) | def off(self, event) | Remove an event handler | 6.425953 | 6.165828 | 1.042188 |
'Wait in a loop and react to events as defined in the namespaces'
# Use ping/pong to unblock recv for polling transport
self._heartbeat_thread.hurry()
# Use timeout to unblock recv for websocket transport
self._transport.set_timeout(seconds=1)
# Listen
warning_scr... | def wait(self, seconds=None, **kw) | Wait in a loop and react to events as defined in the namespaces | 8.197304 | 6.768719 | 1.211057 |
'Return function that acknowledges the server'
return lambda *args: self._ack(path, ack_id, *args) | def _prepare_to_send_ack(self, path, ack_id) | Return function that acknowledges the server | 17.607821 | 6.248063 | 2.818125 |
rad = angle * math.pi / 180
cosa = math.cos(rad)
sina = math.sin(rad)
y = self.y * cosa - self.z * sina
z = self.y * sina + self.z * cosa
return Point3D(self.x, y, z) | def rotateX(self, angle) | Rotates the point around the X axis by the given angle in degrees. | 1.860337 | 1.74463 | 1.066322 |
x1 = normalize(x1)
y1 = normalize(y1)
x2 = normalize(x2)
y2 = normalize(y2)
xdiff = max(x1, x2) - min(x1, x2)
ydiff = max(y1, y2) - min(y1, y2)
xdir = 1 if x1 <= x2 else -1
ydir = 1 if y1 <= y2 else -1
r = max(xdiff, ydiff)
for i in range(r+1):
x = x1
y =... | def line(x1, y1, x2, y2) | Returns the coords of the line between (x1, y1), (x2, y2)
:param x1: x coordinate of the startpoint
:param y1: y coordinate of the startpoint
:param x2: x coordinate of the endpoint
:param y2: y coordinate of the endpoint | 1.882231 | 1.90358 | 0.988785 |
# python2 unicode curses fix
if not IS_PY3:
import locale
locale.setlocale(locale.LC_ALL, "")
def animation(stdscr):
for frame in fn(*args, **kwargs):
for x,y in frame:
canvas.set(x,y)
f = canvas.frame()
stdscr.addstr(0, 0,... | def animate(canvas, fn, delay=1./24, *args, **kwargs) | Animation automation function
:param canvas: :class:`Canvas` object
:param fn: Callable. Frame coord generator
:param delay: Float. Delay between frames.
:param *args, **kwargs: optional fn parameters | 4.159452 | 4.412209 | 0.942714 |
x = normalize(x)
y = normalize(y)
col, row = get_pos(x, y)
if type(self.chars[row][col]) != int:
return
self.chars[row][col] |= pixel_map[y % 4][x % 2] | def set(self, x, y) | Set a pixel of the :class:`Canvas` object.
:param x: x coordinate of the pixel
:param y: y coordinate of the pixel | 5.055282 | 5.971509 | 0.846567 |
x = normalize(x)
y = normalize(y)
col, row = get_pos(x, y)
if type(self.chars[row][col]) == int:
self.chars[row][col] &= ~pixel_map[y % 4][x % 2]
if type(self.chars[row][col]) != int or self.chars[row][col] == 0:
del(self.chars[row][col])
... | def unset(self, x, y) | Unset a pixel of the :class:`Canvas` object.
:param x: x coordinate of the pixel
:param y: y coordinate of the pixel | 3.255984 | 3.619514 | 0.899564 |
col, row = get_pos(x, y)
for i,c in enumerate(text):
self.chars[row][col+i] = c | def set_text(self, x, y, text) | Set text to the given coords.
:param x: x coordinate of the text start position
:param y: y coordinate of the text start position | 5.026634 | 7.491354 | 0.670991 |
x = normalize(x)
y = normalize(y)
dot_index = pixel_map[y % 4][x % 2]
col, row = get_pos(x, y)
char = self.chars.get(row, {}).get(col)
if not char:
return False
if type(char) != int:
return True
return bool(char & dot_in... | def get(self, x, y) | Get the state of a pixel. Returns bool.
:param x: x coordinate of the pixel
:param y: y coordinate of the pixel | 5.367524 | 5.801852 | 0.92514 |
if not self.chars.keys():
return []
minrow = min_y // 4 if min_y != None else min(self.chars.keys())
maxrow = (max_y - 1) // 4 if max_y != None else max(self.chars.keys())
mincol = min_x // 2 if min_x != None else min(min(x.keys()) for x in self.chars.values())
... | def rows(self, min_x=None, min_y=None, max_x=None, max_y=None) | Returns a list of the current :class:`Canvas` object lines.
:param min_x: (optional) minimum x coordinate of the canvas
:param min_y: (optional) minimum y coordinate of the canvas
:param max_x: (optional) maximum x coordinate of the canvas
:param max_y: (optional) maximum y coordinate o... | 2.079926 | 2.120584 | 0.980827 |
ret = self.line_ending.join(self.rows(min_x, min_y, max_x, max_y))
if IS_PY3:
return ret
return ret.encode('utf-8') | def frame(self, min_x=None, min_y=None, max_x=None, max_y=None) | String representation of the current :class:`Canvas` object pixels.
:param min_x: (optional) minimum x coordinate of the canvas
:param min_y: (optional) minimum y coordinate of the canvas
:param max_x: (optional) maximum x coordinate of the canvas
:param max_y: (optional) maximum y coor... | 5.586472 | 6.443806 | 0.866952 |
x = self.pos_x + math.cos(math.radians(self.rotation)) * step
y = self.pos_y + math.sin(math.radians(self.rotation)) * step
prev_brush_state = self.brush_on
self.brush_on = True
self.move(x, y)
self.brush_on = prev_brush_state | def forward(self, step) | Move the turtle forward.
:param step: Integer. Distance to move forward. | 3.018642 | 2.687401 | 1.123257 |
if self.brush_on:
for lx, ly in line(self.pos_x, self.pos_y, x, y):
self.set(lx, ly)
self.pos_x = x
self.pos_y = y | def move(self, x, y) | Move the turtle to a coordinate.
:param x: x coordinate
:param y: y coordinate | 3.5738 | 4.268221 | 0.837304 |
# Make a copy of the Segments class
url_class = type(Segments.__name__, Segments.__bases__,
dict(Segments.__dict__))
segments = [] if segments is None else segments
defaults = [] if defaults is None else defaults
# For each segment attach a property capable of getting and s... | def URL(base, path, segments=None, defaults=None) | URL segment handler capable of getting and setting segments by name. The
URL is constructed by joining base, path and segments.
For each segment a property capable of getting and setting that segment is
created dynamically. | 4.064216 | 4.022337 | 1.010411 |
return property(
fget=lambda x: cls._get_segment(x, segment),
fset=lambda x, v: cls._set_segment(x, segment, v),
) | def _segment(cls, segment) | Returns a property capable of setting and getting a segment. | 3.072654 | 2.414181 | 1.272752 |
@wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if args or kwargs:
return self
else:
return result
return wrapper | def self_if_parameters(func) | If any parameter is given, the method's binded object is returned after
executing the function. Else the function's result is returned. | 2.14435 | 2.066903 | 1.03747 |
request = get(str(self.url), headers={'User-Agent' : "Magic Browser","origin_req_host" : "thepiratebay.se"})
root = html.fromstring(request.text)
items = [self._build_torrent(row) for row in
self._get_torrent_rows(root)]
for item in items:
yield item | def items(self) | Request URL and parse response. Yield a ``Torrent`` for every torrent
on page. | 6.274617 | 5.056051 | 1.241012 |
# Scrape, strip and build!!!
cols = row.findall('.//td') # split the row into it's columns
# this column contains the categories
[category, sub_category] = [c.text for c in cols[0].findall('.//a')]
# this column with all important info
links = cols[1].findall(... | def _build_torrent(self, row) | Builds and returns a Torrent object for the given parsed row. | 3.615576 | 3.581704 | 1.009457 |
if self._multipage:
while True:
# Pool for more torrents
items = super(Paginated, self).items()
# Stop if no more torrents
first = next(items, None)
if first is None:
raise StopIteration()
... | def items(self) | Request URL and parse response. Yield a ``Torrent`` for every torrent
on page. If in multipage mode, Torrents from next pages are
automatically chained. | 4.852947 | 3.815007 | 1.272068 |
if number is None:
return int(self.url.page)
self.url.page = str(number) | def page(self, number=None) | If page is given, modify the URL correspondingly, return the current
page otherwise. | 5.011878 | 3.983398 | 1.258192 |
if query is None:
return self.url.query
self.url.query = query | def query(self, query=None) | If query is given, modify the URL correspondingly, return the current
query otherwise. | 5.413692 | 3.447447 | 1.570348 |
if order is None:
return int(self.url.order)
self.url.order = str(order) | def order(self, order=None) | If order is given, modify the URL correspondingly, return the current
order otherwise. | 5.320995 | 3.990241 | 1.333502 |
if category is None:
return int(self.url.category)
self.url.category = str(category) | def category(self, category=None) | If category is given, modify the URL correspondingly, return the
current category otherwise. | 5.470913 | 4.299882 | 1.27234 |
search = Search(self.base_url, query, page, order, category)
if multipage:
search.multipage()
return search | def search(self, query, page=0, order=7, category=0, multipage=False) | Searches TPB for query and returns a list of paginated Torrents capable
of changing query, categories and orders. | 3.932679 | 3.999143 | 0.98338 |
timestamp, current = self._created
if timestamp.endswith('ago'):
quantity, kind, ago = timestamp.split()
quantity = int(quantity)
if 'sec' in kind:
current -= quantity
elif 'min' in kind:
current -= quantity * 60
... | def created(self) | Attempt to parse the human readable torrent creation datetime. | 3.428264 | 3.172923 | 1.080475 |
print('Title: %s' % self.title)
print('URL: %s' % self.url)
print('Category: %s' % self.category)
print('Sub-Category: %s' % self.sub_category)
print('Magnet Link: %s' % self.magnet_link)
print('Torrent Link: %s' % self.torrent_link)
print('Uploaded: %s' ... | def print_torrent(self) | Print the details of a torrent | 1.851767 | 1.846347 | 1.002935 |
option = '--testrunner='
for arg in argv[2:]:
if arg.startswith(option):
self.test_runner = arg[len(option):]
break
super(Command, self).run_from_argv(argv) | def run_from_argv(self, argv) | Pre-parse the command line to extract the value of the --testrunner
option. This allows a test runner to define additional command line
arguments. | 3.371159 | 2.740527 | 1.230114 |
return encode(color, readline=readline) + content + encode(DEFAULT, readline=readline) | def foreground(color, content, readline=False) | Color the text of the content
:param color: pick a constant, any constant
:type color: int
:param content: Whatever you want to say...
:type content: unicode
:return: ansi string
:rtype: unicode | 6.644263 | 13.438401 | 0.494424 |
color = 16 + 36 * red + 6 * green + blue
return encode('38;5;' + str(color)) + content + encode(DEFAULT) | def rgb(red, green, blue, content) | Colors a content using rgb for h
:param red: [0-5]
:type red: int
:param green: [0-5]
:type green: int
:param blue: [0-5]
:type blue: int
:param content: Whatever you want to say...
:type content: unicode
:return: ansi string
:rtype: unicode | 5.530678 | 6.355865 | 0.870169 |
if identifier is None:
return None
encodable = identifier.encode("utf-8", errors).decode("utf-8")
nul_index = encodable.find("\x00")
if nul_index >= 0:
error = UnicodeEncodeError(
"NUL-terminated utf-8",
encodable,
... | def quote(self, identifier, errors="strict") | https://stackoverflow.com/questions/6514274/how-do-you-escape-strings-for-sqlite-table-column-names-in-python
:param identifier:
:param errors:
:return: | 2.910747 | 2.852193 | 1.020529 |
encoded = OrderedDict()
if self.multiprocessing:
pool = multiprocessing.Pool(self.workers)
results = []
for encoder in self.encoders:
results.append((encoder, pool.apply_async(self.transform, (encoder, data))))
for encoder, result... | def encode_x(self, data) | :param data: unencoded input dataframe
:return: a dict with encoded values | 4.841565 | 4.880599 | 0.992002 |
'''
Creates an object or returns the object if exists
credit to Kevin @ StackOverflow
from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
'''
session = Session()
instance = session.query(cls).filter_by(**kwa... | def get_or_create(cls, **kwargs) | Creates an object or returns the object if exists
credit to Kevin @ StackOverflow
from: http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create | 3.897383 | 1.727371 | 2.256251 |
self._data = self.get_data()
key_list = self.key()
values_list = self.values()
result = {}
for column in values_list:
key_prefix = self.cache_key_prefix() + "#" + column
self._data['cache_key'] = self._data[key_list].apply(lambda xdf: key_prefix +... | def _features_as_kv(self) | Return features row as kv pairs so that they can be stored in memcache or redis and
used at serving layer
:return: a nested hash for each column | 4.251454 | 4.115005 | 1.033159 |
keys = self.key
columns = self.values
if not self._data:
self._data = self.get_data()
for column in columns:
key_prefix = self.cache_key_prefix() + "#" + column
self._data['cache_key'] = self._data[keys].apply(lambda xdf: key_prefix + "=" + '... | def generate_row_keys(self) | Method for generating key features at serving time or prediction time
:param data: Pass in the data that is necessary for generating the keys
Example :
Feature : User warehouse searches and conversions
Keys will be of the form 'user_id#warehouse_id#searches=23811676#3'
... | 5.466726 | 5.080326 | 1.076058 |
data = self._features_as_kv()
for key in data.keys():
cache.batch_set(data[key]) | def distribute(self, cache) | Sync features to a key value compliant cache. Should adhere to cache protocol
:param cache:
:return: None | 14.168427 | 9.13983 | 1.550185 |
stack = inspect.stack()
height = min(len(stack) - 1, height)
caller = stack[height]
scope = caller[0].f_globals
path = scope['__name__']
if path == '__main__':
path = scope['__package__'] or os.path.basename(sys.argv[0])
return logging.getLogger(path) | def calling_logger(height=1) | Obtain a logger for the calling module.
Uses the inspect module to find the name of the calling function and its
position in the module hierarchy. With the optional height argument, logs
for caller's caller, and so forth.
see: http://stackoverflow.com/a/900404/48251 | 3.074442 | 3.030206 | 1.014598 |
self.mean = numpy.mean(y)
return {} | def fit(self, x, y, **kwargs) | Fit a naive model
:param x: Predictors to use for fitting the data (this will not be used in naive models)
:param y: Outcome | 18.972694 | 31.389153 | 0.604435 |
if self.mean > 0.5:
return numpy.ones(dataframe.shape[0])
else:
return numpy.zeros(dataframe.shape[0]) | def predict(self, dataframe) | See :ref:`Base Estimator for Naive _naive_base_predict` | 3.443158 | 3.148055 | 1.093741 |
ret = numpy.ones((dataframe.shape[0], 2))
ret[:, 0] = (1 - self.mean)
ret[:, 1] = self.mean
return ret | def predict_proba(self, dataframe) | Predict probabilities using the model
:param dataframe: Dataframe against which to make predictions | 3.541568 | 4.356398 | 0.812958 |
if series.dtype == numpy.object:
return series
return series.fillna(self.missing_value + addition).astype(self.dtype) | def fillna(self, series, addition=0) | Fills with encoder specific default values.
:param data: examined to determine defaults
:param addition: uniquely identify this set of fillnas if necessary
:return: filled data | 6.084302 | 7.003047 | 0.868808 |
with timer('transform %s' % self.name, logging.DEBUG):
transformed = super(Token, self).transform(self.tokenize(data))
return transformed.reshape((len(data), self.sequence_length)) | def transform(self, data) | :param data: DataFrame with column to encode
:return: encoded Series | 6.497202 | 8.487021 | 0.765546 |
with timer('tokenize %s' % self.name, logging.DEBUG):
cleaned = self.series(data).str.replace(Token.PUNCTUATION_FILTER, ' ')
lowered = cleaned.str.lower()
dataframe = lowered.str.split(expand=True)
if fit and self.sequence_length is None:
... | def tokenize(self, data, fit=False) | :param data: a dataframe containing a column to be tokenized
:param fit: if True, self.sequence_length will exactly accomodate the largest tokenized sequence length
:return: 1D array of tokens with length = rows * sequence_length | 4.222474 | 4.292667 | 0.983648 |
with timer('transform %s' % self.name, logging.DEBUG):
transformed = super(NestedUnique, self).transform(self.unnest(data))
return transformed.reshape((len(data), self.sequence_length)) | def transform(self, data) | :param data: DataFrame with column to encode
:return: encoded Series | 8.06569 | 9.898925 | 0.814805 |
with timer('unnest %s' % self.name, logging.DEBUG):
raw = self.series(data)
# lengths of every sequence
lengths = [0 if x is None or (isinstance(x, float) and numpy.isnan(x)) else len(x) for x in raw.values]
if fit and self.sequence_length is None:
... | def unnest(self, data, fit=False) | :param data: a dataframe containing a column to be unnested
:param fit: if True, self.sequence_length will exactly accomodate the largest sequence length
:return: 1D array of values with length = rows * sequence_length | 2.937111 | 2.887043 | 1.017342 |
params = locals()
params.pop('self')
self.fitting = lore.metadata.Fitting.create(
model=self.name,
custom_data=custom_data,
snapshot=lore.metadata.Snapshot(pipeline=self.pipeline.name,
head=str(self.pipelin... | def hyper_parameter_search(
self,
param_distributions,
n_iter=10,
scoring=None,
fit_params={},
n_jobs=1,
iid=True,
refit=True,
cv=None,
verbose=0,
pre_dispatch='2*njobs',
rando... | Random search hyper params | 2.371408 | 2.348659 | 1.009686 |
global INSTALLED_PACKAGES, _new_requirements
if _new_requirements:
INSTALLED_PACKAGES = None
set_installed_packages()
if not INSTALLED_PACKAGES:
return
if not isinstance(packages, list):
packages = [packages]
missing = []
for package in packages:
name... | def require(packages) | Ensures that a pypi package has been installed into the App's python environment.
If not, the package will be installed and your env will be rebooted.
Example:
::
lore.env.require('pandas')
# -> pandas is required. Dependencies added to requirements.txt
:param packages: re... | 4.104123 | 3.766817 | 1.089547 |
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) | def launched() | Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool | 5.602112 | 6.220669 | 0.900564 |
if not os.path.exists(os.path.join(ROOT, APP, '__init__.py')):
message = ansi.error() + ' Python module not found.'
if os.environ.get('LORE_APP') is None:
message += ' $LORE_APP is not set. Should it be different than "%s"?' % APP
else:
message += ' $LORE_APP is ... | def validate() | Display error messages and exit if no lore environment can be found. | 5.016189 | 4.515953 | 1.110771 |
if launched():
check_version()
os.chdir(ROOT)
return
if not os.path.exists(BIN_LORE):
missing = ' %s virtualenv is missing.' % APP
if '--launched' in sys.argv:
sys.exit(ansi.error() + missing + ' Please check for errors during:\n $ lore install\n')
... | def launch() | Ensure that python is running from the Lore virtualenv past this point. | 11.294596 | 9.826003 | 1.14946 |
args = list(sys.argv) + list(args)
if args[0] == 'python' or not args[0]:
args[0] = BIN_PYTHON
elif os.path.basename(sys.argv[0]) in ['lore', 'lore.exe']:
args[0] = BIN_LORE
try:
os.execv(args[0], args)
except Exception as e:
if args[0] == BIN_LORE and args[1] ==... | def reboot(*args) | Reboot python in the Lore virtualenv | 4.556444 | 4.071266 | 1.119171 |
if sys.version_info[0:3] == PYTHON_VERSION_INFO[0:3]:
return
sys.exit(
ansi.error() + ' your virtual env points to the wrong python version. '
'This is likely because you used a python installer that clobbered '
'the system installation, which ... | def check_version() | Sanity check version information for corrupt virtualenv symlinks | 12.833595 | 10.793454 | 1.189017 |
if not os.path.exists(REQUIREMENTS):
sys.exit(
ansi.error() + ' %s is missing. Please check it in.' % ansi.underline(REQUIREMENTS)
)
with open(REQUIREMENTS, 'r', encoding='utf-8') as f:
dependencies = f.readlines()
vcs = [d for d in dependencies if re.match(r'^(-e ... | def check_requirements() | Make sure all listed packages from requirements.txt have been installed into the virtualenv at boot. | 4.299637 | 4.23263 | 1.015831 |
if configparser is None:
return None
# Check for env specific configs first
if os.path.exists(os.path.join(ROOT, 'config', NAME, path)):
path = os.path.join(ROOT, 'config', NAME, path)
else:
path = os.path.join(ROOT, 'config', path)
if not os.path.isfile(path):
... | def get_config(path) | Load a config from disk
:param path: target config
:type path: unicode
:return:
:rtype: configparser.Config | 2.601712 | 2.861801 | 0.909117 |
version = None
if os.path.exists(path):
version = open(path, 'r', encoding='utf-8').read().strip()
if version:
return re.sub(r'^python-', '', version)
return version | def read_version(path) | Attempts to read a python version string from a runtime.txt file
:param path: to source of the string
:return: python version
:rtype: unicode or None | 3.65064 | 3.26237 | 1.119015 |
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
if LIB not in sys.path:
sys.path.insert(0, LIB) | def extend_path() | Adds Lore App modules to the path to making importing easy, including :any:`LIB` | 2.75078 | 2.394759 | 1.148667 |
if not os.path.exists(ENV_FILE):
return
for line in open(ENV_FILE, 'r'):
line = line.strip()
if not line:
continue
name, value = line.split('=', 1)
if not name or not value or name.startswith('#') or len(name) == 0 or name.isspace():
continue... | def load_env_file() | Adds environment variables defined in :any:`ENV_FILE` to os.environ.
Supports bash style comments and variable interpolation. | 2.36929 | 2.353518 | 1.006701 |
for var in glob.glob(os.path.join(ENV_DIRECTORY, '*')):
if os.path.isfile(var):
os.environ[os.path.basename(var)] = os.path.expandvars(open(var, encoding='utf-8').read()) | def load_env_directory() | Adds environment variables defined in :any:`ENV_DIRECTORY` to os.environ.
Each file will be added to os.environ via filename = contents.
Supports bash style comments and variable interpolation. | 2.787018 | 2.374084 | 1.173934 |
global INSTALLED_PACKAGES, REQUIRED_VERSION
if INSTALLED_PACKAGES:
return
if os.path.exists(BIN_PYTHON):
pip = subprocess.Popen(
(BIN_PYTHON, '-m', 'pip', 'freeze'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
(stdout, stderr) = ... | def set_installed_packages() | Idempotently caches the list of packages installed in the virtualenv.
Can be run safely before the virtualenv is created, and will be rerun
afterwards. | 3.053743 | 3.058672 | 0.998388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.