_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
87
6.4k
title
stringclasses
1 value
language
stringclasses
1 value
meta_information
dict
d1
train
def writeBoolean(self, n): """ Writes a Boolean to the stream. """ t = TYPE_BOOL_TRUE if n is False: t = TYPE_BOOL_FALSE self.stream.write(t)
PYTHON
{ "dummy_field": "" }
d2
train
def paste(xsel=False): """Returns system clipboard contents.""" selection = "primary" if xsel else "clipboard" try: return subprocess.Popen(["xclip", "-selection", selection, "-o"], stdout=subprocess.PIPE).communicate()[0].decode("utf-8") except OSError as why: raise XclipNotFound
PYTHON
{ "dummy_field": "" }
d3
train
def _format_json(data, theme): """Pretty print a dict as a JSON, with colors if pygments is present.""" output = json.dumps(data, indent=2, sort_keys=True) if pygments and sys.stdout.isatty(): style = get_style_by_name(theme) formatter = Terminal256Formatter(style=style) return pygments.highlight(output, JsonLexer(), formatter) return output
PYTHON
{ "dummy_field": "" }
d4
train
def create_path(path): """Creates a absolute path in the file system. :param path: The path to be created """ import os if not os.path.exists(path): os.makedirs(path)
PYTHON
{ "dummy_field": "" }
d5
train
def _vector_or_scalar(x, type='row'): """Convert an object to either a scalar or a row or column vector.""" if isinstance(x, (list, tuple)): x = np.array(x) if isinstance(x, np.ndarray): assert x.ndim == 1 if type == 'column': x = x[:, None] return x
PYTHON
{ "dummy_field": "" }
d6
train
def experiment_property(prop): """Get a property of the experiment by name.""" exp = experiment(session) p = getattr(exp, prop) return success_response(field=prop, data=p, request_type=prop)
PYTHON
{ "dummy_field": "" }
d7
train
def data_from_file(file): """Return (first channel data, sample frequency, sample width) from a .wav file.""" fp = wave.open(file, 'r') data = fp.readframes(fp.getnframes()) channels = fp.getnchannels() freq = fp.getframerate() bits = fp.getsampwidth() # Unpack bytes -- warning currently only tested with 16 bit wavefiles. 32 # bit not supported. data = struct.unpack(('%sh' % fp.getnframes()) * channels, data) # Only use first channel channel1 = [] n = 0 for d in data: if n % channels == 0: channel1.append(d) n += 1 fp.close() return (channel1, freq, bits)
PYTHON
{ "dummy_field": "" }
d8
train
def source_range(start, end, nr_var_dict): """ Given a range of source numbers, as well as a dictionary containing the numbers of each source, returns a dictionary containing tuples of the start and end index for each source variable type. """ return OrderedDict((k, e-s) for k, (s, e) in source_range_tuple(start, end, nr_var_dict).iteritems())
PYTHON
{ "dummy_field": "" }
d9
train
def timespan(start_time): """Return time in milliseconds from start_time""" timespan = datetime.datetime.now() - start_time timespan_ms = timespan.total_seconds() * 1000 return timespan_ms
PYTHON
{ "dummy_field": "" }
d10
train
def _convert_to_array(array_like, dtype): """ Convert Matrix attributes which are array-like or buffer to array. """ if isinstance(array_like, bytes): return np.frombuffer(array_like, dtype=dtype) return np.asarray(array_like, dtype=dtype)
PYTHON
{ "dummy_field": "" }
d11
train
def get_uniques(l): """ Returns a list with no repeated elements. """ result = [] for i in l: if i not in result: result.append(i) return result
PYTHON
{ "dummy_field": "" }
d12
train
def interp(x, xp, *args, **kwargs): """Wrap interpolate_1d for deprecated interp.""" return interpolate_1d(x, xp, *args, **kwargs)
PYTHON
{ "dummy_field": "" }
d13
train
def _array2cstr(arr): """ Serializes a numpy array to a compressed base64 string """ out = StringIO() np.save(out, arr) return b64encode(out.getvalue())
PYTHON
{ "dummy_field": "" }
d14
train
def percentile(values, k): """Find the percentile of a list of values. :param list values: The list of values to find the percentile of :param int k: The percentile to find :rtype: float or int """ if not values: return None values.sort() index = (len(values) * (float(k) / 100)) - 1 return values[int(math.ceil(index))]
PYTHON
{ "dummy_field": "" }
d15
train
def _string_hash(s): """String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).""" h = 5381 for c in s: h = h * 33 + ord(c) return h
PYTHON
{ "dummy_field": "" }
d16
train
def transform_from_rot_trans(R, t): """Transforation matrix from rotation matrix and translation vector.""" R = R.reshape(3, 3) t = t.reshape(3, 1) return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))
PYTHON
{ "dummy_field": "" }
d17
train
def _encode_bool(name, value, dummy0, dummy1): """Encode a python boolean (True/False).""" return b"\x08" + name + (value and b"\x01" or b"\x00")
PYTHON
{ "dummy_field": "" }
d18
train
def transform_to_3d(points,normal,z=0): """Project points into 3d from 2d points.""" d = np.cross(normal, (0, 0, 1)) M = rotation_matrix(d) transformed_points = M.dot(points.T).T + z return transformed_points
PYTHON
{ "dummy_field": "" }
d19
train
def _not(condition=None, **kwargs): """ Return the opposite of input condition. :param condition: condition to process. :result: not condition. :rtype: bool """ result = True if condition is not None: result = not run(condition, **kwargs) return result
PYTHON
{ "dummy_field": "" }
d20
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": "" }
d21
train
def items(self, section_name): """:return: list((option, value), ...) pairs of all items in the given section""" return [(k, v) for k, v in super(GitConfigParser, self).items(section_name) if k != '__name__']
PYTHON
{ "dummy_field": "" }
d22
train
def mag(z): """Get the magnitude of a vector.""" if isinstance(z[0], np.ndarray): return np.array(list(map(np.linalg.norm, z))) else: return np.linalg.norm(z)
PYTHON
{ "dummy_field": "" }
d23
train
def config_parser_to_dict(config_parser): """ Convert a ConfigParser to a dictionary. """ response = {} for section in config_parser.sections(): for option in config_parser.options(section): response.setdefault(section, {})[option] = config_parser.get(section, option) return response
PYTHON
{ "dummy_field": "" }
d24
train
def __add__(self, other): """Handle the `+` operator.""" return self._handle_type(other)(self.value + other.value)
PYTHON
{ "dummy_field": "" }
d25
train
def connect_mysql(host, port, user, password, database): """Connect to MySQL with retries.""" return pymysql.connect( host=host, port=port, user=user, passwd=password, db=database )
PYTHON
{ "dummy_field": "" }
d26
train
def get_column(self, X, column): """Return a column of the given matrix. Args: X: `numpy.ndarray` or `pandas.DataFrame`. column: `int` or `str`. Returns: np.ndarray: Selected column. """ if isinstance(X, pd.DataFrame): return X[column].values return X[:, column]
PYTHON
{ "dummy_field": "" }
d27
train
def connect(url, username, password): """ Return a connected Bitbucket session """ bb_session = stashy.connect(url, username, password) logger.info('Connected to: %s as %s', url, username) return bb_session
PYTHON
{ "dummy_field": "" }
d28
train
def add_blank_row(self, label): """ Add a blank row with only an index value to self.df. This is done inplace. """ col_labels = self.df.columns blank_item = pd.Series({}, index=col_labels, name=label) # use .loc to add in place (append won't do that) self.df.loc[blank_item.name] = blank_item return self.df
PYTHON
{ "dummy_field": "" }
d29
train
def teardown(self): """ Stop and remove the container if it exists. """ while self._http_clients: self._http_clients.pop().close() if self.created: self.halt()
PYTHON
{ "dummy_field": "" }
d30
train
def dumped(text, level, indent=2): """Put curly brackets round an indented text""" return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n"
PYTHON
{ "dummy_field": "" }
d31
train
def context(self): """ Create a context manager that ensures code runs within action's context. The action does NOT finish when the context is exited. """ parent = _ACTION_CONTEXT.set(self) try: yield self finally: _ACTION_CONTEXT.reset(parent)
PYTHON
{ "dummy_field": "" }
d32
train
def pformat(object, indent=1, width=80, depth=None): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
PYTHON
{ "dummy_field": "" }
d33
train
def replace_sys_args(new_args): """Temporarily replace sys.argv with current arguments Restores sys.argv upon exit of the context manager. """ # Replace sys.argv arguments # for module import old_args = sys.argv sys.argv = new_args try: yield finally: sys.argv = old_args
PYTHON
{ "dummy_field": "" }
d34
train
def serialize(obj): """Takes a object and produces a dict-like representation :param obj: the object to serialize """ if isinstance(obj, list): return [serialize(o) for o in obj] return GenericSerializer(ModelProviderImpl()).serialize(obj)
PYTHON
{ "dummy_field": "" }
d35
train
def advance_one_line(self): """Advances to next line.""" current_line = self._current_token.line_number while current_line == self._current_token.line_number: self._current_token = ConfigParser.Token(*next(self._token_generator))
PYTHON
{ "dummy_field": "" }
d36
train
def generate_swagger_html(swagger_static_root, swagger_json_url): """ given a root directory for the swagger statics, and a swagger json path, return back a swagger html designed to use those values. """ tmpl = _get_template("swagger.html") return tmpl.render( swagger_root=swagger_static_root, swagger_json_url=swagger_json_url )
PYTHON
{ "dummy_field": "" }
d37
train
def do_next(self, args): """Step over the next statement """ self._do_print_from_last_cmd = True self._interp.step_over() return True
PYTHON
{ "dummy_field": "" }
d38
train
def __add__(self,other): """ If the number of columns matches, we can concatenate two LabeldMatrices with the + operator. """ assert self.matrix.shape[1] == other.matrix.shape[1] return LabeledMatrix(np.concatenate([self.matrix,other.matrix],axis=0),self.labels)
PYTHON
{ "dummy_field": "" }
d39
train
def get_line_flux(line_wave, wave, flux, **kwargs): """Interpolated flux at a given wavelength (calls np.interp).""" return np.interp(line_wave, wave, flux, **kwargs)
PYTHON
{ "dummy_field": "" }
d40
train
def send(message, request_context=None, binary=False): """Sends a message to websocket. :param str message: data to send :param request_context: :raises IOError: If unable to send a message. """ if binary: return uwsgi.websocket_send_binary(message, request_context) return uwsgi.websocket_send(message, request_context)
PYTHON
{ "dummy_field": "" }
d41
train
def get_number(s, cast=int): """ Try to get a number out of a string, and cast it. """ import string d = "".join(x for x in str(s) if x in string.digits) return cast(d)
PYTHON
{ "dummy_field": "" }
d42
train
def get_hline(): """ gets a horiztonal line """ return Window( width=LayoutDimension.exact(1), height=LayoutDimension.exact(1), content=FillControl('-', token=Token.Line))
PYTHON
{ "dummy_field": "" }
d43
train
def parse_cookies_str(cookies): """ parse cookies str to dict :param cookies: cookies str :type cookies: str :return: cookie dict :rtype: dict """ cookie_dict = {} for record in cookies.split(";"): key, value = record.strip().split("=", 1) cookie_dict[key] = value return cookie_dict
PYTHON
{ "dummy_field": "" }
d44
train
def to_snake_case(name): """ Given a name in camelCase return in snake_case """ s1 = FIRST_CAP_REGEX.sub(r'\1_\2', name) return ALL_CAP_REGEX.sub(r'\1_\2', s1).lower()
PYTHON
{ "dummy_field": "" }
d45
train
def populate_obj(obj, attrs): """Populates an object's attributes using the provided dict """ for k, v in attrs.iteritems(): setattr(obj, k, v)
PYTHON
{ "dummy_field": "" }
d46
train
def wordfreq(text, is_filename=False): """Return a dictionary of words and word counts in a string.""" if is_filename: with open(text) as f: text = f.read() freqs = {} for word in text.split(): lword = word.lower() freqs[lword] = freqs.get(lword, 0) + 1 return freqs
PYTHON
{ "dummy_field": "" }
d47
train
def copyFile(input, output, replace=None): """Copy a file whole from input to output.""" _found = findFile(output) if not _found or (_found and replace): shutil.copy2(input, output)
PYTHON
{ "dummy_field": "" }
d48
train
def push(h, x): """Push a new value into heap.""" h.push(x) up(h, h.size()-1)
PYTHON
{ "dummy_field": "" }
d49
train
def yank(event): """ Paste before cursor. """ event.current_buffer.paste_clipboard_data( event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)
PYTHON
{ "dummy_field": "" }
d50
train
def filter_contour(imageFile, opFile): """ convert an image by applying a contour """ im = Image.open(imageFile) im1 = im.filter(ImageFilter.CONTOUR) im1.save(opFile)
PYTHON
{ "dummy_field": "" }
d51
train
def count(lines): """ Counts the word frequences in a list of sentences. Note: This is a helper function for parallel execution of `Vocabulary.from_text` method. """ words = [w for l in lines for w in l.strip().split()] return Counter(words)
PYTHON
{ "dummy_field": "" }
d52
train
def dictapply(d, fn): """ apply a function to all non-dict values in a dictionary """ for k, v in d.items(): if isinstance(v, dict): v = dictapply(v, fn) else: d[k] = fn(v) return d
PYTHON
{ "dummy_field": "" }
d53
train
def count_replica(self, partition): """Return count of replicas of given partition.""" return sum(1 for b in partition.replicas if b in self.brokers)
PYTHON
{ "dummy_field": "" }
d54
train
def visit_Name(self, node): """ Get range for parameters for examples or false branching. """ return self.add(node, self.result[node.id])
PYTHON
{ "dummy_field": "" }
d55
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": "" }
d56
train
def qrot(vector, quaternion): """Rotate a 3D vector using quaternion algebra. Implemented by Vladimir Kulikovskiy. Parameters ---------- vector: np.array quaternion: np.array Returns ------- np.array """ t = 2 * np.cross(quaternion[1:], vector) v_rot = vector + quaternion[0] * t + np.cross(quaternion[1:], t) return v_rot
PYTHON
{ "dummy_field": "" }
d57
train
def _numpy_char_to_bytes(arr): """Like netCDF4.chartostring, but faster and more flexible. """ # based on: http://stackoverflow.com/a/10984878/809705 arr = np.array(arr, copy=False, order='C') dtype = 'S' + str(arr.shape[-1]) return arr.view(dtype).reshape(arr.shape[:-1])
PYTHON
{ "dummy_field": "" }
d58
train
def _string_hash(s): """String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).""" h = 5381 for c in s: h = h * 33 + ord(c) return h
PYTHON
{ "dummy_field": "" }
d59
train
def csv_to_dicts(file, header=None): """Reads a csv and returns a List of Dicts with keys given by header row.""" with open(file) as csvfile: return [row for row in csv.DictReader(csvfile, fieldnames=header)]
PYTHON
{ "dummy_field": "" }
d60
train
def get_tri_area(pts): """ Given a list of coords for 3 points, Compute the area of this triangle. Args: pts: [a, b, c] three points """ a, b, c = pts[0], pts[1], pts[2] v1 = np.array(b) - np.array(a) v2 = np.array(c) - np.array(a) area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2) return area_tri
PYTHON
{ "dummy_field": "" }
d61
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": "" }
d62
train
def round_to_int(number, precision): """Round a number to a precision""" precision = int(precision) rounded = (int(number) + precision / 2) // precision * precision return rounded
PYTHON
{ "dummy_field": "" }
d63
train
def create_object(cls, members): """Promise an object of class `cls` with content `members`.""" obj = cls.__new__(cls) obj.__dict__ = members return obj
PYTHON
{ "dummy_field": "" }
d64
train
def to_unicode_repr( _letter ): """ helpful in situations where browser/app may recognize Unicode encoding in the \u0b8e type syntax but not actual unicode glyph/code-point""" # Python 2-3 compatible return u"u'"+ u"".join( [ u"\\u%04x"%ord(l) for l in _letter ] ) + u"'"
PYTHON
{ "dummy_field": "" }
d65
train
def create_path(path): """Creates a absolute path in the file system. :param path: The path to be created """ import os if not os.path.exists(path): os.makedirs(path)
PYTHON
{ "dummy_field": "" }
d66
train
def string_input(prompt=''): """Python 3 input()/Python 2 raw_input()""" v = sys.version[0] if v == '3': return input(prompt) else: return raw_input(prompt)
PYTHON
{ "dummy_field": "" }
d67
train
def cfloat64_array_to_numpy(cptr, length): """Convert a ctypes double pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_double)): return np.fromiter(cptr, dtype=np.float64, count=length) else: raise RuntimeError('Expected double pointer')
PYTHON
{ "dummy_field": "" }
d68
train
def yn_prompt(msg, default=True): """ Prompts the user for yes or no. """ ret = custom_prompt(msg, ["y", "n"], "y" if default else "n") if ret == "y": return True return False
PYTHON
{ "dummy_field": "" }
d69
train
def _display(self, layout): """launch layouts display""" print(file=self.out) TextWriter().format(layout, self.out)
PYTHON
{ "dummy_field": "" }
d70
train
def assert_list(self, putative_list, expected_type=string_types, key_arg=None): """ :API: public """ return assert_list(putative_list, expected_type, key_arg=key_arg, raise_type=lambda msg: TargetDefinitionException(self, msg))
PYTHON
{ "dummy_field": "" }
d71
train
def _xxrange(self, start, end, step_count): """Generate n values between start and end.""" _step = (end - start) / float(step_count) return (start + (i * _step) for i in xrange(int(step_count)))
PYTHON
{ "dummy_field": "" }
d72
train
def assert_exactly_one_true(bool_list): """This method asserts that only one value of the provided list is True. :param bool_list: List of booleans to check :return: True if only one value is True, False otherwise """ assert isinstance(bool_list, list) counter = 0 for item in bool_list: if item: counter += 1 return counter == 1
PYTHON
{ "dummy_field": "" }
d73
train
def _get_random_id(): """ Get a random (i.e., unique) string identifier""" symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(symbols) for _ in range(15))
PYTHON
{ "dummy_field": "" }
d74
train
async def list(source): """Generate a single list from an asynchronous sequence.""" result = [] async with streamcontext(source) as streamer: async for item in streamer: result.append(item) yield result
PYTHON
{ "dummy_field": "" }
d75
train
def csv_to_dicts(file, header=None): """Reads a csv and returns a List of Dicts with keys given by header row.""" with open(file) as csvfile: return [row for row in csv.DictReader(csvfile, fieldnames=header)]
PYTHON
{ "dummy_field": "" }
d76
train
def _attrprint(d, delimiter=', '): """Print a dictionary of attributes in the DOT format""" return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.items()))
PYTHON
{ "dummy_field": "" }
d77
train
def get_next_scheduled_time(cron_string): """Calculate the next scheduled time by creating a crontab object with a cron string""" itr = croniter.croniter(cron_string, datetime.utcnow()) return itr.get_next(datetime)
PYTHON
{ "dummy_field": "" }
d78
train
def exit(exit_code=0): r"""A function to support exiting from exit hooks. Could also be used to exit from the calling scripts in a thread safe manner. """ core.processExitHooks() if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook sys.stderr.flush() sys.stdout.flush() os._exit(exit_code) #pylint: disable=W0212 sys.exit(exit_code)
PYTHON
{ "dummy_field": "" }
d79
train
def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y
PYTHON
{ "dummy_field": "" }
d80
train
def reloader_thread(softexit=False): """If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit`` will be used to end the process. """ while RUN_RELOADER: if code_changed(): # force reload if softexit: sys.exit(3) else: os._exit(3) time.sleep(1)
PYTHON
{ "dummy_field": "" }
d81
train
def list_to_csv(value): """ Converts list to string with comma separated values. For string is no-op. """ if isinstance(value, (list, tuple, set)): value = ",".join(value) return value
PYTHON
{ "dummy_field": "" }
d82
train
def average(iterator): """Iterative mean.""" count = 0 total = 0 for num in iterator: count += 1 total += num return float(total)/count
PYTHON
{ "dummy_field": "" }
d83
train
def cint32_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)): return np.fromiter(cptr, dtype=np.int32, count=length) else: raise RuntimeError('Expected int pointer')
PYTHON
{ "dummy_field": "" }
d84
train
def _aws_get_instance_by_tag(region, name, tag, raw): """Get all instances matching a tag.""" client = boto3.session.Session().client('ec2', region) matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', []) instances = [] [[instances.append(_aws_instance_from_dict(region, instance, raw)) # pylint: disable=expression-not-assigned for instance in reservation.get('Instances')] for reservation in matching_reservations if reservation] return instances
PYTHON
{ "dummy_field": "" }
d85
train
def cfloat64_array_to_numpy(cptr, length): """Convert a ctypes double pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_double)): return np.fromiter(cptr, dtype=np.float64, count=length) else: raise RuntimeError('Expected double pointer')
PYTHON
{ "dummy_field": "" }
d86
train
def loganalytics_data_plane_client(cli_ctx, _): """Initialize Log Analytics data client for use with CLI.""" from .vendored_sdks.loganalytics import LogAnalyticsDataClient from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) cred, _, _ = profile.get_login_credentials( resource="https://api.loganalytics.io") return LogAnalyticsDataClient(cred)
PYTHON
{ "dummy_field": "" }
d87
train
def cfloat32_array_to_numpy(cptr, length): """Convert a ctypes float pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_float)): return np.fromiter(cptr, dtype=np.float32, count=length) else: raise RuntimeError('Expected float pointer')
PYTHON
{ "dummy_field": "" }
d88
train
def underscore(text): """Converts text that may be camelcased into an underscored format""" return UNDERSCORE[1].sub(r'\1_\2', UNDERSCORE[0].sub(r'\1_\2', text)).lower()
PYTHON
{ "dummy_field": "" }
d89
train
def cint8_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)): return np.fromiter(cptr, dtype=np.int8, count=length) else: raise RuntimeError('Expected int pointer')
PYTHON
{ "dummy_field": "" }
d90
train
def get_stoplist(language): """Returns an built-in stop-list for the language as a set of words.""" file_path = os.path.join("stoplists", "%s.txt" % language) try: stopwords = pkgutil.get_data("justext", file_path) except IOError: raise ValueError( "Stoplist for language '%s' is missing. " "Please use function 'get_stoplists' for complete list of stoplists " "and feel free to contribute by your own stoplist." % language ) return frozenset(w.decode("utf8").lower() for w in stopwords.splitlines())
PYTHON
{ "dummy_field": "" }
d91
train
def add_str(window, line_num, str): """ attempt to draw str on screen and ignore errors if they occur """ try: window.addstr(line_num, 0, str) except curses.error: pass
PYTHON
{ "dummy_field": "" }
d92
train
def relative_path(path): """ Return the given path relative to this file. """ return os.path.join(os.path.dirname(__file__), path)
PYTHON
{ "dummy_field": "" }
d93
train
def dictfetchall(cursor): """Returns all rows from a cursor as a dict (rather than a headerless table) From Django Documentation: https://docs.djangoproject.com/en/dev/topics/db/sql/ """ desc = cursor.description return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]
PYTHON
{ "dummy_field": "" }
d94
train
def xmltreefromfile(filename): """Internal function to read an XML file""" try: return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False)) except TypeError: return ElementTree.parse(filename, ElementTree.XMLParser())
PYTHON
{ "dummy_field": "" }
d95
train
def _dictfetchall(self, cursor): """ Return all rows from a cursor as a dict. """ columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ]
PYTHON
{ "dummy_field": "" }
d96
train
def beta_pdf(x, a, b): """Beta distirbution probability density function.""" bc = 1 / beta(a, b) fc = x ** (a - 1) sc = (1 - x) ** (b - 1) return bc * fc * sc
PYTHON
{ "dummy_field": "" }
d97
train
def filter_out(queryset, setting_name): """ Remove unwanted results from queryset """ kwargs = helpers.get_settings().get(setting_name, {}).get('FILTER_OUT', {}) queryset = queryset.exclude(**kwargs) return queryset
PYTHON
{ "dummy_field": "" }
d98
train
def intToBin(i): """ Integer to two bytes """ # divide in two parts (bytes) i1 = i % 256 i2 = int(i / 256) # make string (little endian) return i.to_bytes(2, byteorder='little')
PYTHON
{ "dummy_field": "" }
d99
train
def listlike(obj): """Is an object iterable like a list (and not a string)?""" return hasattr(obj, "__iter__") \ and not issubclass(type(obj), str)\ and not issubclass(type(obj), unicode)
PYTHON
{ "dummy_field": "" }
d100
train
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
PYTHON
{ "dummy_field": "" }