code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
story_ids = requests.get(TOP_STORIES_URL).json() story_urls = [] for story_id in story_ids: url = API_BASE + "item/" + str(story_id) + '.json' story_urls.append(url) if first and last: story_urls = story_urls[first:last] if limit...
def top_stories(self, limit=5, first=None, last=None, json=False)
Get the top story objects list params : limit = (default | 5) number of story objects needed json = (default | False) The method uses asynchronous grequest form gevent
3.088768
3.016942
1.023808
try: comment_ids = requests.get( API_BASE + "item/" + str(comment_id) + '.json').json()['kids'] except KeyError: return None comment_urls = [] for comment_id in comment_ids: url = API_BASE + "item/" + str(comment_id) + '.json'...
def get_comments(self, comment_id=2921983, limit=5, json=False)
Get the top story objects list params : comment_id = the id of the story object limit = (default = 5) number of story objects needed set limit it to None to get all the comments The method uses asynchronous grequest form gevent
3.576796
3.339726
1.070985
if image.mode not in ('RGBA', 'LA'): return image # In most cases simply discarding the alpha channel will give # undesirable result, because transparent pixels also have some # unpredictable colors. It is much better to fill transparent pixels # with a specified color. background_...
def convert_image_to_rgb_mode(image, fill_color=(255, 255, 255))
Convert the specified image instance to RGB mode. @param image: a Python Library Image (PIL) instance to convert its pixel format to RGB, discarding the alpha channel. @param fill_color: color to be used to fill transparent pixels when discaring the alpha channel. By default, the white color...
4.938221
4.719189
1.046413
for (logical_size, width, height) in \ sorted(pixel_resolutions, key=lambda (l, w, h): w, reverse=True): yield (logical_size, resize_image(image, (width, height), filter=filter, does_crop=does_crop, crop_aligment=crop_aligment, ...
def generate_multiple_pixel_resolutions(image, pixel_resolutions, filter=Filter.NearestNeighbor, does_crop=False, crop_aligment=CropAlignment.center, match_orientation=False)
Generate multiple resolution images of the given image. @param image: a Python Library Image (PIL) instance to generate multiple pixel resolutions from. @param pixel_resolutions: a list of tuples ``(logical_size, width, height)`` where: * ``logical_size``: string representation of th...
2.727195
2.493935
1.093531
def _get_exposure(histogram): total = sum(histogram) range_offset = len(histogram) / 4 dark = float(sum(histogram[0:range_offset])) / total #normal = float(sum(histogram[range_offset:-range_offset])) / total light = float(sum(histogram[-range_offset:])) / total r...
def get_exposure(image, filters=None)
Determine the exposure of a photo, which can be under-exposed, normally exposed or over-exposed. @param image: a Python Library Image (PIL) object to determine the exposure. @param filters: a list of ``ColorComponentFilter`` filter or ``None`` to use all the filters. @return: an ``E...
2.747688
2.55716
1.074508
# Image.verify is only implemented for PNG images, and it only verifies # the CRC checksum in the image. The only way to check from within # Pillow is to load the image in a try/except and check the error. If # as much info as possible is from the image is needed, # ``ImageFile.LOAD_TRUNCATED...
def is_image_file_valid(file_path_name)
Indicate whether the specified image file is valid or not. @param file_path_name: absolute path and file name of an image. @return: ``True`` if the image file is valid, ``False`` if the file is truncated or does not correspond to a supported image.
8.228574
8.248646
0.997567
# Retrieve tags from the Exchangeable image file format (Exif) # included in the picture. If the orientation of the picture is not # top left side, rotate it accordingly. # @deprecated # exif_tags = dict([ (exif_tag.tag, exif_tag) # for exif_tag in exif.process_file(handle).itervalues...
def open_and_reorient_image(handle)
Load the image from the specified file and orient the image accordingly to the Exif tag that the file might embed, which would indicate the orientation of the camera relative to the captured scene. @param handle: a Python file object. @return: an instance returned by the Python Library Image library...
4.59047
4.300422
1.067446
(width, height) = image.size # Determine the new size of the image based on the maximal horizontal # and vertical shifts of all the other images in this series. new_width = width - max_shift_x * 2 new_height = height - max_shift_y * 2 # Determine the coordinates of the zone to crop to cen...
def realign_image(image, shift_x, shift_y, max_shift_x, max_shift_y, shift_angle=0.0, filter=Filter.NearestNeighbor, stretch_factor=None, cropping_box=None)
Realign the given image providing the specific horizontal and vertical shifts, and crop the image providing the maximum horizontal and vertical shifts of images of a same set so that they all have the same size. @param image: an instance of Python Image Library (PIL) image. @param shift_x: horizo...
2.075007
2.029283
1.022532
(source_width, source_height) = image.size source_aspect = source_width / float(source_height) (canvas_width, canvas_height) = canvas_size canvas_aspect = canvas_width / float(canvas_height) if match_orientation: if (source_aspect > 1.0 > canvas_aspect) or (source_aspect < 1.0 < canva...
def resize_image(image, canvas_size, filter=Filter.NearestNeighbor, does_crop=False, crop_aligment=CropAlignment.center, crop_form=CropForm.rectangle, match_orientation=False)
Resize the specified image to the required dimension. @param image: a Python Image Library (PIL) image instance. @param canvas_size: requested size in pixels, as a 2-tuple ``(width, height)``. @param filter: indicate the filter to use when resizing the image. @param does_crop: indicate whet...
1.644059
1.671871
0.983365
if left >= right: return low = left high = right key = array[low] while left < right: # 将大于key的值放到右边 while left < right and array[right] > key: right -= 1 array[left] = array[right] # 将小于key的值放到左边 while left < right and array[left]...
def quick_sort(array, left, right)
快速排序
2.084949
1.976506
1.054866
# https://www.khanacademy.org/math/trigonometry/unit-circle-trig-func/inverse_trig_functions/v/inverse-trig-functions--arctan angles = np.arctan2(pvals, nvals)-np.pi/4 norm = np.maximum(np.minimum(angles, np.pi-angles), -1*np.pi-angles) norm = csr_matrix(norm) # Remove any weight from the NER features. The...
def __get_vtt_angles(self, pvals, nvals)
Fit the angles to the model Args: pvals (array-like) : positive values nvals (array-like) : negative values Returns: normalized coef_ values
6.08616
6.044308
1.006924
if not hasattr(self, 'coef_') or self.coef_ is None: raise NotFittedError("This %(name)s instance is not fitted " "yet" % {'name': type(self).__name__}) # Number of NER features. These can be int n_ner = len(self.B) X_fea = X[ : , :-n_ner] X_ner = X[ : , -n_ner:] X_fea = check_array(X_fea,...
def decision_function(self, X)
Predict confidence scores for samples. The confidence score for a sample is the signed distance of that sample to the hyperplane. Args: X : {array-like, sparse matrix}, shape = (n_samples, n_features) Samples. Returns: array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes) Confi...
2.664078
2.609019
1.021103
if 'bias' in params.keys(): self.intercept_ = params['bias'] if 'weights' in params.keys(): self.coef_ = params['weights'] for key in params.keys(): if 'b_' == key[:2]: self.B[int(key[2:])] = params[key] return self
def set_params(self, **params)
Set the parameters of the estimator. Args: bias (array-like) : bias of the estimator. Also known as the intercept in a linear model. weights (array-like) : weights of the features. Also known as coeficients. NER biases (array-like) : NER entities infering column position on X and bias value. Ex: `b_4=10, b_...
2.988715
2.673701
1.117819
params = {'weights':self.coef_, 'bias':self.intercept_} if deep: for key, value in self.B.items(): params['b_'+str(key)] = value return params
def get_params(self, deep=True)
Get parameters for the estimator. Args: deep (boolean, optional) : If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns: params : mapping of string to any contained subobjects that are estimators.
3.679839
4.853109
0.758244
assert author_name or author_email_address, 'Both arguments MUST NOT be bull' # Use the specified name of the author or the username of his email # address. author_name_expr = author_name or author_email_address[:author_email_address.find('@')] # Escape the name of the author if it contains a...
def __build_author_name_expr(author_name, author_email_address)
Build the name of the author of a message as described in the Internet Message Format specification: https://tools.ietf.org/html/rfc5322#section-3.6.2 @param author_name: complete name of the originator of the message. @param author_email_address: address of the mailbox to which the author of the...
3.011088
3.304882
0.911103
if len(values) == 0: return None else: if group_by: group_aggs = pd.DataFrame(values).groupby(group_by).agg({agg_field: agg_funcs}) res = {} for row in group_aggs.itertuples(): row_res = {} ...
def agg_multi_func(values, agg_field, agg_funcs, group_by=None)
Aggregates several functions :param values: list of objects (dict) :param agg_field: target field to calculate aggregates :param agg_funcs: list of aggregate functions :param group_by: field used to determine group :return: dict {agg_func0: value, agg_func1: agg_value, ...}
1.903857
1.875816
1.014949
if len(values) == 0: return None else: if group_by: group_aggs = pd.DataFrame(values).groupby(group_by).agg({agg_field: [agg_func]}) res = {} for row in group_aggs.itertuples(): res.update({row[0]: row[1...
def agg_single_func(values, agg_field, agg_func, group_by=None)
Aggregates single function :param values: list of objects (dict) :param agg_field: target field to calculate aggregate :param agg_func: aggregate function :param group_by: field used to determine group :return: aggregated value
2.208773
2.305529
0.958033
debitq = session.query(wm.Debit) debitq = debitq.filter(wm.Debit.address == address) debitq = debitq.filter(wm.Debit.amount == amount) debit = debitq.filter(wm.Debit.transaction_state == 'unconfirmed').first() if not debit: raise ValueError("Debit already confirmed or address unknown.")...
def confirm_send(address, amount, ref_id=None, session=ses)
Confirm that a send has completed. Does not actually check confirmations, but instead assumes that if this is called, the transaction has been completed. This is because we assume our own sends are safe. :param session: :param str ref_id: The updated ref_id for the transaction in question :param st...
2.575314
2.820807
0.912971
parser = _make_parser() if parser.read(path): return parser raise Exception("Failed to read {}".format(path))
def read_config(path)
Read a configuration from disk. Arguments path -- the loation to deserialize
6.134626
9.494375
0.646133
params = get_params(radius_sampling) # sage script: # var('sphere_index, sphere_index_sc, na, nb, medium_index') # x = sphere_index / medium_index - 1 # eq = sphere_index_sc == sphere_index + ( na*x^2 + nb*x) * medium_index # solve([eq], [sphere_index]) # (take the positive sign soluti...
def correct_rytov_sc_input(radius_sc, sphere_index_sc, medium_index, radius_sampling)
Inverse correction of refractive index and radius for Rytov This method returns the inverse of :func:`correct_rytov_output`. Parameters ---------- radius_sc: float Systematically corrected radius of the sphere [m] sphere_index_sc: float Systematically corrected refractive index of ...
5.852629
6.230463
0.939357
r params = get_params(radius_sampling) x = sphere_index / medium_index - 1 radius_sc = radius * (params["ra"] * x**2 + params["rb"] * x + params["rc"]) sphere_index_sc = sphere_index + medium_index * (params["na"] * x**2 ...
def correct_rytov_output(radius, sphere_index, medium_index, radius_sampling)
r"""Error-correction of refractive index and radius for Rytov This method corrects the fitting results for `radius` :math:`r_\text{Ryt}` and `sphere_index` :math:`n_\text{Ryt}` obtained using :func:`qpsphere.models.rytov` using the approach described in :cite:`Mueller2018` (eqns. 3,4, and 5). .. m...
4.621081
4.779813
0.966791
r r_ryt, n_ryt = correct_rytov_sc_input(radius_sc=radius, sphere_index_sc=sphere_index, medium_index=medium_index, radius_sampling=radius_sampling) qpi = mod_rytov.rytov(radius=r_ry...
def rytov_sc(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80), center=(39.5, 39.5), radius_sampling=42)
r"""Field behind a dielectric sphere, systematically corrected Rytov This method implements a correction of :func:`qpsphere.models.rytov`, where the `radius` :math:`r_\text{Ryt}` and the `sphere_index` :math:`n_\text{Ryt}` are corrected using the approach described in :cite:`Mueller2018` (eqns. 3,4...
3.464973
3.095995
1.119179
'''Return all CSV and JSON files paths in datapackage_registry/schemas The paths are relative to ./datapackage_registry ''' def recursive_glob(path, patterns): results = [] for base, dirs, files in os.walk(path): matching_files = [] for pattern in patterns: ...
def schema_files()
Return all CSV and JSON files paths in datapackage_registry/schemas The paths are relative to ./datapackage_registry
2.955786
2.13526
1.384275
frame = sys._getframe(1) try: locals = frame.f_locals finally: del frame dict = locals.setdefault('__gsignals__', {}) if args and args[0] == 'override': dict[name] = 'override' else: retval = kwargs.get('retval', None) if retval is None: ...
def gsignal(name, *args, **kwargs)
Add a GObject signal to the current object. It current supports the following types: - str, int, float, long, object, enum :param name: name of the signal :param args: types for signal parameters, if the first one is a string 'override', the signal will be overridden and must there...
2.965522
2.846433
1.041838
# General type checking if default is None: default = _DEFAULT_VALUES.get(ptype) elif not isinstance(default, ptype): raise TypeError("default must be of type %s, not %r" % ( ptype, default)) if not isinstance(nick, str): raise TypeError('nick for property %s mu...
def gproperty(name, ptype, default=None, nick='', blurb='', flags=gobject.PARAM_READWRITE, **kwargs)
Add a GObject property to the current object. :param name: name of property :param ptype: type of property :param default: default value :param nick: short description :param blurb: long description :param flags: parameter flags, a combination of: - PARAM_READABLE - P...
2.551559
2.55195
0.999847
time.sleep(delay) while gtk.events_pending(): gtk.main_iteration_do(block=False) time.sleep(wait)
def refresh_gui(delay=0.0001, wait=0.0001)
Use up all the events waiting to be run :param delay: Time to wait before using events :param wait: Time to wait between iterations of events This function will block until all pending events are emitted. This is useful in testing to ensure signals and other asynchronous functionality is required ...
3.047668
3.536055
0.861884
w = _get_in_window(target) if on_destroy: w.connect('destroy', on_destroy) w.resize(500, 400) w.move(100, 100) w.show_all() gtk.main()
def run_in_window(target, on_destroy=gtk.main_quit)
Run a widget, or a delegate in a Window
2.397848
2.466833
0.972035
''' Generate a flatland form based on a pandas Series. ''' from flatland import Boolean, Form, String, Integer, Float def is_float(v): try: return (float(str(v)), True)[1] except (ValueError, TypeError): return False def is_int(v): try: ...
def dict_to_form(dict)
Generate a flatland form based on a pandas Series.
2.318056
2.038389
1.1372
if os.name == 'nt': if os.environ.get('TERM') == 'xterm': # maybe MinTTY return 'mintty' else: return 'nt' if platform.system().upper().startswith('CYGWIN'): return 'cygwin' return 'posix'
def _detect_term_type()
Detect the type of the terminal.
5.002854
4.544608
1.100833
if hasattr(stdout, 'encoding') and stdout.encoding: return stdout.encoding if os.environ.get('LANG'): encoding = os.environ.get('LANG').split('.')[-1] # validate the encoding string ret = None try: ret = codecs.lookup...
def _detect_encoding(stdout)
Detect the default encoding for the terminal's output. :return: string: encoding string
3.16161
3.038007
1.040686
if os.name == 'nt' or not self.getch_enabled: return lambda signal, frame: None try: fd = self.stdin.fileno() initial = termios.tcgetattr(fd) except termios.error: return lambda signal, frame: None return lambda signal, frame: te...
def _get_restore_function(self)
Return the binary function for restoring terminal attributes. :return: function (signal, frame) => None:
3.470136
2.873835
1.207493
if hasattr(self.stdout, 'isatty') and self.stdout.isatty() or self.term_type == 'mintty': cmd, shell = { 'posix': ('clear', False), 'nt': ('cls', True), 'cygwin': (['echo', '-en', r'\ec'], False), 'mintty': (r'echo -en "\ec', F...
def clear(self)
Clear the terminal screen.
4.313872
4.153017
1.038732
if hasattr(self.stdin, 'isatty') and self.stdin.isatty(): if os.name == 'nt': while msvcrt.kbhit(): msvcrt.getch() else: try: self.stdin.seek(0, 2) # may fail in some unseekable file object ...
def clear_input_buffer(self)
Clear the input buffer.
3.544369
3.453723
1.026246
ch = self._get_one_char() if self.keep_input_clean: self.clear_input_buffer() try: # accept only unicode characters (for Python 2) uch = to_unicode(ch, 'ascii') except UnicodeError: return '' return uch if self._check_key...
def getch(self)
Read one character from stdin. If stdin is not a tty or set `getch_enabled`=False, read input as one line. :return: unicode:
6.946261
7.53082
0.922378
ret = self.stdin.readline() if ret == '': raise EOFError # To break out of EOF loop return ret.rstrip('\n')
def gets(self)
Read line from stdin. The trailing newline will be omitted. :return: string:
9.738699
7.809592
1.247018
self.parser = subparsers.add_parser(self.name, help=self.help, parents=self.parents) self.add_arguments() self.parser.set_defaults(func=self.handle) return self.parser
def create_parser(self, subparsers)
Creates the subparser for this particular command
2.277344
2.192027
1.038921
if self.parser is None: raise TypeError("Parser cannot be None, has create_parser been called?") for keys, kwargs in self.args.items(): if not isinstance(keys, tuple): keys = (keys,) self.parser.add_argument(*keys, **kwargs)
def add_arguments(self)
Definition and addition of all arguments.
3.894377
3.525052
1.104772
''' Allocation provides a snapshot of how shards have located around the cluster and the state of disk usage ''' try: response = base.es.cat.allocation(node_id=node,bytes=format, h=h, format='json') table = base.draw_table(response) except Exception as e: click.echo(e) ...
def allocation(node,format,h)
Allocation provides a snapshot of how shards have located around the cluster and the state of disk usage
9.38274
4.649581
2.017975
''' Gives count of the documents stored in Elasticsearch. If index option is provided, it will provide document count of that index. ''' try: response = base.es.cat.count(index,h=h) table = base.draw_table(response) except Exception as e: click.echo(e) else: c...
def count(index,h)
Gives count of the documents stored in Elasticsearch. If index option is provided, it will provide document count of that index.
7.44927
3.74372
1.989804
if self.channel is not None: self.channel.close() if self.__connection is not None: self.__connection.close()
def close(self)
Close the connection to the AMQP compliant broker.
4.131984
3.13899
1.316342
self._connection = \ amqp.Connection(host='%s:%s' % (self.hostname, self.port), userid=self.username, password=self.password, virtual_host=self.virtual_host, insist=False) self.channel = self._connection.channel()
def open(self)
Open a connection to the AMQP compliant broker.
3.410035
2.776304
1.228264
payload = json.dumps(jsonpickle.Pickler(unpicklable=False).flatten(message_payload)) message = amqp.Message(payload) message.properties["delivery_mode"] = 2 name = 'majormode.%s.%s.%s' % (settings.ENVIRONMENT_STAGE, self.service_name.lower(), message_type.lower()) self...
def publish(self, message_type, message_payload)
Publish the specified object that the function automatically converts into a JSON string representation. This function use the lowered class name of the service as the AMQP routing key. For instance, if the class ``ExampleService`` inherits from the base class ``BaseService``, the meth...
2.737345
2.787587
0.981976
self._setUp() naming = 'skunkworks.lbs.%s.%s.%s' % (settings.ENVIRONMENT_STAGE, \ self.service_name.lower(), self.message_type.lower()) self.channel.queue_declare(queue=naming, durable=True, exclusive=False, auto_delete=False) self.channel.exchange_declare(exchange...
def run(self)
Consume message from the Advanced Message Queuing Protocol (AMPQ) compliant broker as soon as they are queued, and call the instance method ``__on_message_received`` that the inheriting class must have implemented.
3.375275
3.176911
1.062439
''' Args: np_dtype (numpy.dtype) Returns: (type) : Python data type that corresponds to the specified numpy dtype. ''' if np_dtype.type == np.object_: return object elif hasattr(np_dtype.type(0), 'item'): return type(np_dtype.type(0).item()) els...
def get_py_dtype(np_dtype)
Args: np_dtype (numpy.dtype) Returns: (type) : Python data type that corresponds to the specified numpy dtype.
3.700886
2.344554
1.578503
''' Return a `pandas.DataFrame` containing Python type information for the columns in `data_frame`. Args: data_frame (pandas.DataFrame) : Data frame containing data columns. Returns: (pandas.DataFrame) : Data frame indexed by the column names from `data_frame`, with t...
def get_py_dtypes(data_frame)
Return a `pandas.DataFrame` containing Python type information for the columns in `data_frame`. Args: data_frame (pandas.DataFrame) : Data frame containing data columns. Returns: (pandas.DataFrame) : Data frame indexed by the column names from `data_frame`, with the columns `...
3.076007
1.899374
1.619484
''' Return a `pandas.DataFrame` containing Python type information for the columns in `data_frame` and a `gtk.ListStore` matching the contents of the data frame. Args: data_frame (pandas.DataFrame) : Data frame containing data columns. Returns: (tuple) : The first element is ...
def get_list_store(data_frame)
Return a `pandas.DataFrame` containing Python type information for the columns in `data_frame` and a `gtk.ListStore` matching the contents of the data frame. Args: data_frame (pandas.DataFrame) : Data frame containing data columns. Returns: (tuple) : The first element is a data frame...
3.441827
1.5547
2.213821
''' Add columns to a `gtk.TreeView` for the types listed in `df_py_dtypes`. Args: tree_view (gtk.TreeView) : Tree view to append columns to. df_py_dtypes (pandas.DataFrame) : Data frame containing type information for one or more columns in `list_store`. list_store (gtk...
def add_columns(tree_view, df_py_dtypes, list_store)
Add columns to a `gtk.TreeView` for the types listed in `df_py_dtypes`. Args: tree_view (gtk.TreeView) : Tree view to append columns to. df_py_dtypes (pandas.DataFrame) : Data frame containing type information for one or more columns in `list_store`. list_store (gtk.ListStore) ...
2.173738
1.743455
1.246799
''' Set the text of a cell according to a [format][1] string. [1]: https://docs.python.org/2/library/string.html#formatstrings Args: tree_column (gtk.TreeViewColumn) : Tree view to append columns to. model_column_index (int) : Index in list store model corresponding to tre...
def set_column_format(tree_column, model_column_index, format_str, cell_renderer=None)
Set the text of a cell according to a [format][1] string. [1]: https://docs.python.org/2/library/string.html#formatstrings Args: tree_column (gtk.TreeViewColumn) : Tree view to append columns to. model_column_index (int) : Index in list store model corresponding to tree view colum...
3.332689
1.642227
2.029372
''' Set the text of a numeric cell according to [SI prefixes][1] For example, `1000 -> '1.00k'`. [1]: https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes Args: tree_column (gtk.TreeViewColumn) : Tree view to append columns to. model_column_index (int) : Index in list ...
def set_column_si_format(tree_column, model_column_index, cell_renderer=None, digits=2)
Set the text of a numeric cell according to [SI prefixes][1] For example, `1000 -> '1.00k'`. [1]: https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes Args: tree_column (gtk.TreeViewColumn) : Tree view to append columns to. model_column_index (int) : Index in list store model ...
3.533543
1.758635
2.009253
''' Handle the `'edited'` signal from a `gtk.CellRenderer` to: * Update the corresponding entry in the list store. * Update the corresponding entry in the provided data frame instance. The callback can be connected to the cell renderer as follows: cell_renderer.connect('edited', on_edit...
def on_edited_dataframe_sync(cell_renderer, iter, new_value, column, df_py_dtypes, list_store, df_data)
Handle the `'edited'` signal from a `gtk.CellRenderer` to: * Update the corresponding entry in the list store. * Update the corresponding entry in the provided data frame instance. The callback can be connected to the cell renderer as follows: cell_renderer.connect('edited', on_edited_dataframe...
3.800593
1.76308
2.155656
c14n_prog_name = lambda arg: os.path.basename(re.sub(r'\.py$', '', arg)) try: try: pid_maydaemon = int(file(pidfile).readline().strip()) except IOError, e: if e.errno == errno.ENOENT: return # nothing to suppress, so do nothing... raise ...
def remove_if_stale_pidfile(pidfile)
@pidfile: PID file to remove if it is staled. Exceptions are logged and are not propagated.
4.488667
4.477978
1.002387
try: try: os.link(own_file, lock_file) finally: os.unlink(own_file) except OSError, e: if e.errno == errno.EEXIST: log.warning("The lock file %r already exists - won't " "overwrite it. An other instance of ourself " ...
def take_file_lock(own_file, lock_file, own_content)
Atomically "move" @own_file to @lock_file if the latter does not exists, else just remove @own_file. @own_file: filepath of the temporary file that contains our PID @lock_file: destination filepath @own_content: content of @own_file Return True if the lock has been successfully taken, else False. ...
3.706412
3.744902
0.989722
pid = os.getpid() try: remove_if_stale_pidfile(pidfile) pid_write_file = pidfile + '.' + str(pid) fpid = open(pid_write_file, 'w') try: fpid.write("%s\n" % pid) finally: fpid.close() if not take_file_lock(pid_write_file, pidfile, "%s\n...
def lock_pidfile_or_die(pidfile)
@pidfile: must be a writable path Exceptions are logged. Returns the PID.
3.126448
3.470844
0.900775
try: pid = os.fork() if pid > 0: os._exit(0) # pylint: disable-msg=W0212 except OSError, e: log.exception("first fork() failed: %d (%s)", e.errno, e.strerror) sys.exit(1) os.setsid() os.umask(0) os.chdir("/") try: pid = os.fork() ...
def daemonize()
Daemonize the program, ie. make it run in the "background", detach it from its controlling terminal and from its controlling process group session. NOTES: - This function also umask(0) and chdir("/") - stdin, stdout, and stderr are redirected from/to /dev/null SEE ALSO: http://...
1.80403
1.882884
0.958121
if target_stream is None: target_fd = os.open(os.devnull, os.O_RDWR) else: target_fd = target_stream.fileno() os.dup2(target_fd, system_stream.fileno())
def redirect_stream(system_stream, target_stream)
Redirect a system stream to a specified file. `system_stream` is a standard system stream such as ``sys.stdout``. `target_stream` is an open file object that should replace the corresponding system stream object. If `target_stream` is ``None``, defaults to opening the ...
2.109777
1.909403
1.104941
def ensure_utf8_stream(stream): if not isinstance(stream, io.StringIO): stream = getwriter("utf-8")(getattr(stream, "buffer", stream)) stream.encoding = "utf-8" return stream sys.stdout, sys.stderr = (ensure_utf8_stream(s) ...
def ensure_utf8_streams()
Forces UTF-8 on stdout and stderr; in some crazy environments, they use 'ascii' encoding by default
3.007545
2.646853
1.136272
if etype not in ("begin", "end", "single"): raise ValueError("Event type must any of the following: 'begin', " "'end', 'single'") for handler in logging.getLogger().handlers: if isinstance(handler, MongoLogHandler): data = {"s...
def event(self, name, etype, **info)
Records an event to MongoDB. Events can be later viewed in web status. Parameters: name: the name of the event, for example, "Work". etype: the type of the event, can be either "begin", "end" or "single". info: any extra event attributes.
4.06329
3.686648
1.102164
''' Configure is used to add various ES ports you are working on. The user can add as many es ports as the one wants, but one will remain active at one point. ''' Config = ConfigParser.ConfigParser() if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.pa...
def configure(name, host, port, auth, current)
Configure is used to add various ES ports you are working on. The user can add as many es ports as the one wants, but one will remain active at one point.
3.730346
2.159913
1.727082
p1_parts = path1.split(path_sep) p2_parts = path2.split(path_sep) # special case when path1 is root if path1 == path_sep and len(p2_parts) >= 2: return p2_parts[1] if len(p2_parts) <= len(p1_parts): return '' for i, item in enumerate(p1_parts): if item != p2_parts[i]...
def content_item(path1, path2, path_sep='/')
if path1 is subpart of path2, get the next path item. example: path1 = '/foo' path2 = '/foo/bar/foo' -> 'bar'
2.045107
2.088321
0.979307
if len(path2) < len(path1): return 0 if path1 == path2: return ISFILE else: p1_parts = path1.split(path_sep) p2_parts = path2.split(path_sep) if len(p2_parts) < len(p1_parts): return 0 else: return compare_parts(p1_parts, p2_parts)
def compare_path_strings(path1, path2, path_sep='/')
find out, if path1 is a file, or a directory (or unknown).
2.312682
2.261413
1.022671
for i, item in enumerate(list1): if item != list2[i]: return 0 if len(list2) > len(list1): return ISDIR else: return ISFILE
def compare_parts(list1, list2)
if list2 does not start with list1, we can't really check and return 0
4.236105
3.806507
1.112859
rs = (grequests.get(u) for u in urls) return [content.json() for content in grequests.map(rs)]
def fetch_event(urls)
This parallel fetcher uses gevent one uses gevent
4.332698
4.531188
0.956195
headers, parts = template.evaluate(context) headers["From"] = sender headers["To"] = recipient hook(headers, parts) content = mime.buildMessage(headers, parts) return mailer.send(sender, recipient, content)
def sendTemplate(mailer, sender, recipient, template, context, hook=_nop)
Simple case for sending some e-mail using a template.
4.935321
4.839274
1.019847
''' Executes a `sketchtool export` command and returns formatted output :src_path: File to export. :type <str> :dest_dir: Items are exported at /dest_dir/name@scale.export_format e.g. `~/Desktop/Page 1@2x.png` :param export_format: 'png', 'pdf' etc. :type <ExportFormat> :param scale: Specify as 1.0, 2.0 etc....
def export_cmd(cmd, src_path, dest_dir=None, item_id=None, export_format=None, scale=None)
Executes a `sketchtool export` command and returns formatted output :src_path: File to export. :type <str> :dest_dir: Items are exported at /dest_dir/name@scale.export_format e.g. `~/Desktop/Page 1@2x.png` :param export_format: 'png', 'pdf' etc. :type <ExportFormat> :param scale: Specify as 1.0, 2.0 etc. :type...
3.712774
1.912701
1.941116
paths = [] for arp in [False, True]: paths.append(get_binary(arp=arp)) return paths
def get_binaries()
Download and return paths of all platform-specific binaries
7.724097
6.764743
1.141817
n_x = X.shape[0] # size of input layer n_h = 4 n_y = Y.shape[0] # size of output layer return (n_x, n_h, n_y)
def layer_sizes(X, Y)
Arguments: X -- input dataset of shape (input size, number of examples) Y -- labels of shape (output size, number of examples) Returns: n_x -- the size of the input layer n_h -- the size of the hidden layer n_y -- the size of the output layer
2.147286
2.647156
0.811167
np.random.seed(2) W1 = np.random.randn(n_h, n_x) * 0.01 b1 = np.zeros((n_h, 1)) W2 = np.random.randn(n_y, n_h) * 0.01 b2 = np.zeros((n_y, 1)) assert (W1.shape == (n_h, n_x)) assert (b1.shape == (n_h, 1)) assert (W2.shape == (n_y, n_h)) assert (b2.shape == (n_y, 1)) param...
def initialize_parameters(n_x, n_h, n_y)
Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: params -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) b1 -- bias vector of shape (n_h, 1) ...
1.247103
1.21744
1.024365
# Retrieve each parameter from the dictionary "parameters" W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] # Implement Forward Propagation to calculate A2 (probabilities) Z1 = np.dot(W1, X) + b1 A1 = np.tanh(Z1) Z2 = np.dot(W2, A1) + b2 ...
def forward_propagation(X, parameters)
Argument: X -- input data of size (n_x, m) parameters -- python dictionary containing your parameters (output of initialization function) Returns: A2 -- The sigmoid output of the second activation cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"
1.397159
1.401634
0.996808
m = Y.shape[1] # number of example # Compute the cross-entropy cost logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y)) cost = -np.sum(logprobs) / m cost = np.squeeze(cost) # makes sure cost is the dimension we expect. # E.g., turns [[17]] into 17 assert (...
def compute_cost(A2, Y)
Computes the cross-entropy cost given in equation (13) Arguments: A2 -- The sigmoid output of the second activation, of shape (1, number of examples) Y -- "true" labels vector of shape (1, number of examples) parameters -- python dictionary containing your parameters W1, b1, W2 and b2 Returns: ...
2.406796
2.578198
0.933519
m = X.shape[1] # First, retrieve W1 and W2 from the dictionary "parameters". W1 = parameters["W1"] W2 = parameters["W2"] # Retrieve also A1 and A2 from dictionary "cache". A1 = cache["A1"] A2 = cache["A2"] # Backward propagation: calculate dW1, db1, dW2, db2. dZ2 = A2 - Y ...
def backward_propagation(parameters, cache, X, Y)
Implement the backward propagation using the instructions above. Arguments: parameters -- python dictionary containing our parameters cache -- a dictionary containing "Z1", "A1", "Z2" and "A2". X -- input data of shape (2, number of examples) Y -- "true" labels vector of shape (1, number of example...
1.473077
1.566569
0.940321
# Retrieve each parameter from the dictionary "parameters" W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] # Retrieve each gradient from the dictionary "grads" dW1 = grads["dW1"] db1 = grads["db1"] dW2 = grads["dW2"] db2 = grads["db2"...
def update_parameters(parameters, grads, learning_rate=1.2)
Updates parameters using the gradient descent update rule given above Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients Returns: parameters -- python dictionary containing your updated parameters
1.302628
1.454801
0.8954
np.random.seed(3) n_x = layer_sizes(X, Y)[0] n_y = layer_sizes(X, Y)[2] # Initialize parameters, then retrieve W1, b1, W2, b2. # Inputs: "n_x, n_h, n_y". Outputs = "W1, b1, W2, b2, parameters". parameters = initialize_parameters(n_x, n_h, n_y) W1 = parameters["W1"] b1 = parameters...
def nn_model(X, Y, n_h, num_iterations=10000, print_cost=False)
Arguments: X -- dataset of shape (2, number of examples) Y -- labels of shape (1, number of examples) n_h -- size of the hidden layer num_iterations -- Number of iterations in gradient descent loop print_cost -- if True, print the cost every 1000 iterations Returns: parameters -- parameters...
1.487374
1.500065
0.99154
# Computes probabilities using forward propagation, # and classifies to 0/1 using 0.5 as the threshold. A2, cache = forward_propagation(X, parameters) predictions = np.array([1 if (i > 0.5) else 0 for i in A2[0]]) return predictions
def predict(parameters, X)
Using the learned parameters, predicts a class for each example in X Arguments: parameters -- python dictionary containing your parameters X -- input data of size (n_x, m) Returns predictions -- vector of predictions of our model (red: 0 / blue: 1)
4.157122
5.397433
0.770203
if not key: raise ValueError("请配置key,如果还没有key," "可以到这里申请一个:http://sc.ftqq.com/3.version") url = 'https://sc.ftqq.com/%s.send' % key requests.post(url, data={'text': title, 'desp': content})
def server_chan_push(title, content, key=None)
使用server酱推送消息到微信,关于server酱, 请参考:http://sc.ftqq.com/3.version :param title: str 消息标题 :param content: str 消息内容,最长64Kb,可空,支持MarkDown :param key: str 从[Server酱](https://sc.ftqq.com/3.version)获取的key :return: None
3.877644
3.655816
1.060678
if not send_key: raise ValueError("请配置通道send_key,如果还没有," "可以到这里创建通道获取:https://pushbear.ftqq.com/admin/#/") api = "https://pushbear.ftqq.com/sub" requests.post(api, data={'text': title, 'desp': content, "sendkey": send_key})
def bear_push(title, content, send_key=None)
使用PushBear推送消息给所有订阅者微信,关于PushBear, 请参考:https://pushbear.ftqq.com/admin/#/ :param title: str 消息标题 :param content: str 消息内容,最长64Kb,可空,支持MarkDown :param send_key: str 从[PushBear](https://pushbear.ftqq.com/admin/#/)获取的通道send_key :return: None
6.250151
4.179849
1.495305
se = EmailSender(from_=sender, pw=pw, service=service) se.send_email(to=to, subject=subject, content=content, files=files) se.quit()
def send_email(sender, pw, to, subject, content, files=None, service='163')
send email, recommended use 163 mailbox service, as it is tested. :param sender: str email address of sender :param pw: str password for sender :param to: str email addressee :param subject: str subject of email :param content: str content of email :param...
2.768877
3.158393
0.876673
msg = MIMEMultipart() msg['from'] = self.from_ msg['to'] = to msg['subject'] = subject txt = MIMEText(content) msg.attach(txt) # 添加附件 if files is not None: for file in files: f = MIMEApplication(open(file, 'rb').read()...
def _construct_msg(self, to, subject, content, files=None)
构造email信息 parameters --------------- subject 邮件主题 content 邮件文本内容 files 附件(list) 可以是相对路径下的文件,也可以是绝对路径下的文件; 推荐使用绝对路径。 return -------------- msg 构造好的邮件信息
1.752262
1.805831
0.970336
msg = EmailSender._construct_msg(self, to, subject, content, files=files) try: self.smtp.sendmail(self.from_, to, str(msg)) except: self.login() self.smtp.sendmail(self.from_, to, str(msg))
def send_email(self, to, subject, content, files=None)
登录邮箱,发送msg到指定联系人 :param to: str: 收件人邮箱 :param subject: str: 主题 :param content: str: 内容 :param files: list: 附件列表 :return: None
2.755124
3.175046
0.867743
'''walks through tree and yields each node''' if node is None: for root in self.stack: yield from self.nodes(root) else: yield node if node.is_container(): for child in node.children: yield from self.nodes(ch...
def nodes(self, node=None)
walks through tree and yields each node
3.907356
3.23081
1.209404
'''Print tree''' def print_node(node, depth=0): print('{}{}'.format(' ' * depth, repr(node))) if node.is_container(): for child in node.children: print_node(child, depth + 1) for root in self.stack: print_node(root)
def debug_print(self)
Print tree
4.298379
4.142726
1.037572
''' Function decorator which adds "context" around a group of TestCases and may have a `before` and `after` func. >>> s = Suite() >>> @s.context('context 1') ... def _(): ... @s.before ... def _(): print('before 1 called.') ...
def context(self, message)
Function decorator which adds "context" around a group of TestCases and may have a `before` and `after` func. >>> s = Suite() >>> @s.context('context 1') ... def _(): ... @s.before ... def _(): print('before 1 called.') ... @s....
3.182085
1.332915
2.387312
''' Function decorator which adds a TestCase to the Suite >>> s = Suite() >>> @s.it('always passes') ... def _(): pass >>> list(s.nodes()) [<Container: root>, <TestCase: always passes>] `repeat` will add multiple test cases with ext...
def it(self, message, repeat=None)
Function decorator which adds a TestCase to the Suite >>> s = Suite() >>> @s.it('always passes') ... def _(): pass >>> list(s.nodes()) [<Container: root>, <TestCase: always passes>] `repeat` will add multiple test cases with extra parameters. ...
3.534307
1.567326
2.254992
# Permits use of CSRF middleware context = RequestContext(request, {}) template = Template("") response = HttpResponse(template.render(context)) # Sets a cookie with a 10 years lifetime, accessible only via HTTP: response.set_cookie(COOKIE_KEY, value=COOKIE_SPAM, httponly=True, ...
def spammer_view(request)
View for setting cookies on spammers.
7.195254
7.007507
1.026792
mod_name, attr = object_name.rsplit('.', 1) mod = import_module(mod_name) return getattr(mod, attr)
def load_object_by_name(object_name)
Load an object from a module by name
2.43308
2.401091
1.013323
class TestSchema(BaseSchema): attr_1 = StringNode() attr_2 = IntegerNode() @property def attr_3(self): return 'FooBar' @staticmethod def prepare_attr_1(value): return 'Attr#{}'.format(value) @staticmethod def prepare_at...
def bench_factory()
Benchmark for 1000 objects with 2 fields.
4.860075
4.595308
1.057617
schema = Schema({ Required('attr_1'): str, Required('attr_2'): int}) return [schema(obj) for obj in object_loader()]
def bench_voluptuous()
Benchmark for 1000 objects with 2 fields.
10.128994
8.281913
1.223026
class FooSerializer(serpy.DictSerializer): # Use a Field subclass like IntField if you need more validation. attr_2 = serpy.IntField() attr_1 = serpy.StrField() return [FooSerializer(obj).data for obj in object_loader()]
def bench_serpy()
Beanchmark for 1000 objects with 2 fields.
9.98258
8.15519
1.224077
(language_code, country_code) = Locale.decompose_locale(locale, strict) return Locale(language_code, country_code)
def from_string(locale, strict=True)
Return an instance ``Locale`` corresponding to the string representation of a locale. @param locale: a string representation of a locale, i.e., a ISO 639-3 alpha-3 code (or alpha-2 code), optionally followed by a dash character ``-`` and a ISO 3166-1 alpha-2 code. @param...
4.555951
6.074267
0.750041
return self.language_code[:2] if self.country_code is None \ else '%s-%s' % (self.language_code[:2], self.country_code)
def to_http_string(self)
Return the string representation of the locale compatible with the HTTP header ``Accept-Language`` as specified in `RFC 7231 <https://tools.ietf.org/html/rfc7231#section-5.3.5>_` The Accept-Language request HTTP header advertises which languages the client is able to understand, and whi...
4.564733
4.189433
1.089583
if locale is None: return ('eng', None) match = REGEX_LOCALE.match(locale) if match is None: if strict == True: raise Locale.MalformedLocaleException() match = REGEX_JAVA_LOCALE.match(locale) if match is None: ...
def decompose_locale(locale, strict=True)
Return the decomposition of the specified locale into a language code and a country code. @param locale: a string representation of a locale, i.e., a ISO 639-3 alpha-3 code (or alpha-2 code), optionally followed by a dash character ``-`` and a ISO 3166-1 alpha-2 code. If ``Non...
3.373379
2.950002
1.143518
obj = load_object(dropin) try: drops = getattr(obj, self.drops_type) except AttributeError: try: drops = load_object('%s.%s' % (dropin, self.drops_type)) except ImportError: drops = None if hasattr(drops, '__dro...
def load_drops(self, dropin)
Load `drops` from the given dropin. Args: dropin (string): path of a dropin, e.g. dropin.auth Returns: An iterable contains the drops object in the given dropin This method load drops object by some sort of convension. For example, assuming we want to load drop...
3.12749
2.955719
1.058115
drops = self.app.extensions['dropin'].setdefault(self.drops_type, []) drops.extend(self.load_drops(dropin))
def register_drops(self, dropin)
Register the `drops` in given `dropin` to a flask app. Args: app (Flask): the flask app to be initialized dropin (string): path of a python module or object, e.g. dropin.auth This is the only method that a drops loader **must** implment. The default behavior in the bas...
8.750043
5.396955
1.621293
for other in others: for k, v in other: setattr(cls, k, BoundValue(cls, k, v.value))
def merge(cls, *others)
Merge the `others` schema into this instance. The values will all be read from the provider of the original object.
5.679926
6.526242
0.870321
if ticket_url.startswith('http://') or ticket_url.startswith('https://'): o = urlparse(ticket_url) scheme, netloc = o.scheme, o.netloc else: scheme = 'http' (netloc, _) = ticket_url.split('/', 1) return '%s://%s' % (scheme, netloc)
def find_tracker_url(ticket_url)
Given http://tracker.ceph.com/issues/16673 or tracker.ceph.com/issues/16673, return "http://tracker.ceph.com".
2.310402
2.188703
1.055603
if not self.is_array: return self.field_type(value) if isinstance(value, (list, tuple, set)): return [self.field_type(item) for item in value] return self.field_type(value)
def field_value(self, value)
Validate against NodeType.
2.678985
2.64576
1.012558
if not self.is_array: return self._valid(value) if isinstance(value, (list, set, tuple)): return all([self._valid(item) for item in value]) return self._valid(value)
def is_valid(self, value)
Validate value before actual instance setting based on type. Args: value (object): The value object for validation. Returns: True if value validation succeeds else False.
3.092579
3.274952
0.944313
"Return dir(self)." my_vars = set(self) skips = self.bad_names | my_vars yield from ( attr for attr in dir(type(self)) if ( attr not in skips and not ( attr.startswith('_') and n...
def config_dir(self)
Return dir(self).
6.347437
5.166834
1.228496
"Special property containing the memoized data." try: return self.__attr_data except AttributeError: self.__attr_data = type( ''.join([type(self).__name__, 'EmptyData']), (), { '__module__': type(self)._...
def _attr_data_(self)
Special property containing the memoized data.
5.794132
4.136577
1.400707
self.__attr_data = type( ''.join([type(self).__name__, 'Data']), (), { '__module__': type(self).__module__, '__slots__': tuple(set(slots)) } )()
def _attr_data_(self, slots)
Does not work as expected, makes an empty object with a new __slots__ definition.
5.138521
4.42451
1.161376
"Special property containing functions to be lazily-evaluated." try: return self.__attr_func except AttributeError: self.__attr_func = type( ''.join([type(self).__name__, 'EmptyFuncs']), (), { '__module...
def _attr_func_(self)
Special property containing functions to be lazily-evaluated.
6.958312
4.415403
1.575918