code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
res = match_phase(qpi, model=model, n0=n0, r0=r0, c0=c0, ret_center=ret_center, ret_pha_offset=ret_pha_offset, ret_qpi=ret_qpi, **imagekw) return res
def analyze(qpi, model, n0, r0, c0=None, imagekw={}, ret_center=False, ret_pha_offset=False, ret_qpi=False)
Fit refractive index and radius to a phase image of a sphere Parameters ---------- qpi: QPImage Quantitative phase image information model: str Name of the light-scattering model (see :const:`qpsphere.models.available`) n0: float Approximate refractive index of the s...
1.901235
2.320967
0.819156
''' Remove temporary build folders ''' tempdirs = [Dir.BUILD, Dir.COCOA_BUILD, Dir.LIB] for tempdir in tempdirs: if os.path.exists(tempdir): shutil.rmtree(tempdir, ignore_errors=True)
def rm_tempdirs()
Remove temporary build folders
4.71266
4.274566
1.102489
''' Returns the contents of 'pyglass/lib' as a list of 'lib/*' items for package_data ''' lib_list = [] for (root, dirs, files) in os.walk(Dir.LIB): for filename in files: root = root.replace('pyglass/', '') lib_list.append(join(root, filename)) return lib_list
def lib_list()
Returns the contents of 'pyglass/lib' as a list of 'lib/*' items for package_data
6.227969
2.894146
2.151919
''' Match a pattern in a string ''' rexobj = REX(pattern, None) rexpatstr = reformat_pattern(pattern) #print "rexpatstr: ", rexpatstr rexpat = re.compile(rexpatstr) rexobj.rex_patternstr = rexpatstr rexobj.rex_pattern = rexpat line_count = 1 for line in search_string.spli...
def match_string(pattern, search_string)
Match a pattern in a string
3.667293
3.584018
1.023235
''' Popuate the result object and append it to the rexobj results. ''' resobj = REXResult(mobj, loc) rexobj.matches.append(resobj) rexobj.res_count += 1
def populate_resobj(rexobj, mobj, loc)
Popuate the result object and append it to the rexobj results.
7.169594
3.824578
1.874611
''' The function will match a pattern in a file and return a rex object, which will have all the matches found in the file. ''' # Validate user data. if pattern is None: return None if os.stat(filename).st_size == 0: return None rexobj = REX(pattern, filename) re...
def match_file(pattern, filename)
The function will match a pattern in a file and return a rex object, which will have all the matches found in the file.
3.625983
2.82223
1.284794
''' The function takes a multi-line output/string with the format "name/descr : value", and converts it to a dictionary object with key value pairs, where key is built from the name/desc part and value as the value. eg: "Serial Number: FCH1724V1GT" will be translated to dict['serial_numb...
def parse_lrvalue_string(search_string, delimiter=":")
The function takes a multi-line output/string with the format "name/descr : value", and converts it to a dictionary object with key value pairs, where key is built from the name/desc part and value as the value. eg: "Serial Number: FCH1724V1GT" will be translated to dict['serial_number'] = "FCH1...
3.71696
1.873144
1.984343
''' The function is an extension of the parse_lrvalue_string() API. The function takes a multi-line output/string of the format "Category: xyz name: foo id: bar Category: abc name: foox id: barx : " It splits the output based on the splitstring passed as ...
def parse_multi_lrvalue_string(search_string, split_string, delimiter=":")
The function is an extension of the parse_lrvalue_string() API. The function takes a multi-line output/string of the format "Category: xyz name: foo id: bar Category: abc name: foox id: barx : " It splits the output based on the splitstring passed as argument (eg...
9.364865
1.62145
5.775613
''' Given a string in a tabular format, parse it and return a dictionary @args: search_string: This is a string in tabular format (e.g.: output of df command) header_keys: This is a list of strings for the headers. delimiter(optional): Default is None, which translates to...
def parse_tabular_string(search_string, header_keys, delimiter=None, merge_list=None)
Given a string in a tabular format, parse it and return a dictionary @args: search_string: This is a string in tabular format (e.g.: output of df command) header_keys: This is a list of strings for the headers. delimiter(optional): Default is None, which translates to spaces ...
3.810437
2.033241
1.874071
''' print all the results. ''' print("-" * 60) print("Match count: ", rexobj.res_count) matches = rexobj.matches for match in matches: print("Loc:", match.loc, ":: ") for key in match.named_groups.keys(): print("%s: %s" % (key, match.named_groups...
def dump_rexobj_results(rexobj, options=None)
print all the results.
5.156551
4.591565
1.123049
''' Return a matched value for the key for a specific match from the results. ''' if rexobj is None: return None if rexobj.res_count == 0: return None try: return rexobj.matches[index].named_groups[key] except IndexError: return None except KeyError:...
def get_match_value(rexobj, key, index=0)
Return a matched value for the key for a specific match from the results.
4.963736
2.892273
1.716206
path = os.path.join(resource_dir_path, plugin_name) if not os.path.exists(path): os.makedirs(path) path = os.path.join(path, resource_name) logger.debug("Saving {}".format(path)) with open(path, 'wb') as f: f.write(base64.b64decode(resource_data))
def save_resource(plugin_name, resource_name, resource_data)
Save a resource in local cache :param plugin_name: Name of plugin this resource belongs to :type plugin_name: str :param resource_name: Name of resource :type resource_name: str :param resource_data: Resource content - base64 encoded :type resource_data: str :rtype: None
1.850611
1.960611
0.943895
self.count_lock.acquire() if nb > self.shared['workers']: nb = self.shared['workers'] self.count_lock.release() for x in xrange(nb): self.tasks.put_nowait(WorkerExit)
def kill(self, nb = 1)
Kill one or many workers.
4.834742
4.264256
1.133783
self.count_lock.acquire() self.shared['max_workers'] = nb if self.shared['workers'] > self.shared['max_workers']: self.kill(self.shared['workers'] - self.shared['max_workers']) self.count_lock.release()
def set_max_workers(self, nb)
Set the maximum workers to create.
2.940792
2.896747
1.015205
for x in xrange(nb): self.count_lock.acquire() self.shared['workers'] += 1 xid = self.shared['workers'] self.kill_event.clear() self.count_lock.release() w = WorkerProc(xid, self.queue, self.shared, self.tasks, self.life_time, se...
def add(self, nb = 1, name = None)
Create one or many workers.
4.708605
4.37487
1.076285
self.count_lock.acquire() if not self.shared['workers']: self.add(name = name) self.count_lock.release() self.queue.put_nowait((target, callback, name, args, kargs))
def put(self, target, callback = None, name = None, *args, **kargs)
Start task. @target: callable to run with *args and **kargs arguments. @callback: callable executed after target.
4.438367
4.606224
0.963559
self.queue.close() self.count_lock.acquire() self.kill(self.shared['workers']) self.count_lock.release() self.tasks.close() self.terminate() self.kill_event.wait(wait)
def killall(self, wait = None)
Kill all active workers. @wait: Seconds to wait until last worker ends. If None it waits forever.
6.669568
5.872162
1.135794
''' Parameters ---------- form_values : list List of ``(key, value)`` tuples, where ``key`` corresponds to the ancestor keys of the respective value joined by ``'.'``. For example, the key ``'a.b.c'`` would be expanded to the dictionary ``{'a': {'b': {'c': 'foo'}}}``. ...
def expand_items(form_values, sep='.')
Parameters ---------- form_values : list List of ``(key, value)`` tuples, where ``key`` corresponds to the ancestor keys of the respective value joined by ``'.'``. For example, the key ``'a.b.c'`` would be expanded to the dictionary ``{'a': {'b': {'c': 'foo'}}}``. Returns ...
3.598142
1.775486
2.026567
''' Args: root (dict) : Nested dictionary (e.g., JSON object). parents (list) : List of ancestor keys. Returns ------- list List of ``(key, value)`` tuples, where ``key`` corresponds to the ancestor keys of the respective value joined by ``'.'``. For example, ...
def flatten_dict(root, parents=None, sep='.')
Args: root (dict) : Nested dictionary (e.g., JSON object). parents (list) : List of ancestor keys. Returns ------- list List of ``(key, value)`` tuples, where ``key`` corresponds to the ancestor keys of the respective value joined by ``'.'``. For example, for the i...
3.252472
1.502519
2.164679
''' Parameters ---------- schema : dict `JSON schema <http://spacetelescope.github.io/understanding-json-schema/>`_ ''' fields = [] def get_field_record(i, key, value, parents): if value.get('private') or 'default' not in value: raise Skip field = (len(pa...
def get_fields_frame(schema)
Parameters ---------- schema : dict `JSON schema <http://spacetelescope.github.io/understanding-json-schema/>`_
5.116057
4.543086
1.12612
''' Parameters ---------- schema : dict jsonschema definition. Each property *must* have a default value. device_name : False or None or str or list_like, optional GStreamer video source device name(s). If `None` (default), first available video device is used. If ...
def schema_dialog(schema, data=None, device_name=None, max_width=None, max_fps=None, **kwargs)
Parameters ---------- schema : dict jsonschema definition. Each property *must* have a default value. device_name : False or None or str or list_like, optional GStreamer video source device name(s). If `None` (default), first available video device is used. If `False`, vid...
4.224108
2.490225
1.696276
stream = StringIO() with redirect_stdout(stream): return_value = callable(*args, **kwargs) assert return_value.stdout is None, "stdout appears to have already been captured" return CaptureResult(return_value=return_value.return_value, stdout=stream.getvalue(), ...
def _capture_stdout(callable: Callable[..., CaptureResult], *args, **kwargs) -> CaptureResult
Captures content written to standard out. :param callable: the callable to wrap :param args: positional arguments passed to the callable :param kwargs: keyword arguments passed to the callable :return: the captured result
3.143932
3.334654
0.942806
stream = StringIO() with redirect_stderr(stream): return_value = callable(*args, **kwargs) assert return_value.stderr is None, "stderr appears to have already been captured" return CaptureResult(return_value=return_value.return_value, stdout=return_value.stdout, ...
def _capture_stderr(callable: Callable[..., CaptureResult], *args, **kwargs) -> CaptureResult
Captures content written to standard error. :param callable: the callable to wrap :param args: positional arguments passed to the callable :param kwargs: keyword arguments passed to the callable :return: the captured result
3.440675
3.628185
0.948319
try: return_value = callable(*args, **kwargs) assert return_value.exception is None, "exception appears to have already been captured" return CaptureResult(return_value=return_value.return_value, stdout=return_value.stdout, stderr=ret...
def _capture_exceptions(callable: Callable[..., CaptureResult], *args, **kwargs) -> CaptureResult
Captures exceptions, adding them to the captured result, opposed to raising them. :param callable: the callable to wrap :param args: positional arguments passed to the callable :param kwargs: keyword arguments passed to the callable :return: the captured result
2.916484
3.046016
0.957475
def wrapped(*args, **kwargs): result = CaptureWrapBuilder._capture_exceptions(*args, **kwargs) if result.exception is not None: if not capture_decider(result.exception): raise result.exception return result return wrapped
def _create_capture_exceptions(capture_decider: Callable[[BaseException], bool]) -> Callable
Creates exception capturer using given capture decider. :param capture_decider: given the exception as the first arguments, decides whether it should be captured or not (and hence raised) :return:
4.075501
4.688522
0.869251
def wrapped(*args, **kwargs): return wrapper(method, *args, **kwargs) return wrapped
def _wrap(method: Callable, wrapper: Callable) -> Callable
Wraps the given callable method in the given wrapper, passing through the callable's arguments to the wrapper. :param method: the callable method to wrap :param wrapper: the wrapper to wrap callable with :return:
3.715402
4.60253
0.807252
def capturing_callable(*args, **kwargs) -> CaptureResult: return CaptureResult(return_value=callable(*args, **kwargs)) if self.capture_exceptions: # Need to capture exceptions first else other (non-return) captured information will be lost exceptions_wrapper...
def build(self, callable: Callable) -> Callable[..., CaptureResult]
Build a method that captures the required information when the given callable is called. :param callable: the callable to capture information from :return: the wrapped callable
3.100822
3.123049
0.992883
d = dict(os.environ, **(oget(env, {}))) # workaround for Windows+Python3 environment if not SHOULD_NOT_ENCODE_ARGS: return dict((k.encode(encoding), v.encode(encoding)) for k, v in d.items()) else: return d
def __convert_env(env, encoding)
Environment variables should be bytes not unicode on Windows.
7.23291
6.748093
1.071845
return subprocess.call( args=__convert_args(args, shell, cmd_encoding), shell=shell, cwd=cwd, env=__convert_env(env, cmd_encoding), stdin=stdin, stdout=stdout, stderr=stderr)
def execute_command(args, shell=False, cwd=None, env=None, stdin=None, stdout=None, stderr=None, cmd_encoding='utf-8')
Execute external command :param args: command line arguments : [unicode] :param shell: True when using shell : boolean :param cwd: working directory : string :param env: environment variables : dict :param stdin: standard input :param stdout: standard output :param stderr: standard error ...
3.082665
3.216642
0.958349
p = subprocess.Popen( __convert_args(args, shell, cmd_encoding), shell=shell, cwd=cwd, env=__convert_env(env, cmd_encoding), stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_data, stderr_data = p.communicate() return p.returncode, stdout_data, stderr_data
def capture_command(args, shell=False, cwd=None, env=None, stdin=None, cmd_encoding='utf-8')
Execute external command and capture output :param args: command line arguments : [string] :param shell: True when using shell : boolean :param cwd: working directory : string :param env: environment variables : dict :param stdin: standard input :param cmd_encoding: command line encoding: string...
2.319641
2.321163
0.999344
if os.name == 'nt': # check the output of TASKLIST command returncode, stdout, stderr = capture_command(['TASKLIST', '/FO', 'CSV', '/NH', '/FI', 'PID eq %d' % pid]) return stdout[:1] == b'"' else: if pid == 0: # According to "man 2 kill" PID 0 has a special mean...
def pid_exists(pid)
Check whether pid exists in the current process table. stole from https://github.com/giampaolo/psutil/blob/master/psutil/_psposix.py
2.641873
2.51402
1.050856
return math.sqrt( (self.endpoint_a.northing - self.endpoint_b.northing) ** 2 + (self.endpoint_a.easting - self.endpoint_b.easting) ** 2 )
def length(self)
Return length(meter) of the line :return: length(meter) of the line :rtype: float
2.965636
2.792522
1.061992
total_length = 0 for location_a, location_b in zip( self.locations[:-1], self.locations[1:]): total_length += Line(location_a, location_b).length return total_length
def length(self)
Calculate total length of the polyline :return: total length in meters :rtype: float
3.654409
3.231772
1.130776
args, otherthings = parse_known_args() if args.version: print_version() return 0 directory = os.path.abspath(os.curdir) if args.folder: directory = args.folder verbosity = 0 if args.verbose: verbosity = verbosity_level['low'] elif args.verbosity: ...
def main()
Main
4.961927
5.018012
0.988823
global _old_hook assert _old_hook is None def new_hook(etype, eval, trace): gobject.idle_add(dialog_handler, dialog, etype, eval, trace, extra) if invoke_old_hook: _old_hook(etype, eval, trace) _old_hook = sys.excepthook sys.excepthook = new_hook
def install_hook(dialog=SimpleExceptionDialog, invoke_old_hook=False, **extra)
install the configured exception hook wrapping the old exception hook don't use it twice :oparam dialog: a different exception dialog class :oparam invoke_old_hook: should we invoke the old exception hook?
3.16942
3.872942
0.818349
def is_target_node(node): return isinstance(node, base.EOT) or (node is root_action) # store per-turn results from the bottom up. realistic_ends_by_node = dict() for node in root_action.post_order_nodes(): # bottom up to this action # only work with EOT ...
def _summarize_action(self, root_action)
Return a dictionary with various information about this root_action. Note: Scoring assumes that each actor makes the "best" choices in their turn based on the simulation available.
5.296698
5.284708
1.002269
active_start = self._score_eot_for_actor(start_eot, active) passive_start = self._score_eot_for_actor(start_eot, passive) active_end = self._score_eot_for_actor(end_eot, active) passive_end = self._score_eot_for_actor(end_eot, passive) return (active_end - passive_end) -...
def _relative_score(self, start_eot, end_eot, active, passive)
Return the balance of perception between the two nodes. A positive score indicates the result is relatively better for active.
1.793085
1.688833
1.06173
# currently just simple sum of own attributes # could be much more sophisticated in both analysis (e.g. formulas) # and breadth of items analyzed (e.g. require other actor, the board) end_state = eot.parent a = {'player': end_state.player, 'opponent': end_st...
def _score_eot_for_actor(self, eot, actor)
Have the actor evaluate the end of turn for itself only.
9.000513
8.756815
1.02783
root_board = root_action.parent.board action_detail = root_action.position_pair score = self._relative_score(root_action, leaf_eot, root_action.parent.player, root_action.parent.opponent) # mana drain info...
def _summarize_result(self, root_action, leaf_eot)
Return a dict with useful information that summarizes this action.
3.864543
3.733588
1.035075
with h5py.File(h5path, mode="a") as h5: if identifier in h5: grp = h5[identifier] else: grp = h5.create_group(identifier) ds = grp.create_dataset("phase_error_{:05d}".format(index), data=mphase-phase) ds.attrs["index initia...
def export_phase_error_hdf5(h5path, identifier, index, phase, mphase, model, n0, r0, spi_params)
Export the phase error to an hdf5 file Parameters ---------- h5path: str or pathlib.Path path to hdf5 output file identifier: str unique identifier of the input phase (e.g. `qpimage.QPImage["identifier"]`) index: int iteration index phase: 2d real-valued np.ndarr...
2.448595
2.437319
1.004626
for path in paths: try: fP = pkg_resources.resource_filename(pkg, path) except ImportError: cls.log.warning( "No package called {}".format(pkg) ) else: if not os.path.isfile(fP): ...
def scripts(cls, pkg, metadata, paths=[], **kwargs)
This class method is the preferred way to create SceneScript objects. :param str pkg: The dotted name of the package containing the scripts. :param metadata: A mapping or data object. This parameter permits searching among scripts against particular criteria. Its use is application specific...
3.46753
3.58391
0.967527
doc = docutils.utils.new_document(name, SceneScript.settings) parser = docutils.parsers.rst.Parser() parser.parse(text, doc) return doc
def read(text, name=None)
Read a block of text as a docutils document. :param str text: Scene script text. :param str name: An optional name for the document. :return: A document object.
5.203013
4.989189
1.042858
def constrained(entity): return ( len(entity["options"].get("types", [])) + len(entity["options"].get("states", [])) ) rv = OrderedDict() performing = defaultdict(set) pool = list(personae) self.log.debug(pool) ...
def select(self, personae, relative=False, roles=1)
Select a persona for each entity declared in the scene. :param personae: A sequence of Personae. :param bool relative: Affects imports from namespace packages. Used for testing only. :param int roles: The maximum number of roles allocated to each persona. :return: An Ordered...
4.357669
4.259792
1.022977
# See 'citation' method in # http://docutils.sourceforge.net/docutils/parsers/rst/states.py for c, p in mapping.items(): self.doc.note_citation(c) self.doc.note_explicit_target(c, c) c.persona = p self.log.debug("{0} to be played by {1}".f...
def cast(self, mapping)
Allocate the scene script a cast of personae for each of its entities. :param mapping: A dictionary of {Entity, Persona} :return: The SceneScript object.
9.09941
10.006555
0.909345
model = Model(self.fP, self.doc) self.doc.walkabout(model) return model
def run(self)
Parse the script file. :rtype: :py:class:`~turberfield.dialogue.model.Model`
16.94821
18.292559
0.926508
print('starting MyApp...') if context['debug']: print('Context:') for k in context: print('Key: {}\nValue: {}'.format(k, context[k])) print('Done!') return 0
def my_main(context)
The starting point for your app.
5.724161
5.032526
1.137433
board, player, opponent, extra_actions = _state_investigator.get_versus() if extra_actions: extra_actions = 1 # limit value for realistic time if board is None: return tuple() averaged_summaries = list() # default return value is empty # keep a separate advisor for each simulation to ...
def versus_summaries(turns=2, sims_to_average=2, async_results_q=None)
Return summaries of the likely resutls of each available action.. Arguments: - turns: how many turns to simulate. - in 2013, 1 is fast (seconds), 2 is slow (seconds), 3 who knows - sims_to_average: how many times to run the simulation to get more representative average results of each actio...
4.01307
4.028597
0.996146
pathname = '' (filename_without_extension, _file_extension_) = os.path.splitext(filename) for i in range(min(directory_depth, len(filename_without_extension))): pathname += filename_without_extension[i] + pathname_separator_character return pathname
def build_tree_pathname(filename, directory_depth=8, pathname_separator_character=os.sep)
Return a pathname built of the specified number of sub-directories, and where each directory is named after the nth letter of the filename corresponding to the directory depth. Examples:: >>> build_tree_pathname('foo.txt', 2, '/') 'f/o/' >>> build_tree_pathname('0123456789abcdef') ...
2.632049
3.953447
0.665761
return build_tree_pathname(filename, directory_depth, pathname_separator_character) + filename
def build_tree_file_pathname(filename, directory_depth=8, pathname_separator_character=os.sep)
Return a file pathname which pathname is built of the specified number of sub-directories, and where each directory is named after the nth letter of the filename corresponding to the directory depth. Examples:: >>> build_tree_file_pathname('foo.txt', 2, '/') 'f/o/foo.txt' >>> build...
3.762341
8.511533
0.442029
_absolute_path = os.path.normpath(absolute_path) _relative_path = os.path.normpath(relative_path) index = _absolute_path.rfind(_relative_path) if index == -1 or len(_relative_path) + index < len(_absolute_path): raise ValueError('The relative path does not end the specified absolute path')...
def find_root_path(absolute_path, relative_path)
Return the root path of a path relative to an absolute path. Example: @param absolute_path: an absolute path that is ended by the specified relative path. @param relative_path: a relative path that ends the specified absolute path. @return: the root path of the relative path.
2.604413
2.522244
1.032578
hash_algorithm = hashlib.new(hash_algorithm_name) if sys.platform == "win32": import ctypes sectors_per_cluster = ctypes.c_ulonglong(0) bytes_per_sector = ctypes.c_ulonglong(0) root_path_name = ctypes.c_wchar_p(u"C:\\") ctypes.windll.kernel32.GetDiskFreeSpaceW(root_...
def get_file_checksum(file_path_name, hash_algorithm_name='md5')
Generate the MD5 checksum of the specified file. @param file_path_name: the absolute path and name of the file to generate its MD5 checksum. @param hash_algorithm_name: specify the hash algorithm to use. Refer to ``hashlib.algorithms`` to get the names of the hash algorithms guarante...
2.076845
2.16784
0.958025
try: os.makedirs(path) except OSError, error: # Ignore if the directory has been already created. if error.errno <> errno.EEXIST: raise error
def make_directory_if_not_exists(path)
Create the specified path, making all intermediate-level directories needed to contain the leaf directory. Ignore any error that would occur if the leaf directory already exists. @note: all the intermediate-level directories are created with the default mode is 0777 (octal). @param path: the ...
4.893567
5.203284
0.940477
if os.path.exists(destination_file_pathname): os.remove(destination_file_pathname) shutil.move(source_file_pathname, destination_file_pathname)
def move_file(source_file_pathname, destination_file_pathname)
Move the the specified file to another location. If the destination already exists, it is replaced silently. This function is an alternative to ``shutil.move(src, dst)``, which might raise ``OSError`` if the destination already exists. @param source_file_pathname: the complete path and name of the fi...
1.748147
2.709899
0.645097
if file_path_name and file_path_name != '-': file_handle = codecs.open(file_path_name, mode=mode, encoding='utf-8') else: file_handle = sys.stdout try: yield file_handle finally: if file_handle is not sys.stdout: file_handle.close()
def smart_open(file_path_name, mode='r', encoding='utf-8')
Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding. The default file mode is 'r' meaning to open the file in read mode. @param file_path_name: the absolute path and name of the file to open. @param mode: indicate how the file is to ...
1.974144
2.775075
0.711384
def is_exe(file_path_name): return os.path.isfile(file_path_name) and os.access(file_path_name, os.X_OK) is_platform_windows = (platform.system() == 'Windows') fpath, _fname = os.path.split(exe_name) if fpath: if is_exe(exe_name): return exe_name else: for ...
def which(exe_name)
Locate a program file in the user's path. @param exec_name: name of the executable file. @return: ``None`` if the executable has not been found in the user's path, or the path for the executable file.
1.602711
1.670991
0.959138
def haversine(lat1, lon1, lat2, lon2): if abs(lat1) > 90 or abs(lat2) > 90: raise InvalidCoordinate('invalid latitude') if abs(lon1) > 180 or abs(lon2) > 180: raise InvalidCoordinate('invalid longitude') # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radian...
Calculate the great circle distance between two points on the earth (specified in decimal degrees) Thanks to a answer on stackoverflow by Michael Dunn. http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points
null
null
null
def get_time(filename, tags): # use exif 'Image DateTime' field as the time if 'Image DateTime' in tags.keys(): return time.strptime(str(tags['Image DateTime']), '%Y:%m:%d %H:%M:%S') # very fuzzy time machting on filename # TODO: very fuzzy part, now it just matches the iphone namin...
Get most reliable timestamp from a picture, running down a couple of options. Filename, exif tags, modification time.
null
null
null
def convert_to_decimal(string): number_or_fraction = '(?:\d{1,2}) | (?:\d{1,10} \\ \d{1,10})' m = re.compile('''\[?\s? # opening bracket \d{{1,2}}\s?,\s? # first number {0} \s?,\s? # second number (can be a fraction) {0...
Decode the exif-gps format into a decimal point. '[51, 4, 1234/34]' -> 51.074948366
null
null
null
def build_dict(img_iterator): files_with_tags = dict() for f in img_iterator: with open(str(f.abspath()), 'rb') as jpg: tags = exifread.process_file(jpg) # Dont waste space on thumbnails try: del tags['JPEGThumbnail'] except K...
Build a dict from files from iterator. {'absolute_filename': {'EXIF field': 'exif tag value'}} Parse DateTime from filename in the same loop, added as 'TIME'.
null
null
null
def location_filter(files_with_tags, location, radius): ''' Get photos taken within the specified radius from a given point. ''' on_location = dict() for f, tags in files_with_tags.items(): if 'GPS GPSLatitude' in tags: try: lat = convert_to_decimal(str(ta...
Get photos taken within the specified radius from a given point.
null
null
null
def add_based_on_time(files_with_tags, on_location): ''' Sometimes the first photo in a series does not have gps coordinates because the phone doesnt have a gps-fix yet. To add these photos as well we take the list of photos wich where taken in the right location. Then add any photos taken whitin 10...
Sometimes the first photo in a series does not have gps coordinates because the phone doesnt have a gps-fix yet. To add these photos as well we take the list of photos wich where taken in the right location. Then add any photos taken whitin 10 minutes of these photos, because they are almost certainly ta...
null
null
null
# Do nothing if debugging is disabled if self._debug_stream is None or self._debug_stream is False: return # What are we passing to the format? if kwargs: fmtargs = kwargs else: fmtargs = args # Emit the message prin...
def _debug(self, msg, *args, **kwargs)
Emit debugging messages.
5.083418
4.666761
1.089282
if index is None: self._procstack.append(proc) else: self._procstack.insert(index, proc)
def _push_processor(self, proc, index=None)
Pushes a processor onto the processor stack. Processors are objects with proc_request(), proc_response(), and/or proc_exception() methods, which can intercept requests, responses, and exceptions. When a method invokes the send() method on a request, the proc_request() method on each ...
2.932732
2.649981
1.106699
# Build up headers hset = hdrs.HeaderDict() # Walk through our global headers for hdr, value in self._headers.items(): # If it's a callable, call it if callable(value): value = value(methname) else: # OK, just...
def _make_req(self, method, url, methname, headers=None)
Create a request object for the specified method and url.
4.586555
4.581012
1.00121
entries = {} for entry_point in pkg_resources.iter_entry_points(entry_point_name): entries[entry_point.name] = entry_point.load() return entries
def query_plugins(entry_point_name)
Find everything with a specific entry_point. Results will be returned as a dictionary, with the name as the key and the entry_point itself as the value. Arguments: entry_point_name - the name of the entry_point to populate
2.030711
2.507901
0.809725
"Warning: depends on python-yaml internals" node = copy.copy(node) # bypass YAML anti recursion best_tag = base_tag best_fit = 0 for key, val in loader.DEFAULT_TAGS.iteritems(): lenk = len(key) if lenk <= best_fit: continue if base_tag.startswith(key): ...
def _construct_node(loader, node, base_tag)
Warning: depends on python-yaml internals
5.025296
3.97671
1.263682
"Split comma-separated tag_suffix[:-1] and map with _maybe_int" if tag_suffix[-1:] != ')': raise ValueError, "unbalanced parenthesis in type %s%s" % (tag_prefix, tag_suffix) return map(_maybe_int, tag_suffix[:-1].split(','))
def _split_params(tag_prefix, tag_suffix)
Split comma-separated tag_suffix[:-1] and map with _maybe_int
6.810154
3.402308
2.001627
if not tag: tag = u'!~' + validator.__name__ for xid, opts in _VALIDATOR_MODES.iteritems(): mtag = "%s%s" % (tag, xid) yaml.add_constructor(mtag, ContructorValidatorNode(mtag, base_tag, ...
def add_validator(validator, base_tag, tag=None)
Add a validator for the given tag, which defines a subset of base_tag. If tag is None, it is automatically constructed as u'!~' + validator.__name__ Validator is a function that accepts a document node (in the form of a Python object), a schema node (also a Python object) and a tracing object, and r...
7.680392
6.240816
1.230671
# pylint: disable-msg=C0111,W0621 if not tag_prefix: tag_prefix = u'!~%s(' % param_validator.__name__ def multi_constructor(loader, tag_suffix, node): def temp_validator(node, schema): return param_validator(node, schema, *_split_params(tag_prefix, tag_suffix)) temp_...
def add_parameterized_validator(param_validator, base_tag, tag_prefix=None)
Add a parameterized validator for the given tag prefix. If tag_prefix is None, it is automatically constructed as u'!~%s(' % param_validator.__name__ A parametrized validator is a function that accepts a document node (in the form of a Python object), a schema node (also a Python object), and other ...
5.007556
3.923583
1.276271
"with builtin tag prefixing" add_validator(validator, base_tag, tag = u'!~~' + validator.__name__)
def _add_validator_internal(validator, base_tag)
with builtin tag prefixing
30.271965
16.453289
1.839873
"with builtin tag prefixing" add_parameterized_validator(param_validator, base_tag, tag_prefix=u'!~~%s(' % param_validator.__name__)
def _add_parameterized_validator_internal(param_validator, base_tag)
with builtin tag prefixing
14.095256
8.665631
1.62657
if not nstr.startswith(schema): return False postfix = nstr[len(schema):] try: int(postfix) except ValueError: return False return True
def prefixedDec(nstr, schema)
!~~prefixedDec corresponding strings in documents must begin with the associated string in the schema, and the right part of strings in documents must be decimal.
2.683559
2.818379
0.952164
if isinstance(nstr, (float, int, long)): return True elif not isinstance(nstr, basestring): return False try: float(nstr) except ValueError: return False return True
def isFloat(nstr, schema)
!~~isFloat
2.329042
2.475185
0.940957
if isinstance(nstr, int): nstr = str(nstr) elif not isinstance(nstr, basestring): return False return nstr.isdigit()
def digit(nstr, schema)
!~~digit '0123456789'.isdigit() or 123456789
2.928422
3.09852
0.945103
if isinstance(nstr, basestring): if not nstr.isdigit(): return False nstr = long(nstr) elif not isinstance(nstr, (int, long)): return False return nstr > 0
def uint(nstr, schema)
!~~uint
2.585546
2.745367
0.941785
name = schema if not _callbacks.has_key(name): return False return _callbacks[name](val)
def callback(val, schema, name = None): # pylint: disable-msg=W0613 if name is None
!~~callback(function)
7.606863
5.552088
1.37009
name = schema if not _lists.has_key(name): return False try: return val in _lists[name] except TypeError: return False
def isIn(val, schema, name = None): # pylint: disable-msg=W0613 if name is None
!~~isIn(data)
5.605888
4.330035
1.294652
name = schema if not _regexs.has_key(name): return False try: if _regexs[name](val): return True except TypeError: pass return False
def regex(val, schema, name = None): # pylint: disable-msg=W0613 if name is None
!~~regex(regex) or !~~regex regex
4.918221
4.268919
1.1521
if not isinstance(key, basestring): return key, content min_len = None max_len = None modifier = [] m = RE_MATCH_CSTR(key) if not m: raise KeyError("Unable to parse, invalid key: %r" % key) if m.group(3) is not None: min_len = max_len = int(m.group(3)...
def _qualify_map(key, content)
When a dictionary key is optional/optionalnull/mandatory, its corresponding _value_ is decorated in an Optional/OptionalNull/Mandatory tuple. This function undo the decoration when necessary.
2.091553
2.012506
1.039278
if isinstance(x, tuple): return x.__class__(_transschema(x[0]), *x[1:]) elif isinstance(x, dict): return dict((_qualify_map(key, _transschema(val)) for key, val in x.iteritems())) elif isinstance(x, list): return map(_transschema, x) else: return x
def _transschema(x)
Transform a schema, once loaded from its YAML representation, to its final internal representation
2.836388
3.16353
0.89659
''' For multi-page files, e.g. if pdf preview ''' def __init__(self, filename, page_id): self.id = page_id super(Page, self).__init__(filename) def export(self, export_format=ExportFormat.PNG): pass
def Page(QLExportable)
For multi-page files, e.g. if pdf preview
6.561999
4.192143
1.565309
for file in self.index.files: path = self.index.paths[file.pathIndex] data_offset = file.dataOffset data_size = file.dataSize obj = RAFEntry(self._data_handle, path, data_offset, data_size) # Add to full path dictionary assert path...
def _fill_entries(self)
Populate entries dictionaries from index.
3.486683
3.089236
1.128655
if path is None and name is None: # TODO: Correct error type raise ValueError("Path or name is required.") # Entries are sorted by version number, so the last will be the most recent # TODO: Reduce redundancy with RAFArchive if path: retur...
def find(self, path=None, name=None)
Returns most recent version of the matching file. If there are multiple files of the same name and version, a random one is used.
7.560604
6.916255
1.093164
# TODO: Reduce redundancy with RAFArchive pattern = re.compile(pattern, re.I) for k, v in six.iteritems(self.entries_full): if pattern.search(k): # Most recent version will be last yield v[-1]
def find_re(self, pattern)
Find the most recent versions of all entries whose path matches a given pattern.
9.034374
8.127587
1.111569
string = string.format(*args, **kwargs) return color + string + colorama.Fore.RESET
def colorize(string, color, *args, **kwargs)
Implements string formatting along with color specified in colorama.Fore
3.629537
2.830037
1.282505
import platform os_ = platform.system() # POSIX systems text = text.translate({ 0: None, ord('/'): '-', ord('|'): '-', }) if os_ == 'Windows': # Windows (non-POSIX namespace) text = text.translate({ # Reserved in Windows VFAT and NTFS ...
def legitimize(text)
Converts a string to a valid filename.
4.305837
3.991187
1.078836
try: lines = open(file, 'r').readlines() f_len = len(lines) - 1 for i in range(f_len): if old in lines[i]: lines[i] = lines[i].replace(old, new) open(file, 'w').writelines(lines) except Exception as e: print(e)
def modify_content(file, old, new)
替换文件中的指定内容,逐行进行
1.881064
1.869695
1.00608
if in_name is None: file_to_del = [os.path.join(path, i) for i in os.listdir(path)] else: file_to_del = [os.path.join(path, i) for i in os.listdir(path) if in_name in i] print('以下是要删除的文件列表:\n') print(file_to_del) if yn is None: yn = input('删除以上文件(输入:y/n), 保留部分文件(输入:k):'...
def batch_del_file(path, in_name=None, yn=None)
批量删除文件(给出一定的规则)
2.119104
2.070529
1.02346
assert os.path.exists(path), '%s 文件夹不存在' % path assert os.path.exists(dest), '%s 文件夹不存在' % dest if copy: mv = shutil.copy else: mv = shutil.move if in_name is None: file_list = os.listdir(path) else: file_list = [i for i in os.listdir(path) if in_name in i] ...
def batch_move_file(path, dest, in_name=None, copy=True)
将path目录下文件名中包含的in_name的文件移动到dest目录下 parameters ------------ path 需要转移文件的目录 dest 目标目录 in_name str, 默认是None。文件名过滤规则 example ------------ # 将path目录下的所有txt文件转移到dest目录 move_file(path, dest, in_name='.txt') 默认会覆盖目标目录下的同名文件
2.022559
2.018898
1.001814
files = os.listdir(path) for file in files: if f in file: new_fn = file.replace(f, t) old = os.path.join(path, file) new = os.path.join(path, new_fn) os.rename(old, new)
def batch_rename_file(path, f, t)
根据replaces中定义的规则,批量重命名
1.814003
1.822006
0.995608
cwd = os.getcwd() # 获取需要打包的文件列表 file_lists = [] for root, dirs, files in os.walk(folder_path): for file in files: file_1 = os.path.join(root, file).replace(folder_path + '/', '') if 'zip' not in file_1: file_lists.append(file_1) # 将文件列表打包成zip ...
def make_zip(folder_path, output_filename)
将目录中除zip之外的文件打包成zip文件(包括子文件夹) 空文件夹不会被打包 example ---------------- make_zip('results','zips//招标信息结果_2017-05-09.zip')
2.310068
2.443297
0.945471
with open(file, mode, encoding=encoding) as f: f.truncate()
def empty_file(file, mode="w", encoding='utf-8')
empty file
2.914022
2.849231
1.02274
# check input is numpy array im = np.asarray(im) # Compute the dft if it is not already done if not isccsedge: im = reg.dft_optsize(np.float32(edge(im))) # save the truesize for later use truesize = im.shape # get centered magnitude squared (This changes the size) im = re...
def channel_width(im, chanangle=None, *, chanapproxangle=None, isccsedge=False)
Get an estimation of the channel width. Parameters: ----------- im: 2d array The channel image chanangle: number, optional The angle of the channel (None if unknown) chanapproxangle: number, optional If chanangle is None, the approximate channel angle isccsedge: boolean,...
6.807895
6.55258
1.038964
im = np.asarray(im) # Compute edge if not isshiftdftedge: im = edge(im) return reg.orientation_angle(im, isshiftdft=isshiftdftedge, approxangle=chanapproxangle, truesize=truesize)
def channel_angle(im, chanapproxangle=None, *, isshiftdftedge=False, truesize=None)
Extract the channel angle from the rfft Parameters: ----------- im: 2d array The channel image chanapproxangle: number, optional If not None, an approximation of the result isshiftdftedge: boolean, default False If The image has already been treated: (edge, dft, ffts...
3.865688
5.209308
0.742073
im = np.asarray(im, dtype='float32') blurRadius = 2 * blurRadius + 1 im = cv2.GaussianBlur(im, (blurRadius, blurRadius), 0) Gx = cv2.Scharr(im, -1, 0, 1) Gy = cv2.Scharr(im, -1, 1, 0) ret = cv2.magnitude(Gx, Gy) if imblur is not None and imblur.shape == im.shape: imblur[:, :] = ...
def Scharr_edge(im, blurRadius=10, imblur=None)
Extract the edges using Scharr kernel (Sobel optimized for rotation invariance) Parameters: ----------- im: 2d array The image blurRadius: number, default 10 The gaussian blur raduis (The kernel has size 2*blurRadius+1) imblur: 2d array, OUT If not None, will be fille wi...
2.159836
2.365665
0.912993
im0 = np.asarray(im0) im1 = np.asarray(im1) # extract the channels edges e0 = edge(im0) e1 = edge(im1) fe0, fe1 = reg.dft_optsize_same(np.float32(e0), np.float32(e1)) # compute the angle and channel width of biggest angular feature w0, a0 = channel_width( fe0, isccsedge=Tru...
def register_channel(im0, im1, scale=None, ch0angle=None, chanapproxangle=None)
Register the images assuming they are channels Parameters: ----------- im0: 2d array The first image im1: 2d array The second image scale: number, optional The scale difference if known ch0angle: number, optional The angle of the channel in the first image if kno...
4.726406
4.453298
1.061327
im = np.asarray(im) immin = im.min() immax = im.max() imrange = immax - immin return cv2.convertScaleAbs(im - immin, alpha=255 / imrange)
def uint8sc(im)
Scale the image to uint8 Parameters: ----------- im: 2d array The image Returns: -------- im: 2d array (dtype uint8) The scaled image to uint8
2.680118
3.23398
0.828737
salutation = { 'french': 'Bonjour', 'spanish': 'Hola', 'english': 'Hello', }[args.lang.lower()] output = [] for name in args.name: output.append("{} {}!".format(salutation, name)) return "\n".join(output)
def handle(self, args)
Greet each person by name.
3.187841
2.695495
1.182655
game = Game() v = (0, 0) stub_actor = base.Actor('capture', v, v, v, v, v, v, v, v, v) root = base.State(board, stub_actor, stub_actor, turn=1, actions_remaining=1) solution_node = None for eot in game.all_ends_of_turn(root): # check for a solution if e...
def capture(board)
Try to solve the board described by board_string. Return sequence of summaries that describe how to get to the solution.
6.204138
5.911097
1.049575
disallow_methods = (self._is_duplicate_board, self._is_impossible_by_count) for disallow_method in disallow_methods: if disallow_method(state): return True return False
def _disallow_state(self, state)
Disallow states that are not useful to continue simulating.
5.553351
4.985158
1.113977