_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
87
6.4k
title
stringclasses
1 value
language
stringclasses
1 value
meta_information
dict
d301
train
def is_same_dict(d1, d2): """Test two dictionary is equal on values. (ignore order) """ for k, v in d1.items(): if isinstance(v, dict): is_same_dict(v, d2[k]) else: assert d1[k] == d2[k] for k, v in d2.items(): if isinstance(v, dict): is_same_dict(v, d1[k]) else: assert d1[k] == d2[k]
PYTHON
{ "dummy_field": "" }
d302
train
def file_writelines_flush_sync(path, lines): """ Fill file at @path with @lines then flush all buffers (Python and system buffers) """ fp = open(path, 'w') try: fp.writelines(lines) flush_sync_file_object(fp) finally: fp.close()
PYTHON
{ "dummy_field": "" }
d303
train
def make_kind_check(python_types, numpy_kind): """ Make a function that checks whether a scalar or array is of a given kind (e.g. float, int, datetime, timedelta). """ def check(value): if hasattr(value, 'dtype'): return value.dtype.kind == numpy_kind return isinstance(value, python_types) return check
PYTHON
{ "dummy_field": "" }
d304
train
def file_empty(fp): """Determine if a file is empty or not.""" # for python 2 we need to use a homemade peek() if six.PY2: contents = fp.read() fp.seek(0) return not bool(contents) else: return not fp.peek()
PYTHON
{ "dummy_field": "" }
d305
train
def all_equal(arg1,arg2): """ Return a single boolean for arg1==arg2, even for numpy arrays using element-wise comparison. Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise. If both objects have an '_infinitely_iterable' attribute, they are not be zipped together and are compared directly instead. """ if all(hasattr(el, '_infinitely_iterable') for el in [arg1,arg2]): return arg1==arg2 try: return all(a1 == a2 for a1, a2 in zip(arg1, arg2)) except TypeError: return arg1==arg2
PYTHON
{ "dummy_field": "" }
d306
train
def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
PYTHON
{ "dummy_field": "" }
d307
train
def _check_for_int(x): """ This is a compatibility function that takes a C{float} and converts it to an C{int} if the values are equal. """ try: y = int(x) except (OverflowError, ValueError): pass else: # There is no way in AMF0 to distinguish between integers and floats if x == x and y == x: return y return x
PYTHON
{ "dummy_field": "" }
d308
train
def fill_form(form, data): """Prefill form with data. :param form: The form to fill. :param data: The data to insert in the form. :returns: A pre-filled form. """ for (key, value) in data.items(): if hasattr(form, key): if isinstance(value, dict): fill_form(getattr(form, key), value) else: getattr(form, key).data = value return form
PYTHON
{ "dummy_field": "" }
d309
train
def check_clang_apply_replacements_binary(args): """Checks if invoking supplied clang-apply-replacements binary works.""" try: subprocess.check_call([args.clang_apply_replacements_binary, '--version']) except: print('Unable to run clang-apply-replacements. Is clang-apply-replacements ' 'binary correctly specified?', file=sys.stderr) traceback.print_exc() sys.exit(1)
PYTHON
{ "dummy_field": "" }
d310
train
def _maybe_fill(arr, fill_value=np.nan): """ if we have a compatible fill_value and arr dtype, then fill """ if _isna_compat(arr, fill_value): arr.fill(fill_value) return arr
PYTHON
{ "dummy_field": "" }
d311
train
def extract_alzip (archive, compression, cmd, verbosity, interactive, outdir): """Extract a ALZIP archive.""" return [cmd, '-d', outdir, archive]
PYTHON
{ "dummy_field": "" }
d312
train
def _maybe_fill(arr, fill_value=np.nan): """ if we have a compatible fill_value and arr dtype, then fill """ if _isna_compat(arr, fill_value): arr.fill(fill_value) return arr
PYTHON
{ "dummy_field": "" }
d313
train
def get_lons_from_cartesian(x__, y__): """Get longitudes from cartesian coordinates. """ return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__)
PYTHON
{ "dummy_field": "" }
d314
train
def filter_(stream_spec, filter_name, *args, **kwargs): """Alternate name for ``filter``, so as to not collide with the built-in python ``filter`` operator. """ return filter(stream_spec, filter_name, *args, **kwargs)
PYTHON
{ "dummy_field": "" }
d315
train
def _calculate_distance(latlon1, latlon2): """Calculates the distance between two points on earth. """ lat1, lon1 = latlon1 lat2, lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2 c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180 return c
PYTHON
{ "dummy_field": "" }
d316
train
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
PYTHON
{ "dummy_field": "" }
d317
train
def get_stationary_distribution(self): """Compute the stationary distribution of states. """ # The stationary distribution is proportional to the left-eigenvector # associated with the largest eigenvalue (i.e., 1) of the transition # matrix. check_is_fitted(self, "transmat_") eigvals, eigvecs = np.linalg.eig(self.transmat_.T) eigvec = np.real_if_close(eigvecs[:, np.argmax(eigvals)]) return eigvec / eigvec.sum()
PYTHON
{ "dummy_field": "" }
d318
train
def apply_fit(xy,coeffs): """ Apply the coefficients from a linear fit to an array of x,y positions. The coeffs come from the 'coeffs' member of the 'fit_arrays()' output. """ x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1] y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1] return x_new,y_new
PYTHON
{ "dummy_field": "" }
d319
train
def _tf_squared_euclidean(X, Y): """Squared Euclidean distance between the rows of `X` and `Y`. """ return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1)
PYTHON
{ "dummy_field": "" }
d320
train
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
PYTHON
{ "dummy_field": "" }
d321
train
def euclidean(x, y): """Standard euclidean distance. ..math:: D(x, y) = \sqrt{\sum_i (x_i - y_i)^2} """ result = 0.0 for i in range(x.shape[0]): result += (x[i] - y[i]) ** 2 return np.sqrt(result)
PYTHON
{ "dummy_field": "" }
d322
train
def create_table_from_fits(fitsfile, hduname, colnames=None): """Memory efficient function for loading a table from a FITS file.""" if colnames is None: return Table.read(fitsfile, hduname) cols = [] with fits.open(fitsfile, memmap=True) as h: for k in colnames: data = h[hduname].data.field(k) cols += [Column(name=k, data=data)] return Table(cols)
PYTHON
{ "dummy_field": "" }
d323
train
def _gcd_array(X): """ Return the largest real value h such that all elements in x are integer multiples of h. """ greatest_common_divisor = 0.0 for x in X: greatest_common_divisor = _gcd(greatest_common_divisor, x) return greatest_common_divisor
PYTHON
{ "dummy_field": "" }
d324
train
def lint(args): """Run lint checks using flake8.""" application = get_current_application() if not args: args = [application.name, 'tests'] args = ['flake8'] + list(args) run.main(args, standalone_mode=False)
PYTHON
{ "dummy_field": "" }
d325
train
def torecarray(*args, **kwargs): """ Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``. """ import numpy as np return toarray(*args, **kwargs).view(np.recarray)
PYTHON
{ "dummy_field": "" }
d326
train
def _type_bool(label,default=False): """Shortcut fot boolean like fields""" return label, abstractSearch.nothing, abstractRender.boolen, default
PYTHON
{ "dummy_field": "" }
d327
train
def join_cols(cols): """Join list of columns into a string for a SQL query""" return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols
PYTHON
{ "dummy_field": "" }
d328
train
def parse_form(self, req, name, field): """Pull a form value from the request.""" return core.get_value(req.POST, name, field)
PYTHON
{ "dummy_field": "" }
d329
train
def type_converter(text): """ I convert strings into integers, floats, and strings! """ if text.isdigit(): return int(text), int try: return float(text), float except ValueError: return text, STRING_TYPE
PYTHON
{ "dummy_field": "" }
d330
train
def cors_header(func): """ @cors_header decorator adds CORS headers """ @wraps(func) def wrapper(self, request, *args, **kwargs): res = func(self, request, *args, **kwargs) request.setHeader('Access-Control-Allow-Origin', '*') request.setHeader('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With') return res return wrapper
PYTHON
{ "dummy_field": "" }
d331
train
def pdf(x, mu, std): """Probability density function (normal distribution)""" return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))
PYTHON
{ "dummy_field": "" }
d332
train
def handleFlaskPostRequest(flaskRequest, endpoint): """ Handles the specified flask request for one of the POST URLS Invokes the specified endpoint to generate a response. """ if flaskRequest.method == "POST": return handleHttpPost(flaskRequest, endpoint) elif flaskRequest.method == "OPTIONS": return handleHttpOptions() else: raise exceptions.MethodNotAllowedException()
PYTHON
{ "dummy_field": "" }
d333
train
def pdf(x, mu, std): """Probability density function (normal distribution)""" return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))
PYTHON
{ "dummy_field": "" }
d334
train
def python_mime(fn): """ Decorator, which adds correct MIME type for python source to the decorated bottle API function. """ @wraps(fn) def python_mime_decorator(*args, **kwargs): response.content_type = "text/x-python" return fn(*args, **kwargs) return python_mime_decorator
PYTHON
{ "dummy_field": "" }
d335
train
def _spawn_kafka_consumer_thread(self): """Spawns a kafka continuous consumer thread""" self.logger.debug("Spawn kafka consumer thread""") self._consumer_thread = Thread(target=self._consumer_loop) self._consumer_thread.setDaemon(True) self._consumer_thread.start()
PYTHON
{ "dummy_field": "" }
d336
train
def flatpages_link_list(request): """ Returns a HttpResponse whose content is a Javascript file representing a list of links to flatpages. """ from django.contrib.flatpages.models import FlatPage link_list = [(page.title, page.url) for page in FlatPage.objects.all()] return render_to_link_list(link_list)
PYTHON
{ "dummy_field": "" }
d337
train
def values(self): """Gets the user enter max and min values of where the raster points should appear on the y-axis :returns: (float, float) -- (min, max) y-values to bound the raster plot by """ lower = float(self.lowerSpnbx.value()) upper = float(self.upperSpnbx.value()) return (lower, upper)
PYTHON
{ "dummy_field": "" }
d338
train
def sqlmany(self, stringname, *args): """Wrapper for executing many SQL calls on my connection. First arg is the name of a query, either a key in the precompiled JSON or a method name in ``allegedb.alchemy.Alchemist``. Remaining arguments should be tuples of argument sequences to be passed to the query. """ if hasattr(self, 'alchemist'): return getattr(self.alchemist.many, stringname)(*args) s = self.strings[stringname] return self.connection.cursor().executemany(s, args)
PYTHON
{ "dummy_field": "" }
d339
train
def convolve_gaussian_2d(image, gaussian_kernel_1d): """Convolve 2d gaussian.""" result = scipy.ndimage.filters.correlate1d( image, gaussian_kernel_1d, axis=0) result = scipy.ndimage.filters.correlate1d( result, gaussian_kernel_1d, axis=1) return result
PYTHON
{ "dummy_field": "" }
d340
train
def render_template_string(source, **context): """Renders a template from the given template source string with the given context. :param source: the sourcecode of the template to be rendered :param context: the variables that should be available in the context of the template. """ ctx = _app_ctx_stack.top ctx.app.update_template_context(context) return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)
PYTHON
{ "dummy_field": "" }
d341
train
def asynchronous(function, event): """ Runs the function asynchronously taking care of exceptions. """ thread = Thread(target=synchronous, args=(function, event)) thread.daemon = True thread.start()
PYTHON
{ "dummy_field": "" }
d342
train
def HttpResponse403(request, template=KEY_AUTH_403_TEMPLATE, content=KEY_AUTH_403_CONTENT, content_type=KEY_AUTH_403_CONTENT_TYPE): """ HTTP response for forbidden access (status code 403) """ return AccessFailedResponse(request, template, content, content_type, status=403)
PYTHON
{ "dummy_field": "" }
d343
train
def similarity(self, other): """Calculates the cosine similarity between this vector and another vector.""" if self.magnitude == 0 or other.magnitude == 0: return 0 return self.dot(other) / self.magnitude
PYTHON
{ "dummy_field": "" }
d344
train
def default_static_path(): """ Return the path to the javascript bundle """ fdir = os.path.dirname(__file__) return os.path.abspath(os.path.join(fdir, '../assets/'))
PYTHON
{ "dummy_field": "" }
d345
train
def count_list(the_list): """ Generates a count of the number of times each unique item appears in a list """ count = the_list.count result = [(item, count(item)) for item in set(the_list)] result.sort() return result
PYTHON
{ "dummy_field": "" }
d346
train
def round_to_float(number, precision): """Round a float to a precision""" rounded = Decimal(str(floor((number + precision / 2) // precision)) ) * Decimal(str(precision)) return float(rounded)
PYTHON
{ "dummy_field": "" }
d347
train
def _calc_overlap_count( markers1: dict, markers2: dict, ): """Calculate overlap count between the values of two dictionaries Note: dict values must be sets """ overlaps=np.zeros((len(markers1), len(markers2))) j=0 for marker_group in markers1: tmp = [len(markers2[i].intersection(markers1[marker_group])) for i in markers2.keys()] overlaps[j,:] = tmp j += 1 return overlaps
PYTHON
{ "dummy_field": "" }
d348
train
def intround(value): """Given a float returns a rounded int. Should give the same result on both Py2/3 """ return int(decimal.Decimal.from_float( value).to_integral_value(decimal.ROUND_HALF_EVEN))
PYTHON
{ "dummy_field": "" }
d349
train
def _datetime_to_date(arg): """ convert datetime/str to date :param arg: :return: """ _arg = parse(arg) if isinstance(_arg, datetime.datetime): _arg = _arg.date() return _arg
PYTHON
{ "dummy_field": "" }
d350
train
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(PageControlWidget, self).focusInEvent(event)
PYTHON
{ "dummy_field": "" }
d351
train
def mkdir(dir, enter): """Create directory with template for topic of the current environment """ if not os.path.exists(dir): os.makedirs(dir)
PYTHON
{ "dummy_field": "" }
d352
train
def one_hot(x, size, dtype=np.float32): """Make a n+1 dim one-hot array from n dim int-categorical array.""" return np.array(x[..., np.newaxis] == np.arange(size), dtype)
PYTHON
{ "dummy_field": "" }
d353
train
def iter_finds(regex_obj, s): """Generate all matches found within a string for a regex and yield each match as a string""" if isinstance(regex_obj, str): for m in re.finditer(regex_obj, s): yield m.group() else: for m in regex_obj.finditer(s): yield m.group()
PYTHON
{ "dummy_field": "" }
d354
train
def a2s(a): """ convert 3,3 a matrix to 6 element "s" list (see Tauxe 1998) """ s = np.zeros((6,), 'f') # make the a matrix for i in range(3): s[i] = a[i][i] s[3] = a[0][1] s[4] = a[1][2] s[5] = a[0][2] return s
PYTHON
{ "dummy_field": "" }
d355
train
def concat(cls, iterables): """ Similar to #itertools.chain.from_iterable(). """ def generator(): for it in iterables: for element in it: yield element return cls(generator())
PYTHON
{ "dummy_field": "" }
d356
train
def format_result(input): """From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python """ items = list(iteritems(input)) return OrderedDict(sorted(items, key=lambda x: x[0]))
PYTHON
{ "dummy_field": "" }
d357
train
def bulk_query(self, query, *multiparams): """Bulk insert or update.""" with self.get_connection() as conn: conn.bulk_query(query, *multiparams)
PYTHON
{ "dummy_field": "" }
d358
train
def Trie(S): """ :param S: set of words :returns: trie containing all words from S :complexity: linear in total word sizes from S """ T = None for w in S: T = add(T, w) return T
PYTHON
{ "dummy_field": "" }
d359
train
def __set__(self, instance, value): """ Set a related object for an instance. """ self.map[id(instance)] = (weakref.ref(instance), value)
PYTHON
{ "dummy_field": "" }
d360
train
def recarray(self): """Returns data as :class:`numpy.recarray`.""" return numpy.rec.fromrecords(self.records, names=self.names)
PYTHON
{ "dummy_field": "" }
d361
train
def go_to_background(): """ Daemonize the running process. """ try: if os.fork(): sys.exit() except OSError as errmsg: LOGGER.error('Fork failed: {0}'.format(errmsg)) sys.exit('Fork failed')
PYTHON
{ "dummy_field": "" }
d362
train
def generate_unique_host_id(): """Generate a unique ID, that is somewhat guaranteed to be unique among all instances running at the same time.""" host = ".".join(reversed(socket.gethostname().split("."))) pid = os.getpid() return "%s.%d" % (host, pid)
PYTHON
{ "dummy_field": "" }
d363
train
def compress(self, data_list): """ Return the cleaned_data of the form, everything should already be valid """ data = {} if data_list: return dict( (f.name, data_list[i]) for i, f in enumerate(self.form)) return data
PYTHON
{ "dummy_field": "" }
d364
train
def init_db(): """ Drops and re-creates the SQL schema """ db.drop_all() db.configure_mappers() db.create_all() db.session.commit()
PYTHON
{ "dummy_field": "" }
d365
train
def safe_format(s, **kwargs): """ :type s str """ return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))
PYTHON
{ "dummy_field": "" }
d366
train
def _init_unique_sets(self): """Initialise sets used for uniqueness checking.""" ks = dict() for t in self._unique_checks: key = t[0] ks[key] = set() # empty set return ks
PYTHON
{ "dummy_field": "" }
d367
train
def straight_line_show(title, length=100, linestyle="=", pad=0): """Print a formatted straight line. """ print(StrTemplate.straight_line( title=title, length=length, linestyle=linestyle, pad=pad))
PYTHON
{ "dummy_field": "" }
d368
train
def make_executable(script_path): """Make `script_path` executable. :param script_path: The file to change """ status = os.stat(script_path) os.chmod(script_path, status.st_mode | stat.S_IEXEC)
PYTHON
{ "dummy_field": "" }
d369
train
def make_html_code( self, lines ): """ convert a code sequence to HTML """ line = code_header + '\n' for l in lines: line = line + html_quote( l ) + '\n' return line + code_footer
PYTHON
{ "dummy_field": "" }
d370
train
def cross_product_matrix(vec): """Returns a 3x3 cross-product matrix from a 3-element vector.""" return np.array([[0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]])
PYTHON
{ "dummy_field": "" }
d371
train
def index_nearest(value, array): """ expects a _n.array returns the global minimum of (value-array)^2 """ a = (array-value)**2 return index(a.min(), a)
PYTHON
{ "dummy_field": "" }
d372
train
def main(args=sys.argv): """ main entry point for the jardiff CLI """ parser = create_optparser(args[0]) return cli(parser.parse_args(args[1:]))
PYTHON
{ "dummy_field": "" }
d373
train
def free(self): """Free the underlying C array""" if self._ptr is None: return Gauged.array_free(self.ptr) FloatArray.ALLOCATIONS -= 1 self._ptr = None
PYTHON
{ "dummy_field": "" }
d374
train
def from_points(cls, list_of_lists): """ Creates a *Polygon* instance out of a list of lists, each sublist being populated with `pyowm.utils.geo.Point` instances :param list_of_lists: list :type: list_of_lists: iterable_of_polygons :returns: a *Polygon* instance """ result = [] for l in list_of_lists: curve = [] for point in l: curve.append((point.lon, point.lat)) result.append(curve) return Polygon(result)
PYTHON
{ "dummy_field": "" }
d375
train
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
PYTHON
{ "dummy_field": "" }
d376
train
def tmpfile(prefix, direc): """Returns the path to a newly created temporary file.""" return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
PYTHON
{ "dummy_field": "" }
d377
train
def connect(host, port, username, password): """Connect and login to an FTP server and return ftplib.FTP object.""" # Instantiate ftplib client session = ftplib.FTP() # Connect to host without auth session.connect(host, port) # Authenticate connection session.login(username, password) return session
PYTHON
{ "dummy_field": "" }
d378
train
def unique_list(lst): """Make a list unique, retaining order of initial appearance.""" uniq = [] for item in lst: if item not in uniq: uniq.append(item) return uniq
PYTHON
{ "dummy_field": "" }
d379
train
def connect(): """Connect to FTP server, login and return an ftplib.FTP instance.""" ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS ftp = ftp_class(timeout=TIMEOUT) ftp.connect(HOST, PORT) ftp.login(USER, PASSWORD) if SSL: ftp.prot_p() # secure data connection return ftp
PYTHON
{ "dummy_field": "" }
d380
train
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
PYTHON
{ "dummy_field": "" }
d381
train
def All(sequence): """ :param sequence: Any sequence whose elements can be evaluated as booleans. :returns: true if all elements of the sequence satisfy True and x. """ return bool(reduce(lambda x, y: x and y, sequence, True))
PYTHON
{ "dummy_field": "" }
d382
train
def zero_state(self, batch_size): """ Initial state of the network """ return torch.zeros(batch_size, self.state_dim, dtype=torch.float32)
PYTHON
{ "dummy_field": "" }
d383
train
def _fullname(o): """Return the fully-qualified name of a function.""" return o.__module__ + "." + o.__name__ if o.__module__ else o.__name__
PYTHON
{ "dummy_field": "" }
d384
train
def create_index(config): """Create the root index.""" filename = pathlib.Path(config.cache_path) / "index.json" index = {"version": __version__} with open(filename, "w") as out: out.write(json.dumps(index, indent=2))
PYTHON
{ "dummy_field": "" }
d385
train
def issorted(list_, op=operator.le): """ Determines if a list is sorted Args: list_ (list): op (func): sorted operation (default=operator.le) Returns: bool : True if the list is sorted """ return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))
PYTHON
{ "dummy_field": "" }
d386
train
def is_valid(number): """determines whether the card number is valid.""" n = str(number) if not n.isdigit(): return False return int(n[-1]) == get_check_digit(n[:-1])
PYTHON
{ "dummy_field": "" }
d387
train
def us2mc(string): """Transform an underscore_case string to a mixedCase string""" return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)
PYTHON
{ "dummy_field": "" }
d388
train
def csv2yaml(in_file, out_file=None): """Convert a CSV SampleSheet to YAML run_info format. """ if out_file is None: out_file = "%s.yaml" % os.path.splitext(in_file)[0] barcode_ids = _generate_barcode_ids(_read_input_csv(in_file)) lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids) with open(out_file, "w") as out_handle: out_handle.write(yaml.safe_dump(lanes, default_flow_style=False)) return out_file
PYTHON
{ "dummy_field": "" }
d389
train
def get_average_length_of_string(strings): """Computes average length of words :param strings: list of words :return: Average length of word on list """ if not strings: return 0 return sum(len(word) for word in strings) / len(strings)
PYTHON
{ "dummy_field": "" }
d390
train
def cumsum(inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1, len(newlist)): newlist[i] = newlist[i] + newlist[i - 1] return newlist
PYTHON
{ "dummy_field": "" }
d391
train
def good(txt): """Print, emphasized 'good', the given 'txt' message""" print("%s# %s%s%s" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC)) sys.stdout.flush()
PYTHON
{ "dummy_field": "" }
d392
train
def move_to(self, ypos, xpos): """ move the cursor to the given co-ordinates. Co-ordinates are 1 based, as listed in the status area of the terminal. """ # the screen's co-ordinates are 1 based, but the command is 0 based xpos -= 1 ypos -= 1 self.exec_command("MoveCursor({0}, {1})".format(ypos, xpos).encode("ascii"))
PYTHON
{ "dummy_field": "" }
d393
train
def dict_from_object(obj: object): """Convert a object into dictionary with all of its readable attributes.""" # If object is a dict instance, no need to convert. return (obj if isinstance(obj, dict) else {attr: getattr(obj, attr) for attr in dir(obj) if not attr.startswith('_')})
PYTHON
{ "dummy_field": "" }
d394
train
def ensure_hbounds(self): """Ensure the cursor is within horizontal screen bounds.""" self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)
PYTHON
{ "dummy_field": "" }
d395
train
def strip_spaces(s): """ Strip excess spaces from a string """ return u" ".join([c for c in s.split(u' ') if c])
PYTHON
{ "dummy_field": "" }
d396
train
def scatter(self, *args, **kwargs): """Add a scatter plot.""" cls = _make_class(ScatterVisual, _default_marker=kwargs.pop('marker', None), ) return self._add_item(cls, *args, **kwargs)
PYTHON
{ "dummy_field": "" }
d397
train
def download_file_from_bucket(self, bucket, file_path, key): """ Download file from S3 Bucket """ with open(file_path, 'wb') as data: self.__s3.download_fileobj(bucket, key, data) return file_path
PYTHON
{ "dummy_field": "" }
d398
train
def imdecode(image_path): """Return BGR image read by opencv""" import os assert os.path.exists(image_path), image_path + ' not found' im = cv2.imread(image_path) return im
PYTHON
{ "dummy_field": "" }
d399
train
def ex(self, cmd): """Execute a normal python statement in user namespace.""" with self.builtin_trap: exec cmd in self.user_global_ns, self.user_ns
PYTHON
{ "dummy_field": "" }
d400
train
def split(s): """Uses dynamic programming to infer the location of spaces in a string without spaces.""" l = [_split(x) for x in _SPLIT_RE.split(s)] return [item for sublist in l for item in sublist]
PYTHON
{ "dummy_field": "" }