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 RocketMissingParamException('roomId or roomName required')
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_screen = self._yield_warning_screen(seconds) for elapsed_time in warning_screen: if self._should_stop_waiting(**kw): break try: try: self._process_packets() except TimeoutError: pass except KeyboardInterrupt: self._close() raise except ConnectionError as e: self._opened = False try: warning = Exception('[connection error] %s' % e) warning_screen.throw(warning) except StopIteration: self._warn(warning) try: namespace = self.get_namespace() namespace._find_packet_callback('disconnect')() except PacketError: pass self._heartbeat_thread.relax() self._transport.set_timeout()
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 = y1 if ydiff: y += (float(i) * ydiff) / r * ydir if xdiff: x += (float(i) * xdiff) / r * xdir yield (x, 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, '{0}\n'.format(f)) stdscr.refresh() if delay: sleep(delay) canvas.clear() curses.wrapper(animation)
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]) if not self.chars.get(row): del(self.chars[row])
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_index)
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()) maxcol = (max_x - 1) // 2 if max_x != None else max(max(x.keys()) for x in self.chars.values()) ret = [] for rownum in range(minrow, maxrow+1): if not rownum in self.chars: ret.append('') continue maxcol = (max_x - 1) // 2 if max_x != None else max(self.chars[rownum].keys()) row = [] for x in range(mincol, maxcol+1): char = self.chars[rownum].get(x) if not char: row.append(unichr(braille_char_offset)) elif type(char) != int: row.append(char) else: row.append(unichr(braille_char_offset+char)) ret.append(''.join(row)) return ret
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 of the canvas
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 coordinate of the canvas
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 setting it for segment in segments: setattr(url_class, segment, url_class._segment(segment)) # Instantiate the class with the actual parameters return url_class(base, path, segments, defaults)
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('.//a') # get 4 a tags from this columns title = unicode(links[0].text) url = self.url.build().path(links[0].get('href')) magnet_link = links[1].get('href') # the magnet download link try: torrent_link = links[2].get('href') # the torrent download link if not torrent_link.endswith('.torrent'): torrent_link = None except IndexError: torrent_link = None comments = 0 has_cover = 'No' images = cols[1].findall('.//img') for image in images: image_title = image.get('title') if image_title is None: continue if "comments" in image_title: comments = int(image_title.split(" ")[3]) if "cover" in image_title: has_cover = 'Yes' user_status = "MEMBER" if links[-2].get('href').startswith("/user/"): user_status = links[-2].find('.//img').get('title') meta_col = cols[1].find('.//font').text_content() # don't need user match = self._meta.match(meta_col) created = match.groups()[0].replace('\xa0', ' ') size = match.groups()[1].replace('\xa0', ' ') user = match.groups()[2] # uploaded by user # last 2 columns for seeders and leechers seeders = int(cols[2].text) leechers = int(cols[3].text) t = Torrent(title, url, category, sub_category, magnet_link, torrent_link, comments, has_cover, user_status, created, size, user, seeders, leechers) return t
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() # Yield them if not else: yield first for item in items: yield item # Go to the next page self.next() else: for item in super(Paginated, self).items(): yield item
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 elif 'hour' in kind: current -= quantity * 60 * 60 return datetime.datetime.fromtimestamp(current) current = datetime.datetime.fromtimestamp(current) timestamp = timestamp.replace( 'Y-day', str(current.date() - datetime.timedelta(days=1))) timestamp = timestamp.replace('Today', current.date().isoformat()) try: return dateutil.parser.parse(timestamp) except: return current
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' % self.created) print('Comments: %d' % self.comments) print('Has Cover Image: %s' % self.has_cover) print('User Status: %s' % self.user_status) print('Size: %s' % self.size) print('User: %s' % self.user) print('Seeders: %d' % self.seeders) print('Leechers: %d' % self.leechers)
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, nul_index, nul_index + 1, "NUL not allowed" ) error_handler = codecs.lookup_error(errors) replacement, _ = error_handler(error) encodable = encodable.replace("\x00", replacement) return "\"" + encodable.replace("\"", "\"\"") + "\""
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 in results: self.merged_transformed(encoded, encoder, result.get()) else: for encoder in self.encoders: self.merged_transformed(encoded, encoder, self.transform(encoder, data), append_twin=False) if encoder.twin: self.merged_transformed(encoded, encoder, self.transform(encoder, data, append_twin = True), append_twin=True) for column in self.index: encoded[column] = self.read_column(data, column) # Using a DataFrame as a container temporarily requires double the memory, # as pandas copies all data on __init__. This is justified by having a # type supported by all dependent libraries (heterogeneous dict is not) dataframe = pandas.DataFrame(encoded) if self.index: dataframe.set_index(self.index) return dataframe
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(**kwargs).first() session.close() if not instance: self = cls(**kwargs) self.save() else: self = instance return self
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 + "=" + '#'.join(xdf.astype(str).values), axis=1) result[column] = dict(zip(self._data.cache_key.values, self._data[column].values)) return result
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 + "=" + '#'.join(xdf.astype(str).values), axis=1) return list(self._data['cache_key'].values)
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' Keys will be of the form 'user_id#warehouse_id#conversions=23811676#3' data Frame should have values for all the columns as feature_key in this case ['user_id','warehouse_id'] :return:
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: self.sequence_length = len(dataframe.columns) while len(dataframe.columns) < self.sequence_length: column = len(dataframe.columns) logger.warning('No string has %i tokens, adding blank column %i' % (self.sequence_length, column)) dataframe[column] = float('nan') return pandas.DataFrame({self.column: dataframe.loc[:,0:self.sequence_length - 1].values.flatten()})
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: self.sequence_length = numpy.max(lengths) # Make them all the same size def fill_x(x, length): x_new = numpy.empty(length, dtype='float') x_new[:] = numpy.nan if x is None or (isinstance(x, float) and numpy.isnan(x)): return x_new fill_length = min(len(x), length) x_new[0:fill_length] = x[0:fill_length] return x_new same_size = [fill_x(x, self.sequence_length) for x in raw.values] # Flatten flattened = [item for sublist in same_size for item in sublist] return pandas.DataFrame({self.column: flattened})
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.pipeline.training_data.head(2)), tail=str(self.pipeline.training_data.tail(2)) ) ) result = RandomizedSearchCV( self.estimator, param_distributions, n_iter=n_iter, scoring=scoring, n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose, pre_dispatch=pre_dispatch, random_state=random_state, error_score=error_score, return_train_score=return_train_score ).fit( self.pipeline.encoded_training_data.x, y=self.pipeline.encoded_training_data.y, validation_x=self.pipeline.encoded_validation_data.x, validation_y=self.pipeline.encoded_validation_data.y, **fit_params ) self.estimator = result.best_estimator_ self.stats = {} self.estimator_kwargs = self.estimator.__getstate__() if test: self.stats['test'] = self.evaluate(self.pipeline.test_data) if score: self.stats['score'] = self.score(self.pipeline.test_data) self.complete_fitting() if save: self.save() return result
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', random_state=None, error_score='raise', return_train_score=True, test=True, score=True, save=True, custom_data=None )
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 = re.split(r'[!<>=]', package)[0].lower() if name not in INSTALLED_PACKAGES: print(ansi.info() + ' %s is required.' % package) missing += [package] if missing: mode = 'a' if os.path.exists(REQUIREMENTS) else 'w' with open(REQUIREMENTS, mode) as requirements: requirements.write('\n' + '\n'.join(missing) + '\n') print(ansi.info() + ' Dependencies added to requirements.txt. Rebooting.') _new_requirements = True import lore.__main__ lore.__main__.install(None, None) reboot('--env-checked')
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: requirements.txt style name and versions of packages :type packages: [unicode]
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 set to "%s". Should it be different?' % APP sys.exit(message) if exists(): return if len(sys.argv) > 1: command = sys.argv[1] else: command = 'lore' sys.exit( ansi.error() + ' %s is only available in lore ' 'app directories (missing %s)' % ( ansi.bold(command), ansi.underline(VERSION_PATH) ) )
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') else: print(ansi.warning() + missing) import lore.__main__ lore.__main__.install(None, None) reboot('--env-launched')
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] == 'console' and JUPYTER_KERNEL_PATH: print(ansi.error() + ' Your jupyter kernel may be corrupt. Please remove it so lore can reinstall:\n $ rm ' + JUPYTER_KERNEL_PATH) raise e
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 breaks virtualenv creation. ' 'To fix, check this symlink, and delete the installation of python ' 'that it is brokenly pointing to, then delete the virtual env itself ' 'and rerun lore install: ' + os.linesep + os.linesep + BIN_PYTHON + os.linesep )
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 )?(git|svn|hg|bzr).*', d)] dependencies = list(set(dependencies) - set(vcs)) missing = [] try: pkg_resources.require(dependencies) except ( pkg_resources.ContextualVersionConflict, pkg_resources.DistributionNotFound, pkg_resources.VersionConflict ) as error: missing.append(str(error)) except pkg_resources.RequirementParseError: pass if missing: missing = ' missing requirement:\n ' + os.linesep.join(missing) if '--env-checked' in sys.argv: sys.exit(ansi.error() + missing + '\nRequirement installation failure, please check for errors in:\n $ lore install\n') else: print(ansi.warning() + missing) import lore.__main__ lore.__main__.install_requirements(None) reboot('--env-checked')
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): return None conf = open(path, 'rt').read() conf = os.path.expandvars(conf) config = configparser.SafeConfigParser() if sys.version_info[0] == 2: from io import StringIO config.readfp(StringIO(unicode(conf))) else: config.read_string(conf) return config
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 if re.match(r'^(["\']).*\1$', value): if value.startswith('"'): value = os.path.expandvars(value) value = value[1:-1] os.environ[name] = value
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) = pip.communicate() pip.wait() INSTALLED_PACKAGES = [r.decode().split('==')[0].lower() for r in stdout.split()] REQUIRED_VERSION = next((package for package in INSTALLED_PACKAGES if re.match(r'^lore[!<>=]', package)), None) if REQUIRED_VERSION: REQUIRED_VERSION = re.split(r'[!<>=]', REQUIRED_VERSION)[-1]
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