Search is not available for this dataset
text
stringlengths
75
104k
def convert_to_this_nbformat(nb, orig_version=2, orig_minor=0): """Convert a notebook to the v3 format. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. orig_version : int The original version of the notebook to convert. orig_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). """ if orig_version == 1: nb = v2.convert_to_this_nbformat(nb) orig_version = 2 if orig_version == 2: # Mark the original nbformat so consumers know it has been converted. nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor nb.orig_nbformat = 2 return nb elif orig_version == 3: if orig_minor != nbformat_minor: nb.orig_nbformat_minor = orig_minor nb.nbformat_minor = nbformat_minor return nb else: raise ValueError('Cannot convert a notebook from v%s to v3' % orig_version)
def hex_to_rgb(color): """Convert a hex color to rgb integer tuple.""" if color.startswith('#'): color = color[1:] if len(color) == 3: color = ''.join([c*2 for c in color]) if len(color) != 6: return False try: r = int(color[:2],16) g = int(color[2:4],16) b = int(color[4:],16) except ValueError: return False else: return r,g,b
def get_colors(stylename): """Construct the keys to be used building the base stylesheet from a templatee.""" style = get_style_by_name(stylename) fgcolor = style.style_for_token(Token.Text)['color'] or '' if len(fgcolor) in (3,6): # could be 'abcdef' or 'ace' hex, which needs '#' prefix try: int(fgcolor, 16) except TypeError: pass else: fgcolor = "#"+fgcolor return dict( bgcolor = style.background_color, select = style.highlight_color, fgcolor = fgcolor )
def sheet_from_template(name, colors='lightbg'): """Use one of the base templates, and set bg/fg/select colors.""" colors = colors.lower() if colors=='lightbg': return default_light_style_template%get_colors(name) elif colors=='linux': return default_dark_style_template%get_colors(name) elif colors=='nocolor': return default_bw_style_sheet else: raise KeyError("No such color scheme: %s"%colors)
def get_font(family, fallback=None): """Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallback font. Parameters ---------- family : str A font name. fallback : str A font name. Returns ------- font : QFont object """ font = QtGui.QFont(family) # Check whether we got what we wanted using QFontInfo, since exactMatch() # is overly strict and returns false in too many cases. font_info = QtGui.QFontInfo(font) if fallback is not None and font_info.family() != family: font = QtGui.QFont(fallback) return font
def _handle_complete_reply(self, rep): """ Reimplemented to support IPython's improved completion machinery. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): matches = rep['content']['matches'] text = rep['content']['matched_text'] offset = len(text) # Clean up matches with period and path separators if the matched # text has not been transformed. This is done by truncating all # but the last component and then suitably decreasing the offset # between the current cursor position and the start of completion. if len(matches) > 1 and matches[0][:offset] == text: parts = re.split(r'[./\\]', text) sep_count = len(parts) - 1 if sep_count: chop_length = sum(map(len, parts[:sep_count])) + sep_count matches = [ match[chop_length:] for match in matches ] offset -= chop_length # Move the cursor to the start of the match and complete. cursor.movePosition(QtGui.QTextCursor.Left, n=offset) self._complete_with_items(cursor, matches)
def _handle_execute_reply(self, msg): """ Reimplemented to support prompt requests. """ msg_id = msg['parent_header'].get('msg_id') info = self._request_info['execute'].get(msg_id) if info and info.kind == 'prompt': number = msg['content']['execution_count'] + 1 self._show_interpreter_prompt(number) self._request_info['execute'].pop(msg_id) else: super(IPythonWidget, self)._handle_execute_reply(msg)
def _handle_history_reply(self, msg): """ Implemented to handle history tail replies, which are only supported by the IPython kernel. """ content = msg['content'] if 'history' not in content: self.log.error("History request failed: %r"%content) if content.get('status', '') == 'aborted' and \ not self._retrying_history_request: # a *different* action caused this request to be aborted, so # we should try again. self.log.error("Retrying aborted history request") # prevent multiple retries of aborted requests: self._retrying_history_request = True # wait out the kernel's queue flush, which is currently timed at 0.1s time.sleep(0.25) self.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000) else: self._retrying_history_request = False return # reset retry flag self._retrying_history_request = False history_items = content['history'] self.log.debug("Received history reply with %i entries", len(history_items)) items = [] last_cell = u"" for _, _, cell in history_items: cell = cell.rstrip() if cell != last_cell: items.append(cell) last_cell = cell self._set_history(items)
def _handle_pyout(self, msg): """ Reimplemented for IPython-style "display hook". """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if data.has_key('text/html'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) html = data['text/html'] self._append_plain_text('\n', True) self._append_html(html + self.output_sep2, True) elif data.has_key('text/plain'): self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) text = data['text/plain'] # If the repr is multiline, make sure we start on a new line, # so that its lines are aligned. if "\n" in text and not self.output_sep.endswith("\n"): self._append_plain_text('\n', True) self._append_plain_text(text + self.output_sep2, True)
def _handle_display_data(self, msg): """ The base handler for the ``display_data`` message. """ self.log.debug("display: %s", msg.get('content', '')) # For now, we don't display data from other frontends, but we # eventually will as this allows all frontends to monitor the display # data. But we need to figure out how to handle this in the GUI. if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] # In the regular IPythonWidget, we simply print the plain text # representation. if data.has_key('text/html'): html = data['text/html'] self._append_html(html, True) elif data.has_key('text/plain'): text = data['text/plain'] self._append_plain_text(text, True) # This newline seems to be needed for text and html output. self._append_plain_text(u'\n', True)
def _started_channels(self): """Reimplemented to make a history request and load %guiref.""" super(IPythonWidget, self)._started_channels() self._load_guiref_magic() self.kernel_manager.shell_channel.history(hist_access_type='tail', n=1000)
def execute_file(self, path, hidden=False): """ Reimplemented to use the 'run' magic. """ # Use forward slashes on Windows to avoid escaping each separator. if sys.platform == 'win32': path = os.path.normpath(path).replace('\\', '/') # Perhaps we should not be using %run directly, but while we # are, it is necessary to quote or escape filenames containing spaces # or quotes. # In earlier code here, to minimize escaping, we sometimes quoted the # filename with single quotes. But to do this, this code must be # platform-aware, because run uses shlex rather than python string # parsing, so that: # * In Win: single quotes can be used in the filename without quoting, # and we cannot use single quotes to quote the filename. # * In *nix: we can escape double quotes in a double quoted filename, # but can't escape single quotes in a single quoted filename. # So to keep this code non-platform-specific and simple, we now only # use double quotes to quote filenames, and escape when needed: if ' ' in path or "'" in path or '"' in path: path = '"%s"' % path.replace('"', '\\"') self.execute('%%run %s' % path, hidden=hidden)
def _complete(self): """ Reimplemented to support IPython's improved completion machinery. """ # We let the kernel split the input line, so we *always* send an empty # text field. Readline-based frontends do get a real text field which # they can use. text = '' # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( text, # text self._get_input_buffer_cursor_line(), # line self._get_input_buffer_cursor_column(), # cursor_pos self.input_buffer) # block pos = self._get_cursor().position() info = self._CompletionRequest(msg_id, pos) self._request_info['complete'] = info
def _process_execute_error(self, msg): """ Reimplemented for IPython-style traceback formatting. """ content = msg['content'] traceback = '\n'.join(content['traceback']) + '\n' if False: # FIXME: For now, tracebacks come as plain text, so we can't use # the html renderer yet. Once we refactor ultratb to produce # properly styled tracebacks, this branch should be the default traceback = traceback.replace(' ', '&nbsp;') traceback = traceback.replace('\n', '<br/>') ename = content['ename'] ename_styled = '<span class="error">%s</span>' % ename traceback = traceback.replace(ename, ename_styled) self._append_html(traceback) else: # This is the fallback for now, using plain text with ansi escapes self._append_plain_text(traceback)
def _process_execute_payload(self, item): """ Reimplemented to dispatch payloads to handler methods. """ handler = self._payload_handlers.get(item['source']) if handler is None: # We have no handler for this type of payload, simply ignore it return False else: handler(item) return True
def _show_interpreter_prompt(self, number=None): """ Reimplemented for IPython-style prompts. """ # If a number was not specified, make a prompt number request. if number is None: msg_id = self.kernel_manager.shell_channel.execute('', silent=True) info = self._ExecutionRequest(msg_id, 'prompt') self._request_info['execute'][msg_id] = info return # Show a new prompt and save information about it so that it can be # updated later if the prompt number turns out to be wrong. self._prompt_sep = self.input_sep self._show_prompt(self._make_in_prompt(number), html=True) block = self._control.document().lastBlock() length = len(self._prompt) self._previous_prompt_obj = self._PromptBlock(block, length, number) # Update continuation prompt to reflect (possibly) new prompt length. self._set_continuation_prompt( self._make_continuation_prompt(self._prompt), html=True)
def _show_interpreter_prompt_for_reply(self, msg): """ Reimplemented for IPython-style prompts. """ # Update the old prompt number if necessary. content = msg['content'] # abort replies do not have any keys: if content['status'] == 'aborted': if self._previous_prompt_obj: previous_prompt_number = self._previous_prompt_obj.number else: previous_prompt_number = 0 else: previous_prompt_number = content['execution_count'] if self._previous_prompt_obj and \ self._previous_prompt_obj.number != previous_prompt_number: block = self._previous_prompt_obj.block # Make sure the prompt block has not been erased. if block.isValid() and block.text(): # Remove the old prompt and insert a new prompt. cursor = QtGui.QTextCursor(block) cursor.movePosition(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, self._previous_prompt_obj.length) prompt = self._make_in_prompt(previous_prompt_number) self._prompt = self._insert_html_fetching_plain_text( cursor, prompt) # When the HTML is inserted, Qt blows away the syntax # highlighting for the line, so we need to rehighlight it. self._highlighter.rehighlightBlock(cursor.block()) self._previous_prompt_obj = None # Show a new prompt with the kernel's estimated prompt number. self._show_interpreter_prompt(previous_prompt_number + 1)
def set_default_style(self, colors='lightbg'): """ Sets the widget style to the class defaults. Parameters: ----------- colors : str, optional (default lightbg) Whether to use the default IPython light background or dark background or B&W style. """ colors = colors.lower() if colors=='lightbg': self.style_sheet = styles.default_light_style_sheet self.syntax_style = styles.default_light_syntax_style elif colors=='linux': self.style_sheet = styles.default_dark_style_sheet self.syntax_style = styles.default_dark_syntax_style elif colors=='nocolor': self.style_sheet = styles.default_bw_style_sheet self.syntax_style = styles.default_bw_syntax_style else: raise KeyError("No such color scheme: %s"%colors)
def _edit(self, filename, line=None): """ Opens a Python script for editing. Parameters: ----------- filename : str A path to a local system file. line : int, optional A line of interest in the file. """ if self.custom_edit: self.custom_edit_requested.emit(filename, line) elif not self.editor: self._append_plain_text('No default editor available.\n' 'Specify a GUI text editor in the `IPythonWidget.editor` ' 'configurable to enable the %edit magic') else: try: filename = '"%s"' % filename if line and self.editor_line: command = self.editor_line.format(filename=filename, line=line) else: try: command = self.editor.format() except KeyError: command = self.editor.format(filename=filename) else: command += ' ' + filename except KeyError: self._append_plain_text('Invalid editor command.\n') else: try: Popen(command, shell=True) except OSError: msg = 'Opening editor with command "%s" failed.\n' self._append_plain_text(msg % command)
def _make_in_prompt(self, number): """ Given a prompt number, returns an HTML In prompt. """ try: body = self.in_prompt % number except TypeError: # allow in_prompt to leave out number, e.g. '>>> ' body = self.in_prompt return '<span class="in-prompt">%s</span>' % body
def _make_continuation_prompt(self, prompt): """ Given a plain text version of an In prompt, returns an HTML continuation prompt. """ end_chars = '...: ' space_count = len(prompt.lstrip('\n')) - len(end_chars) body = '&nbsp;' * space_count + end_chars return '<span class="in-prompt">%s</span>' % body
def _style_sheet_changed(self): """ Set the style sheets of the underlying widgets. """ self.setStyleSheet(self.style_sheet) if self._control is not None: self._control.document().setDefaultStyleSheet(self.style_sheet) bg_color = self._control.palette().window().color() self._ansi_processor.set_background_color(bg_color) if self._page_control is not None: self._page_control.document().setDefaultStyleSheet(self.style_sheet)
def _syntax_style_changed(self): """ Set the style for the syntax highlighter. """ if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter.set_style(self.syntax_style) else: self._highlighter.set_style_sheet(self.style_sheet)
async def request(self, command: str, **kwargs) -> dict: """ Async co-routine to perform requests to a CloudStackAPI. The parameters needs to include the command string, which refers to the API to be called. In principle any available and future CloudStack API can be called. The `**kwargs` magic allows us to all add supported parameters to the given API call. A list of all available APIs can found at https://cloudstack.apache.org/api/apidocs-4.8/TOC_User.html :param command: Command string indicating the CloudStack API to be called. :type command: str :param kwargs: Parameters to be passed to the CloudStack API :return: Dictionary containing the decoded json reply of the CloudStack API :rtype: dict """ kwargs.update(dict(apikey=self.api_key, command=command, response='json')) if 'list' in command.lower(): # list APIs can be paginated, therefore include max_page_size and page parameter kwargs.update(dict(pagesize=self.max_page_size, page=1)) final_data = dict() while True: async with self.client_session.get(self.end_point, params=self._sign(kwargs)) as response: data = await self._handle_response(response=response, await_final_result='queryasyncjobresult' not in command.lower()) try: count = data.pop('count') except KeyError: if not data: # Empty dictionary is returned in case a query does not contain any results. # Can happen also if a listAPI is called with a page that does not exits. Therefore, final_data # has to be returned in order to return all results from preceding pages. return final_data else: # Only list API calls have a 'count' key inside the response, # return data as it is in other cases! return data else: # update final_data using paginated results, dictionaries of the response contain the count key # and one key pointing to the actual data values for key, value in data.items(): final_data.setdefault(key, []).extend(value) final_data['count'] = final_data.setdefault('count', 0) + count kwargs['page'] += 1 if count < self.max_page_size: # no more pages exists return final_data
async def _handle_response(self, response: aiohttp.client_reqrep.ClientResponse, await_final_result: bool) -> dict: """ Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which means that the API call returns just a job id. The actually expected API response is postponed and a specific asyncJobResults API has to be polled using the job id to get the final result once the API call has been processed. :param response: The response returned by the aiohttp call. :type response: aiohttp.client_reqrep.ClientResponse :param await_final_result: Specifier that indicates whether the function should poll the asyncJobResult API until the asynchronous API call has been processed :type await_final_result: bool :return: Dictionary containing the JSON response of the API call :rtype: dict """ try: data = await response.json() except aiohttp.client_exceptions.ContentTypeError: text = await response.text() logging.debug('Content returned by server not of type "application/json"\n Content: {}'.format(text)) raise CloudStackClientException(message="Could not decode content. Server did not return json content!") else: data = self._transform_data(data) if response.status != 200: raise CloudStackClientException(message="Async CloudStack call failed!", error_code=data.get("errorcode", response.status), error_text=data.get("errortext"), response=data) while await_final_result and ('jobid' in data): await asyncio.sleep(self.async_poll_latency) data = await self.queryAsyncJobResult(jobid=data['jobid']) if data['jobstatus']: # jobstatus is 0 for pending async CloudStack calls if not data['jobresultcode']: # exit code is zero try: return data['jobresult'] except KeyError: pass logging.debug("Async CloudStack call returned {}".format(str(data))) raise CloudStackClientException(message="Async CloudStack call failed!", error_code=data.get("errorcode"), error_text=data.get("errortext"), response=data) return data
def _sign(self, url_parameters: dict) -> dict: """ According to the CloudStack documentation, each request needs to be signed in order to authenticate the user account executing the API command. The signature is generated using a combination of the api secret and a SHA-1 hash of the url parameters including the command string. In order to generate a unique identifier, the url parameters have to be transformed to lower case and ordered alphabetically. :param url_parameters: The url parameters of the API call including the command string :type url_parameters: dict :return: The url parameters including a new key, which contains the signature :rtype: dict """ if url_parameters: url_parameters.pop('signature', None) # remove potential existing signature from url parameters request_string = urlencode(sorted(url_parameters.items()), safe='.-*_', quote_via=quote).lower() digest = hmac.new(self.api_secret.encode('utf-8'), request_string.encode('utf-8'), hashlib.sha1).digest() url_parameters['signature'] = base64.b64encode(digest).decode('utf-8').strip() return url_parameters
def _transform_data(data: dict) -> dict: """ Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating the API that originated the response. This function removes that first level from the data returned to the caller. :param data: Response of the API call :type data: dict :return: Simplified response without the information about the API that originated the response. :rtype: dict """ for key in data.keys(): return_value = data[key] if isinstance(return_value, dict): return return_value return data
def virtual_memory(): """System virtual memory as a namedutple.""" mem = _psutil_bsd.get_virtual_mem() total, free, active, inactive, wired, cached, buffers, shared = mem avail = inactive + cached + free used = active + wired + cached percent = usage_percent((total - avail), total, _round=1) return nt_virtmem_info(total, avail, percent, used, free, active, inactive, buffers, cached, shared, wired)
def swap_memory(): """System swap memory as (total, used, free, sin, sout) namedtuple.""" total, used, free, sin, sout = \ [x * _PAGESIZE for x in _psutil_bsd.get_swap_mem()] percent = usage_percent(used, total, _round=1) return nt_swapmeminfo(total, used, free, percent, sin, sout)
def get_system_cpu_times(): """Return system per-CPU times as a named tuple""" user, nice, system, idle, irq = _psutil_bsd.get_system_cpu_times() return _cputimes_ntuple(user, nice, system, idle, irq)
def get_system_per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in _psutil_bsd.get_system_per_cpu_times(): user, nice, system, idle, irq = cpu_t item = _cputimes_ntuple(user, nice, system, idle, irq) ret.append(item) return ret
def get_process_uids(self): """Return real, effective and saved user ids.""" real, effective, saved = _psutil_bsd.get_process_uids(self.pid) return nt_uids(real, effective, saved)
def get_process_gids(self): """Return real, effective and saved group ids.""" real, effective, saved = _psutil_bsd.get_process_gids(self.pid) return nt_gids(real, effective, saved)
def get_cpu_times(self): """return a tuple containing process user/kernel time.""" user, system = _psutil_bsd.get_process_cpu_times(self.pid) return nt_cputimes(user, system)
def get_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms = _psutil_bsd.get_process_memory_info(self.pid)[:2] return nt_meminfo(rss, vms)
def get_process_threads(self): """Return the number of threads belonging to the process.""" rawlist = _psutil_bsd.get_process_threads(self.pid) retlist = [] for thread_id, utime, stime in rawlist: ntuple = nt_thread(thread_id, utime, stime) retlist.append(ntuple) return retlist
def get_open_files(self): """Return files opened by process as a list of namedtuples.""" # XXX - C implementation available on FreeBSD >= 8 only # else fallback on lsof parser if hasattr(_psutil_bsd, "get_process_open_files"): rawlist = _psutil_bsd.get_process_open_files(self.pid) return [nt_openfile(path, fd) for path, fd in rawlist] else: lsof = _psposix.LsofParser(self.pid, self._process_name) return lsof.get_process_open_files()
def get_connection_file(app=None): """Return the path to the connection file of an app Parameters ---------- app : KernelApp instance [optional] If unspecified, the currently running app will be used """ if app is None: from IPython.zmq.ipkernel import IPKernelApp if not IPKernelApp.initialized(): raise RuntimeError("app not specified, and not in a running Kernel") app = IPKernelApp.instance() return filefind(app.connection_file, ['.', app.profile_dir.security_dir])
def find_connection_file(filename, profile=None): """find a connection file, and return its absolute path. The current working directory and the profile's security directory will be searched for the file if it is not given by absolute path. If profile is unspecified, then the current running application's profile will be used, or 'default', if not run from IPython. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) security_dir = profile_dir.security_dir try: # first, try explicit name return filefind(filename, ['.', security_dir]) except IOError: pass # not found by full name if '*' in filename: # given as a glob already pat = filename else: # accept any substring match pat = '*%s*' % filename matches = glob.glob( os.path.join(security_dir, pat) ) if not matches: raise IOError("Could not find %r in %r" % (filename, security_dir)) elif len(matches) == 1: return matches[0] else: # get most recent match, by access time: return sorted(matches, key=lambda f: os.stat(f).st_atime)[-1]
def get_connection_info(connection_file=None, unpack=False, profile=None): """Return the connection information for the current Kernel. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. unpack : bool [default: False] if True, return the unpacked dict, otherwise just the string contents of the file. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- The connection dictionary of the current kernel, as string or dict, depending on `unpack`. """ if connection_file is None: # get connection file from current kernel cf = get_connection_file() else: # connection file specified, allow shortnames: cf = find_connection_file(connection_file, profile=profile) with open(cf) as f: info = f.read() if unpack: info = json.loads(info) # ensure key is bytes: info['key'] = str_to_bytes(info.get('key', '')) return info
def connect_qtconsole(connection_file=None, argv=None, profile=None): """Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel, or to a local notebook. Parameters ---------- connection_file : str [optional] The connection file to be used. Can be given by absolute path, or IPython will search in the security directory of a given profile. If run from IPython, If unspecified, the connection file for the currently running IPython Kernel will be used, which is only allowed from inside a kernel. argv : list [optional] Any extra args to be passed to the console. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- subprocess.Popen instance running the qtconsole frontend """ argv = [] if argv is None else argv if connection_file is None: # get connection file from current kernel cf = get_connection_file() else: cf = find_connection_file(connection_file, profile=profile) cmd = ';'.join([ "from IPython.frontend.qt.console import qtconsoleapp", "qtconsoleapp.main()" ]) return Popen([sys.executable, '-c', cmd, '--existing', cf] + argv, stdout=PIPE, stderr=PIPE)
def tunnel_to_kernel(connection_info, sshserver, sshkey=None): """tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Parameters ---------- connection_info : dict or str (path) Either a connection dict, or the path to a JSON connection file sshserver : str The ssh sever to use to tunnel to the kernel. Can be a full `user@server:port` string. ssh config aliases are respected. sshkey : str [optional] Path to file containing ssh key to use for authentication. Only necessary if your ssh config does not already associate a keyfile with the host. Returns ------- (shell, iopub, stdin, hb) : ints The four ports on localhost that have been forwarded to the kernel. """ if isinstance(connection_info, basestring): # it's a path, unpack it with open(connection_info) as f: connection_info = json.loads(f.read()) cf = connection_info lports = tunnel.select_random_ports(4) rports = cf['shell_port'], cf['iopub_port'], cf['stdin_port'], cf['hb_port'] remote_ip = cf['ip'] if tunnel.try_passwordless_ssh(sshserver, sshkey): password=False else: password = getpass("SSH Password for %s: "%sshserver) for lp,rp in zip(lports, rports): tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password) return tuple(lports)
def swallow_argv(argv, aliases=None, flags=None): """strip frontend-specific aliases and flags from an argument list For use primarily in frontend apps that want to pass a subset of command-line arguments through to a subprocess, where frontend-specific flags and aliases should be removed from the list. Parameters ---------- argv : list(str) The starting argv, to be filtered aliases : container of aliases (dict, list, set, etc.) The frontend-specific aliases to be removed flags : container of flags (dict, list, set, etc.) The frontend-specific flags to be removed Returns ------- argv : list(str) The argv list, excluding flags and aliases that have been stripped """ if aliases is None: aliases = set() if flags is None: flags = set() stripped = list(argv) # copy swallow_next = False was_flag = False for a in argv: if swallow_next: swallow_next = False # last arg was an alias, remove the next one # *unless* the last alias has a no-arg flag version, in which # case, don't swallow the next arg if it's also a flag: if not (was_flag and a.startswith('-')): stripped.remove(a) continue if a.startswith('-'): split = a.lstrip('-').split('=') alias = split[0] if alias in aliases: stripped.remove(a) if len(split) == 1: # alias passed with arg via space swallow_next = True # could have been a flag that matches an alias, e.g. `existing` # in which case, we might not swallow the next arg was_flag = alias in flags elif alias in flags and len(split) == 1: # strip flag, but don't swallow next, as flags don't take args stripped.remove(a) # return shortened list return stripped
def pkg_commit_hash(pkg_path): """Get short form of commit hash given directory `pkg_path` We get the commit hash from (in order of preference): * IPython.utils._sysinfo.commit * git output, if we are in a git repository If these fail, we return a not-found placeholder tuple Parameters ---------- pkg_path : str directory containing package only used for getting commit from active repo Returns ------- hash_from : str Where we got the hash from - description hash_str : str short form of hash """ # Try and get commit from written commit text file if _sysinfo.commit: return "installation", _sysinfo.commit # maybe we are in a repository proc = subprocess.Popen('git rev-parse --short HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=pkg_path, shell=True) repo_commit, _ = proc.communicate() if repo_commit: return 'repository', repo_commit.strip() return '(none found)', '<not found>'
def pkg_info(pkg_path): """Return dict describing the context of this package Parameters ---------- pkg_path : str path containing __init__.py for package Returns ------- context : dict with named parameters of interest """ src, hsh = pkg_commit_hash(pkg_path) return dict( ipython_version=release.version, ipython_path=pkg_path, commit_source=src, commit_hash=hsh, sys_version=sys.version, sys_executable=sys.executable, sys_platform=sys.platform, platform=platform.platform(), os_name=os.name, default_encoding=encoding.DEFAULT_ENCODING, )
def sys_info(): """Return useful information about IPython and the system, as a string. Example ------- In [2]: print sys_info() {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', 'os_name': 'posix', 'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick', 'sys_executable': '/usr/bin/python', 'sys_platform': 'linux2', 'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'} """ p = os.path path = p.dirname(p.abspath(p.join(__file__, '..'))) return pprint.pformat(pkg_info(path))
def _num_cpus_darwin(): """Return the number of active CPUs on a Darwin system.""" p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE) return p.stdout.read()
def num_cpus(): """Return the effective number of CPUs in the system as an integer. This cross-platform function makes an attempt at finding the total number of available CPUs in the system, as returned by various underlying system and python calls. If it can't find a sensible answer, it returns 1 (though an error *may* make it return a large positive number that's actually incorrect). """ # Many thanks to the Parallel Python project (http://www.parallelpython.com) # for the names of the keys we needed to look up for this function. This # code was inspired by their equivalent function. ncpufuncs = {'Linux':_num_cpus_unix, 'Darwin':_num_cpus_darwin, 'Windows':_num_cpus_windows, # On Vista, python < 2.5.2 has a bug and returns 'Microsoft' # See http://bugs.python.org/issue1082 for details. 'Microsoft':_num_cpus_windows, } ncpufunc = ncpufuncs.get(platform.system(), # default to unix version (Solaris, AIX, etc) _num_cpus_unix) try: ncpus = max(1,int(ncpufunc())) except: ncpus = 1 return ncpus
def handle(self, integers, **options): """ [1, 2, 3, 4] {'accumulate': <built-in function max>} """ print integers, options return super(Command, self).handle(integers, **options)
def nextset(self): """Advance to the next result set. Returns None if there are no more result sets. """ if self._executed: self.fetchall() del self.messages[:] db = self._get_db() nr = db.next_result() if nr == -1: return None self._do_get_result() self._post_get_result() self._warning_check() return 1
def execute(self, query, args=None): """Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any """ del self.messages[:] db = self._get_db() if isinstance(query, unicode): query = query.encode(db.unicode_literal.charset) if args is not None: query = query % db.literal(args) try: r = None r = self._query(query) except TypeError, m: if m.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.messages.append((ProgrammingError, m.args[0])) self.errorhandler(self, ProgrammingError, m.args[0]) else: self.messages.append((TypeError, m)) self.errorhandler(self, TypeError, m) except (SystemExit, KeyboardInterrupt): raise except: exc, value, tb = sys.exc_info() del tb self.messages.append((exc, value)) self.errorhandler(self, exc, value) self._executed = query if not self._defer_warnings: self._warning_check() return r
def executemany(self, query, args): """Execute a multi-row query. query -- string, query to execute on server args Sequence of sequences or mappings, parameters to use with query. Returns long integer rows affected, if any. This method improves performance on multiple-row INSERT and REPLACE. Otherwise it is equivalent to looping over args with execute(). """ del self.messages[:] db = self._get_db() if not args: return if isinstance(query, unicode): query = query.encode(db.unicode_literal.charset) m = insert_values.search(query) if not m: r = 0 for a in args: r = r + self.execute(query, a) return r p = m.start(1) e = m.end(1) qv = m.group(1) try: q = [ qv % db.literal(a) for a in args ] except TypeError, msg: if msg.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.errorhandler(self, ProgrammingError, msg.args[0]) else: self.errorhandler(self, TypeError, msg) except (SystemExit, KeyboardInterrupt): raise except: exc, value, tb = sys.exc_info() del tb self.errorhandler(self, exc, value) r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]])) if not self._defer_warnings: self._warning_check() return r
def callproc(self, procname, args=()): """Execute stored procedure procname with args procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This is currently impossible as they are only available by storing them in a server variable and then retrieved by a query. Since stored procedures return zero or more result sets, there is no reliable way to get at OUT or INOUT parameters via callproc. The server variables are named @_procname_n, where procname is the parameter above and n is the position of the parameter (from zero). Once all result sets generated by the procedure have been fetched, you can issue a SELECT @_procname_0, ... query using .execute() to get any OUT or INOUT values. Compatibility warning: The act of calling a stored procedure itself creates an empty result set. This appears after any result sets generated by the procedure. This is non-standard behavior with respect to the DB-API. Be sure to use nextset() to advance through all result sets; otherwise you may get disconnected. """ db = self._get_db() for index, arg in enumerate(args): q = "SET @_%s_%d=%s" % (procname, index, db.literal(arg)) if isinstance(q, unicode): q = q.encode(db.unicode_literal.charset) self._query(q) self.nextset() q = "CALL %s(%s)" % (procname, ','.join(['@_%s_%d' % (procname, i) for i in range(len(args))])) if type(q) is UnicodeType: q = q.encode(db.unicode_literal.charset) self._query(q) self._executed = q if not self._defer_warnings: self._warning_check() return args
def fetchone(self): """Fetches a single row from the cursor.""" self._check_executed() r = self._fetch_row(1) if not r: self._warning_check() return None self.rownumber = self.rownumber + 1 return r[0]
def fetchmany(self, size=None): """Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined, cursor.arraysize is used.""" self._check_executed() r = self._fetch_row(size or self.arraysize) self.rownumber = self.rownumber + len(r) if not r: self._warning_check() return r
def fetchall(self): """Fetchs all available rows from the cursor.""" self._check_executed() r = self._fetch_row(0) self.rownumber = self.rownumber + len(r) self._warning_check() return r
def fetchmanyDict(self, size=None): """Fetch several rows as a list of dictionaries. Deprecated: Use fetchmany() instead. Will be removed in 1.3.""" from warnings import warn warn("fetchmanyDict() is non-standard and will be removed in 1.3", DeprecationWarning, 2) return self.fetchmany(size)
def connect(com, peers, tree, pub_url, root_id): """this function will be called on the engines""" com.connect(peers, tree, pub_url, root_id)
def parse_json(s, **kwargs): """Parse a string into a (nbformat, dict) tuple.""" d = json.loads(s, **kwargs) nbf = d.get('nbformat', 1) nbm = d.get('nbformat_minor', 0) return nbf, nbm, d
def parse_py(s, **kwargs): """Parse a string into a (nbformat, string) tuple.""" nbf = current_nbformat nbm = current_nbformat_minor pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>' m = re.search(pattern,s) if m is not None: digits = m.group('nbformat').split('.') nbf = int(digits[0]) if len(digits) > 1: nbm = int(digits[1]) return nbf, nbm, s
def reads_json(s, **kwargs): """Read a JSON notebook from a string and return the NotebookNode object.""" nbf, minor, d = parse_json(s, **kwargs) if nbf == 1: nb = v1.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=1) elif nbf == 2: nb = v2.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=2) elif nbf == 3: nb = v3.to_notebook_json(d, **kwargs) nb = v3.convert_to_this_nbformat(nb, orig_version=3, orig_minor=minor) else: raise NBFormatError('Unsupported JSON nbformat version: %i' % nbf) return nb
def reads_py(s, **kwargs): """Read a .py notebook from a string and return the NotebookNode object.""" nbf, nbm, s = parse_py(s, **kwargs) if nbf == 2: nb = v2.to_notebook_py(s, **kwargs) elif nbf == 3: nb = v3.to_notebook_py(s, **kwargs) else: raise NBFormatError('Unsupported PY nbformat version: %i' % nbf) return nb
def reads(s, format, **kwargs): """Read a notebook from a string and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- s : unicode The raw unicode string to read the notebook from. format : (u'json', u'ipynb', u'py') The format that the string is in. Returns ------- nb : NotebookNode The notebook that was read. """ format = unicode(format) if format == u'json' or format == u'ipynb': return reads_json(s, **kwargs) elif format == u'py': return reads_py(s, **kwargs) else: raise NBFormatError('Unsupported format: %s' % format)
def writes(nb, format, **kwargs): """Write a notebook to a string in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string. """ format = unicode(format) if format == u'json' or format == u'ipynb': return writes_json(nb, **kwargs) elif format == u'py': return writes_py(nb, **kwargs) else: raise NBFormatError('Unsupported format: %s' % format)
def write(nb, fp, format, **kwargs): """Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like object with a write method. format : (u'json', u'ipynb', u'py') The format to write the notebook in. Returns ------- s : unicode The notebook string. """ return fp.write(writes(nb, format, **kwargs))
def _convert_to_metadata(): """Convert to a notebook having notebook metadata.""" import glob for fname in glob.glob('*.ipynb'): print('Converting file:',fname) with open(fname,'r') as f: nb = read(f,u'json') md = new_metadata() if u'name' in nb: md.name = nb.name del nb[u'name'] nb.metadata = md with open(fname,'w') as f: write(nb, f, u'json')
def load_from_dict(self, src: dict, key): ''' try load value from dict. if key is not exists, mark as state unset. ''' if key in src: self.value = src[key] else: self.reset()
def inputhook_pyglet(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. try: t = clock() while not stdin_ready(): pyglet.clock.tick() for window in pyglet.app.windows: window.switch_to() window.dispatch_events() window.dispatch_event('on_draw') flip(window) # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 5*60.0: # print 'Sleep for 5 s' # dbg time.sleep(5.0) elif used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
def matches(self, name): """Does the name match my requirements? To match, a name must match config.testMatch OR config.include and it must not match config.exclude """ return ((self.match.search(name) or (self.include and filter(None, [inc.search(name) for inc in self.include]))) and ((not self.exclude) or not filter(None, [exc.search(name) for exc in self.exclude]) ))
def wantClass(self, cls): """Is the class a wanted test class? A class must be a unittest.TestCase subclass, or match test name requirements. Classes that start with _ are always excluded. """ declared = getattr(cls, '__test__', None) if declared is not None: wanted = declared else: wanted = (not cls.__name__.startswith('_') and (issubclass(cls, unittest.TestCase) or self.matches(cls.__name__))) plug_wants = self.plugins.wantClass(cls) if plug_wants is not None: log.debug("Plugin setting selection of %s to %s", cls, plug_wants) wanted = plug_wants log.debug("wantClass %s? %s", cls, wanted) return wanted
def wantDirectory(self, dirname): """Is the directory a wanted test directory? All package directories match, so long as they do not match exclude. All other directories must match test requirements. """ tail = op_basename(dirname) if ispackage(dirname): wanted = (not self.exclude or not filter(None, [exc.search(tail) for exc in self.exclude] )) else: wanted = (self.matches(tail) or (self.config.srcDirs and tail in self.config.srcDirs)) plug_wants = self.plugins.wantDirectory(dirname) if plug_wants is not None: log.debug("Plugin setting selection of %s to %s", dirname, plug_wants) wanted = plug_wants log.debug("wantDirectory %s? %s", dirname, wanted) return wanted
def wantFile(self, file): """Is the file a wanted test file? The file must be a python source file and match testMatch or include, and not match exclude. Files that match ignore are *never* wanted, regardless of plugin, testMatch, include or exclude settings. """ # never, ever load files that match anything in ignore # (.* _* and *setup*.py by default) base = op_basename(file) ignore_matches = [ ignore_this for ignore_this in self.ignoreFiles if ignore_this.search(base) ] if ignore_matches: log.debug('%s matches ignoreFiles pattern; skipped', base) return False if not self.config.includeExe and os.access(file, os.X_OK): log.info('%s is executable; skipped', file) return False dummy, ext = op_splitext(base) pysrc = ext == '.py' wanted = pysrc and self.matches(base) plug_wants = self.plugins.wantFile(file) if plug_wants is not None: log.debug("plugin setting want %s to %s", file, plug_wants) wanted = plug_wants log.debug("wantFile %s? %s", file, wanted) return wanted
def wantFunction(self, function): """Is the function a test function? """ try: if hasattr(function, 'compat_func_name'): funcname = function.compat_func_name else: funcname = function.__name__ except AttributeError: # not a function return False declared = getattr(function, '__test__', None) if declared is not None: wanted = declared else: wanted = not funcname.startswith('_') and self.matches(funcname) plug_wants = self.plugins.wantFunction(function) if plug_wants is not None: wanted = plug_wants log.debug("wantFunction %s? %s", function, wanted) return wanted
def wantMethod(self, method): """Is the method a test method? """ try: method_name = method.__name__ except AttributeError: # not a method return False if method_name.startswith('_'): # never collect 'private' methods return False declared = getattr(method, '__test__', None) if declared is not None: wanted = declared else: wanted = self.matches(method_name) plug_wants = self.plugins.wantMethod(method) if plug_wants is not None: wanted = plug_wants log.debug("wantMethod %s? %s", method, wanted) return wanted
def wantModule(self, module): """Is the module a test module? The tail of the module name must match test requirements. One exception: we always want __main__. """ declared = getattr(module, '__test__', None) if declared is not None: wanted = declared else: wanted = self.matches(module.__name__.split('.')[-1]) \ or module.__name__ == '__main__' plug_wants = self.plugins.wantModule(module) if plug_wants is not None: wanted = plug_wants log.debug("wantModule %s? %s", module, wanted) return wanted
def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): """Make new_fn have old_fn's doc string. This is particularly useful for the do_... commands that hook into the help system. Adapted from from a comp.lang.python posting by Duncan Booth.""" def wrapper(*args, **kw): return new_fn(*args, **kw) if old_fn.__doc__: wrapper.__doc__ = old_fn.__doc__ + additional_text return wrapper
def _file_lines(fname): """Return the contents of a named file as a list of lines. This function never raises an IOError exception: if the file can't be read, it simply returns an empty list.""" try: outfile = open(fname) except IOError: return [] else: out = outfile.readlines() outfile.close() return out
def list_command_pydb(self, arg): """List command to use if we have a newer pydb installed""" filename, first, last = OldPdb.parse_list_cmd(self, arg) if filename is not None: self.print_list_lines(filename, first, last)
def print_list_lines(self, filename, first, last): """The printing (as opposed to the parsing part of a 'list' command.""" try: Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) src = [] for lineno in range(first, last+1): line = linecache.getline(filename, lineno) if not line: break if lineno == self.curframe.f_lineno: line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) else: line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) src.append(line) self.lineno = lineno print >>io.stdout, ''.join(src) except KeyboardInterrupt: pass
def do_pdef(self, arg): """The debugger interface to magic_pdef""" namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
def checkline(self, filename, lineno): """Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive. """ ####################################################################### # XXX Hack! Use python-2.5 compatible code for this call, because with # all of our changes, we've drifted from the pdb api in 2.6. For now, # changing: # #line = linecache.getline(filename, lineno, self.curframe.f_globals) # to: # line = linecache.getline(filename, lineno) # # does the trick. But in reality, we need to fix this by reconciling # our updates with the new Pdb APIs in Python 2.6. # # End hack. The rest of this method is copied verbatim from 2.6 pdb.py ####################################################################### if not line: print >>self.stdout, 'End of file' return 0 line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): print >>self.stdout, '*** Blank or comment' return 0 return lineno
def conversion_factor(from_symbol, to_symbol, date): """ Generates a multiplying factor used to convert two currencies """ from_currency = Currency.objects.get(symbol=from_symbol) try: from_currency_price = CurrencyPrice.objects.get(currency=from_currency, date=date).mid_price except CurrencyPrice.DoesNotExist: print "Cannot fetch prices for %s on %s" % (str(from_currency), str(date)) return None to_currency = Currency.objects.get(symbol=to_symbol) try: to_currency_price = CurrencyPrice.objects.get(currency=to_currency, date=date).mid_price except CurrencyPrice.DoesNotExist: print "Cannot fetch prices for %s on %s" % (str(to_currency), str(date)) return None return to_currency_price / from_currency_price
def convert_currency(from_symbol, to_symbol, value, date): """ Converts an amount of money from one currency to another on a specified date. """ if from_symbol == to_symbol: return value factor = conversion_factor(from_symbol, to_symbol, date) if type(value) == float: output = value * float(factor) elif type(value) == Decimal: output = Decimal(format(value * factor, '.%sf' % str(PRICE_PRECISION))) elif type(value) in [np.float16, np.float32, np.float64, np.float128, np.float]: output = float(value) * float(factor) else: output = None return output
def compute_return(self, start_date, end_date, rate="MID"): """ Compute the return of the currency between two dates """ if rate not in ["MID", "ASK", "BID"]: raise ValueError("Unknown rate type (%s)- must be 'MID', 'ASK' or 'BID'" % str(rate)) if end_date <= start_date: raise ValueError("End date must be on or after start date") df = self.generate_dataframe(start_date=start_date, end_date=end_date) start_price = df.ix[start_date][rate] end_price = df.ix[end_date][rate] currency_return = (end_price / start_price) - 1.0 return currency_return
def generate_dataframe(self, symbols=None, date_index=None, price_type="mid"): """ Generate a dataframe consisting of the currency prices (specified by symbols) from the start to end date """ # Set defaults if necessary if symbols is None: symbols = list(Currency.objects.all().values_list('symbol', flat=True)) try: start_date = date_index[0] end_date = date_index[-1] except: start_date = DATEFRAME_START_DATE end_date = date.today() date_index = date_range(start_date, end_date) currency_price_data = CurrencyPrice.objects.filter(currency__symbol__in=symbols, date__gte=date_index[0], date__lte=date_index[-1]).values_list('date', 'currency__symbol', 'ask_price', 'bid_price') try: forex_data_array = np.core.records.fromrecords(currency_price_data, names=['date', 'symbol', 'ask_price', 'bid_price']) except IndexError: forex_data_array = np.core.records.fromrecords([(date(1900, 1, 1), "", 0, 0)], names=['date', 'symbol', 'ask_price', 'bid_price']) df = DataFrame.from_records(forex_data_array, index='date') df['date'] = df.index if price_type == "mid": df['price'] = (df['ask_price'] + df['bid_price']) / 2 elif price_type == "ask": df['price'] = df['ask_price'] elif price_type == "bid": df['price'] = df['bid_price'] else: raise ValueError("Incorrect price_type (%s) must be on of 'ask', 'bid' or 'mid'" % str(price_type)) df = df.pivot(index='date', columns='symbol', values='price') df = df.reindex(date_index) df = df.fillna(method="ffill") unlisted_symbols = list(set(symbols) - set(df.columns)) for unlisted_symbol in unlisted_symbols: df[unlisted_symbol] = np.nan df = df[symbols] return df
def save(self, *args, **kwargs): """ Sanitation checks """ if self.ask_price < 0: raise ValidationError("Ask price must be greater than zero") if self.bid_price < 0: raise ValidationError("Bid price must be greater than zero") if self.ask_price < self.bid_price: raise ValidationError("Ask price must be at least Bid price") super(CurrencyPrice, self).save(*args, **kwargs)
def get_stream_enc(stream, default=None): """Return the given stream's encoding or a default. There are cases where sys.std* might not actually be a stream, so check for the encoding attribute prior to returning it, and return a default if it doesn't exist or evaluates as False. `default' is None if not provided. """ if not hasattr(stream, 'encoding') or not stream.encoding: return default else: return stream.encoding
def getdefaultencoding(): """Return IPython's guess for the default encoding for bytes as text. Asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Fall back on locale.getpreferredencoding() which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually ASCII. """ enc = get_stream_enc(sys.stdin) if not enc or enc=='ascii': try: # There are reports of getpreferredencoding raising errors # in some cases, which may well be fixed, but let's be conservative here. enc = locale.getpreferredencoding() except Exception: pass return enc or sys.getdefaultencoding()
def get_userpass_value(cli_value, config, key, prompt_strategy): """Gets the username / password from config. Uses the following rules: 1. If it is specified on the cli (`cli_value`), use that. 2. If `config[key]` is specified, use that. 3. Otherwise prompt using `prompt_strategy`. :param cli_value: The value supplied from the command line or `None`. :type cli_value: unicode or `None` :param config: Config dictionary :type config: dict :param key: Key to find the config value. :type key: unicode :prompt_strategy: Argumentless function to return fallback value. :type prompt_strategy: function :returns: The value for the username / password :rtype: unicode """ if cli_value is not None: return cli_value elif config.get(key): return config[key] else: return prompt_strategy()
def load_connection_file(self): """load ip/port/hmac config from JSON connection file""" try: fname = filefind(self.connection_file, ['.', self.profile_dir.security_dir]) except IOError: self.log.debug("Connection file not found: %s", self.connection_file) # This means I own it, so I will clean it up: atexit.register(self.cleanup_connection_file) return self.log.debug(u"Loading connection file %s", fname) with open(fname) as f: s = f.read() cfg = json.loads(s) if self.ip == LOCALHOST and 'ip' in cfg: # not overridden by config or cl_args self.ip = cfg['ip'] for channel in ('hb', 'shell', 'iopub', 'stdin'): name = channel + '_port' if getattr(self, name) == 0 and name in cfg: # not overridden by config or cl_args setattr(self, name, cfg[name]) if 'key' in cfg: self.config.Session.key = str_to_bytes(cfg['key'])
def write_connection_file(self): """write connection info to JSON file""" if os.path.basename(self.connection_file) == self.connection_file: cf = os.path.join(self.profile_dir.security_dir, self.connection_file) else: cf = self.connection_file write_connection_file(cf, ip=self.ip, key=self.session.key, shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port, iopub_port=self.iopub_port) self._full_connection_file = cf
def init_heartbeat(self): """start the heart beating""" # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() self.heartbeat = Heartbeat(hb_ctx, (self.ip, self.hb_port)) self.hb_port = self.heartbeat.port self.log.debug("Heartbeat REP Channel on port: %i"%self.hb_port) self.heartbeat.start() # Helper to make it easier to connect to an existing kernel. # set log-level to critical, to make sure it is output self.log.critical("To connect another client to this kernel, use:")
def log_connection_info(self): """display connection info, and store ports""" basename = os.path.basename(self.connection_file) if basename == self.connection_file or \ os.path.dirname(self.connection_file) == self.profile_dir.security_dir: # use shortname tail = basename if self.profile != 'default': tail += " --profile %s" % self.profile else: tail = self.connection_file self.log.critical("--existing %s", tail) self.ports = dict(shell=self.shell_port, iopub=self.iopub_port, stdin=self.stdin_port, hb=self.hb_port)
def init_session(self): """create our session object""" default_secure(self.config) self.session = Session(config=self.config, username=u'kernel')
def init_blackhole(self): """redirects stdout/stderr to devnull if necessary""" if self.no_stdout or self.no_stderr: blackhole = open(os.devnull, 'w') if self.no_stdout: sys.stdout = sys.__stdout__ = blackhole if self.no_stderr: sys.stderr = sys.__stderr__ = blackhole
def init_io(self): """Redirect input streams and set a display hook.""" if self.outstream_class: outstream_factory = import_item(str(self.outstream_class)) sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout') sys.stderr = outstream_factory(self.session, self.iopub_socket, u'stderr') if self.displayhook_class: displayhook_factory = import_item(str(self.displayhook_class)) sys.displayhook = displayhook_factory(self.session, self.iopub_socket)
def init_kernel(self): """Create the Kernel object itself""" kernel_factory = import_item(str(self.kernel_class)) self.kernel = kernel_factory(config=self.config, session=self.session, shell_socket=self.shell_socket, iopub_socket=self.iopub_socket, stdin_socket=self.stdin_socket, log=self.log ) self.kernel.record_ports(self.ports)
def init_connector(self): """construct connection function, which handles tunnels.""" self.using_ssh = bool(self.sshkey or self.sshserver) if self.sshkey and not self.sshserver: # We are using ssh directly to the controller, tunneling localhost to localhost self.sshserver = self.url.split('://')[1].split(':')[0] if self.using_ssh: if tunnel.try_passwordless_ssh(self.sshserver, self.sshkey, self.paramiko): password=False else: password = getpass("SSH Password for %s: "%self.sshserver) else: password = False def connect(s, url): url = disambiguate_url(url, self.location) if self.using_ssh: self.log.debug("Tunneling connection to %s via %s"%(url, self.sshserver)) return tunnel.tunnel_connection(s, url, self.sshserver, keyfile=self.sshkey, paramiko=self.paramiko, password=password, ) else: return s.connect(url) def maybe_tunnel(url): """like connect, but don't complete the connection (for use by heartbeat)""" url = disambiguate_url(url, self.location) if self.using_ssh: self.log.debug("Tunneling connection to %s via %s"%(url, self.sshserver)) url,tunnelobj = tunnel.open_tunnel(url, self.sshserver, keyfile=self.sshkey, paramiko=self.paramiko, password=password, ) return url return connect, maybe_tunnel
def register(self): """send the registration_request""" self.log.info("Registering with controller at %s"%self.url) ctx = self.context connect,maybe_tunnel = self.init_connector() reg = ctx.socket(zmq.DEALER) reg.setsockopt(zmq.IDENTITY, self.bident) connect(reg, self.url) self.registrar = zmqstream.ZMQStream(reg, self.loop) content = dict(queue=self.ident, heartbeat=self.ident, control=self.ident) self.registrar.on_recv(lambda msg: self.complete_registration(msg, connect, maybe_tunnel)) # print (self.session.key) self.session.send(self.registrar, "registration_request",content=content)
def html_to_text(content): """ Converts html content to plain text """ text = None h2t = html2text.HTML2Text() h2t.ignore_links = False text = h2t.handle(content) return text