repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
gophish/api-client-python
gophish/api/campaigns.py
API.summary
def summary(self, campaign_id=None): """ Returns the campaign summary """ resource_cls = CampaignSummary single_resource = False if not campaign_id: resource_cls = CampaignSummaries single_resource = True return super(API, self).get( resource...
python
def summary(self, campaign_id=None): """ Returns the campaign summary """ resource_cls = CampaignSummary single_resource = False if not campaign_id: resource_cls = CampaignSummaries single_resource = True return super(API, self).get( resource...
[ "def", "summary", "(", "self", ",", "campaign_id", "=", "None", ")", ":", "resource_cls", "=", "CampaignSummary", "single_resource", "=", "False", "if", "not", "campaign_id", ":", "resource_cls", "=", "CampaignSummaries", "single_resource", "=", "True", "return", ...
Returns the campaign summary
[ "Returns", "the", "campaign", "summary" ]
train
https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/campaigns.py#L38-L51
gophish/api-client-python
gophish/api/campaigns.py
API.results
def results(self, campaign_id): """ Returns just the results for a given campaign """ return super(API, self).get( resource_id=campaign_id, resource_action='results', resource_cls=CampaignResults)
python
def results(self, campaign_id): """ Returns just the results for a given campaign """ return super(API, self).get( resource_id=campaign_id, resource_action='results', resource_cls=CampaignResults)
[ "def", "results", "(", "self", ",", "campaign_id", ")", ":", "return", "super", "(", "API", ",", "self", ")", ".", "get", "(", "resource_id", "=", "campaign_id", ",", "resource_action", "=", "'results'", ",", "resource_cls", "=", "CampaignResults", ")" ]
Returns just the results for a given campaign
[ "Returns", "just", "the", "results", "for", "a", "given", "campaign" ]
train
https://github.com/gophish/api-client-python/blob/28a7790f19e13c92ef0fb7bde8cd89389df5c155/gophish/api/campaigns.py#L53-L58
gunthercox/jsondb
jsondb/db.py
Database.set_path
def set_path(self, file_path): """ Set the path of the database. Create the file if it does not exist. """ if not file_path: self.read_data = self.memory_read self.write_data = self.memory_write elif not is_valid(file_path): self.write_...
python
def set_path(self, file_path): """ Set the path of the database. Create the file if it does not exist. """ if not file_path: self.read_data = self.memory_read self.write_data = self.memory_write elif not is_valid(file_path): self.write_...
[ "def", "set_path", "(", "self", ",", "file_path", ")", ":", "if", "not", "file_path", ":", "self", ".", "read_data", "=", "self", ".", "memory_read", "self", ".", "write_data", "=", "self", ".", "memory_write", "elif", "not", "is_valid", "(", "file_path", ...
Set the path of the database. Create the file if it does not exist.
[ "Set", "the", "path", "of", "the", "database", ".", "Create", "the", "file", "if", "it", "does", "not", "exist", "." ]
train
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L38-L49
gunthercox/jsondb
jsondb/db.py
Database.delete
def delete(self, key): """ Removes the specified key from the database. """ obj = self._get_content() obj.pop(key, None) self.write_data(self.path, obj)
python
def delete(self, key): """ Removes the specified key from the database. """ obj = self._get_content() obj.pop(key, None) self.write_data(self.path, obj)
[ "def", "delete", "(", "self", ",", "key", ")", ":", "obj", "=", "self", ".", "_get_content", "(", ")", "obj", ".", "pop", "(", "key", ",", "None", ")", "self", ".", "write_data", "(", "self", ".", "path", ",", "obj", ")" ]
Removes the specified key from the database.
[ "Removes", "the", "specified", "key", "from", "the", "database", "." ]
train
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L68-L75
gunthercox/jsondb
jsondb/db.py
Database.data
def data(self, **kwargs): """ If a key is passed in, a corresponding value will be returned. If a key-value pair is passed in then the corresponding key in the database will be set to the specified value. A dictionary can be passed in as well. If a key does not exist and ...
python
def data(self, **kwargs): """ If a key is passed in, a corresponding value will be returned. If a key-value pair is passed in then the corresponding key in the database will be set to the specified value. A dictionary can be passed in as well. If a key does not exist and ...
[ "def", "data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "key", "=", "kwargs", ".", "pop", "(", "'key'", ",", "None", ")", "value", "=", "kwargs", ".", "pop", "(", "'value'", ",", "None", ")", "dictionary", "=", "kwargs", ".", "pop", "(", ...
If a key is passed in, a corresponding value will be returned. If a key-value pair is passed in then the corresponding key in the database will be set to the specified value. A dictionary can be passed in as well. If a key does not exist and a value is provided then an entry will...
[ "If", "a", "key", "is", "passed", "in", "a", "corresponding", "value", "will", "be", "returned", ".", "If", "a", "key", "-", "value", "pair", "is", "passed", "in", "then", "the", "corresponding", "key", "in", "the", "database", "will", "be", "set", "to...
train
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L77-L109
gunthercox/jsondb
jsondb/db.py
Database.filter
def filter(self, filter_arguments): """ Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters. """ results = self._get_content() # Filter based on a dictionary of search parameters if isinstance(filter_arguments, dict): ...
python
def filter(self, filter_arguments): """ Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters. """ results = self._get_content() # Filter based on a dictionary of search parameters if isinstance(filter_arguments, dict): ...
[ "def", "filter", "(", "self", ",", "filter_arguments", ")", ":", "results", "=", "self", ".", "_get_content", "(", ")", "# Filter based on a dictionary of search parameters", "if", "isinstance", "(", "filter_arguments", ",", "dict", ")", ":", "for", "item", ",", ...
Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters.
[ "Takes", "a", "dictionary", "of", "filter", "parameters", ".", "Return", "a", "list", "of", "objects", "based", "on", "a", "list", "of", "parameters", "." ]
train
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L125-L149
gunthercox/jsondb
jsondb/db.py
Database.drop
def drop(self): """ Remove the database by deleting the JSON file. """ import os if self.path: if os.path.exists(self.path): os.remove(self.path) else: # Clear the in-memory data if there is no file path self._data = {}
python
def drop(self): """ Remove the database by deleting the JSON file. """ import os if self.path: if os.path.exists(self.path): os.remove(self.path) else: # Clear the in-memory data if there is no file path self._data = {}
[ "def", "drop", "(", "self", ")", ":", "import", "os", "if", "self", ".", "path", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", ":", "os", ".", "remove", "(", "self", ".", "path", ")", "else", ":", "# Clear the in-mem...
Remove the database by deleting the JSON file.
[ "Remove", "the", "database", "by", "deleting", "the", "JSON", "file", "." ]
train
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L151-L162
gunthercox/jsondb
jsondb/file_writer.py
read_data
def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """ if not is_valid(file_path): write_data(file_path, {}) db = open_file_for_reading(file_path) content = db.read() obj = decode(content) db.close() return obj
python
def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """ if not is_valid(file_path): write_data(file_path, {}) db = open_file_for_reading(file_path) content = db.read() obj = decode(content) db.close() return obj
[ "def", "read_data", "(", "file_path", ")", ":", "if", "not", "is_valid", "(", "file_path", ")", ":", "write_data", "(", "file_path", ",", "{", "}", ")", "db", "=", "open_file_for_reading", "(", "file_path", ")", "content", "=", "db", ".", "read", "(", ...
Reads a file and returns a json encoded representation of the file.
[ "Reads", "a", "file", "and", "returns", "a", "json", "encoded", "representation", "of", "the", "file", "." ]
train
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/file_writer.py#L4-L19
gunthercox/jsondb
jsondb/file_writer.py
write_data
def write_data(path, obj): """ Writes to a file and returns the updated file content. """ with open_file_for_writing(path) as db: db.write(encode(obj)) return obj
python
def write_data(path, obj): """ Writes to a file and returns the updated file content. """ with open_file_for_writing(path) as db: db.write(encode(obj)) return obj
[ "def", "write_data", "(", "path", ",", "obj", ")", ":", "with", "open_file_for_writing", "(", "path", ")", "as", "db", ":", "db", ".", "write", "(", "encode", "(", "obj", ")", ")", "return", "obj" ]
Writes to a file and returns the updated file content.
[ "Writes", "to", "a", "file", "and", "returns", "the", "updated", "file", "content", "." ]
train
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/file_writer.py#L21-L28
gunthercox/jsondb
jsondb/file_writer.py
is_valid
def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(fil...
python
def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(fil...
[ "def", "is_valid", "(", "file_path", ")", ":", "from", "os", "import", "path", ",", "stat", "can_open", "=", "False", "try", ":", "with", "open", "(", "file_path", ")", "as", "fp", ":", "can_open", "=", "True", "except", "IOError", ":", "return", "Fals...
Check to see if a file exists or is empty.
[ "Check", "to", "see", "if", "a", "file", "exists", "or", "is", "empty", "." ]
train
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/file_writer.py#L30-L46
nschloe/meshzoo
meshzoo/helpers.py
_refine
def _refine(node_coords, cells_nodes, edge_nodes, cells_edges): """Canonically refine a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one. This is a very crude refinement; don't use for actual applications. """ num_nodes = len(node_coords) num_ne...
python
def _refine(node_coords, cells_nodes, edge_nodes, cells_edges): """Canonically refine a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one. This is a very crude refinement; don't use for actual applications. """ num_nodes = len(node_coords) num_ne...
[ "def", "_refine", "(", "node_coords", ",", "cells_nodes", ",", "edge_nodes", ",", "cells_edges", ")", ":", "num_nodes", "=", "len", "(", "node_coords", ")", "num_new_nodes", "=", "len", "(", "edge_nodes", ")", "# new_nodes = numpy.empty(num_new_nodes, dtype=numpy.dtyp...
Canonically refine a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one. This is a very crude refinement; don't use for actual applications.
[ "Canonically", "refine", "a", "mesh", "by", "inserting", "nodes", "at", "all", "edge", "midpoints", "and", "make", "four", "triangular", "elements", "where", "there", "was", "one", ".", "This", "is", "a", "very", "crude", "refinement", ";", "don", "t", "us...
train
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/helpers.py#L7-L124
nschloe/meshzoo
meshzoo/helpers.py
create_edges
def create_edges(cells_nodes): """Setup edge-node and edge-cell relations. Adapted from voropy. """ # Create the idx_hierarchy (nodes->edges->cells), i.e., the value of # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3...
python
def create_edges(cells_nodes): """Setup edge-node and edge-cell relations. Adapted from voropy. """ # Create the idx_hierarchy (nodes->edges->cells), i.e., the value of # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3...
[ "def", "create_edges", "(", "cells_nodes", ")", ":", "# Create the idx_hierarchy (nodes->edges->cells), i.e., the value of", "# `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge", "# 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3, n)`, where `n` is", "# the number of...
Setup edge-node and edge-cell relations. Adapted from voropy.
[ "Setup", "edge", "-", "node", "and", "edge", "-", "cell", "relations", ".", "Adapted", "from", "voropy", "." ]
train
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/helpers.py#L127-L158
nschloe/meshzoo
meshzoo/helpers.py
plot2d
def plot2d(points, cells, mesh_color="k", show_axes=False): """Plot a 2D mesh using matplotlib. """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection fig = plt.figure() ax = fig.gca() plt.axis("equal") if not show_axes: ax.set_axis_off() xmin...
python
def plot2d(points, cells, mesh_color="k", show_axes=False): """Plot a 2D mesh using matplotlib. """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection fig = plt.figure() ax = fig.gca() plt.axis("equal") if not show_axes: ax.set_axis_off() xmin...
[ "def", "plot2d", "(", "points", ",", "cells", ",", "mesh_color", "=", "\"k\"", ",", "show_axes", "=", "False", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "matplotlib", ".", "collections", "import", "LineCollection", "fig", "=", "...
Plot a 2D mesh using matplotlib.
[ "Plot", "a", "2D", "mesh", "using", "matplotlib", "." ]
train
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/helpers.py#L169-L203
shazow/workerpool
samples/blockingworker.py
BlockingWorkerPool.put
def put(self, job, result): "Perform a job by a member in the pool and return the result." self.job.put(job) r = result.get() return r
python
def put(self, job, result): "Perform a job by a member in the pool and return the result." self.job.put(job) r = result.get() return r
[ "def", "put", "(", "self", ",", "job", ",", "result", ")", ":", "self", ".", "job", ".", "put", "(", "job", ")", "r", "=", "result", ".", "get", "(", ")", "return", "r" ]
Perform a job by a member in the pool and return the result.
[ "Perform", "a", "job", "by", "a", "member", "in", "the", "pool", "and", "return", "the", "result", "." ]
train
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/samples/blockingworker.py#L16-L20
shazow/workerpool
samples/blockingworker.py
BlockingWorkerPool.contract
def contract(self, jobs, result): """ Perform a contract on a number of jobs and block until a result is retrieved for each job. """ for j in jobs: WorkerPool.put(self, j) r = [] for i in xrange(len(jobs)): r.append(result.get()) ...
python
def contract(self, jobs, result): """ Perform a contract on a number of jobs and block until a result is retrieved for each job. """ for j in jobs: WorkerPool.put(self, j) r = [] for i in xrange(len(jobs)): r.append(result.get()) ...
[ "def", "contract", "(", "self", ",", "jobs", ",", "result", ")", ":", "for", "j", "in", "jobs", ":", "WorkerPool", ".", "put", "(", "self", ",", "j", ")", "r", "=", "[", "]", "for", "i", "in", "xrange", "(", "len", "(", "jobs", ")", ")", ":",...
Perform a contract on a number of jobs and block until a result is retrieved for each job.
[ "Perform", "a", "contract", "on", "a", "number", "of", "jobs", "and", "block", "until", "a", "result", "is", "retrieved", "for", "each", "job", "." ]
train
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/samples/blockingworker.py#L22-L34
nschloe/meshzoo
meshzoo/cube.py
cube
def cube( xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, zmin=0.0, zmax=1.0, nx=11, ny=11, nz=11 ): """Canonical tetrahedrization of the cube. Input: Edge lenghts of the cube Number of nodes along the edges. """ # Generate suitable ranges for parametrization x_range = numpy.linspace(xmin, xmax,...
python
def cube( xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, zmin=0.0, zmax=1.0, nx=11, ny=11, nz=11 ): """Canonical tetrahedrization of the cube. Input: Edge lenghts of the cube Number of nodes along the edges. """ # Generate suitable ranges for parametrization x_range = numpy.linspace(xmin, xmax,...
[ "def", "cube", "(", "xmin", "=", "0.0", ",", "xmax", "=", "1.0", ",", "ymin", "=", "0.0", ",", "ymax", "=", "1.0", ",", "zmin", "=", "0.0", ",", "zmax", "=", "1.0", ",", "nx", "=", "11", ",", "ny", "=", "11", ",", "nz", "=", "11", ")", ":...
Canonical tetrahedrization of the cube. Input: Edge lenghts of the cube Number of nodes along the edges.
[ "Canonical", "tetrahedrization", "of", "the", "cube", ".", "Input", ":", "Edge", "lenghts", "of", "the", "cube", "Number", "of", "nodes", "along", "the", "edges", "." ]
train
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/cube.py#L6-L294
shazow/workerpool
workerpool/pools.py
WorkerPool.grow
def grow(self): "Add another worker to the pool." t = self.worker_factory(self) t.start() self._size += 1
python
def grow(self): "Add another worker to the pool." t = self.worker_factory(self) t.start() self._size += 1
[ "def", "grow", "(", "self", ")", ":", "t", "=", "self", ".", "worker_factory", "(", "self", ")", "t", ".", "start", "(", ")", "self", ".", "_size", "+=", "1" ]
Add another worker to the pool.
[ "Add", "another", "worker", "to", "the", "pool", "." ]
train
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L66-L70
shazow/workerpool
workerpool/pools.py
WorkerPool.shrink
def shrink(self): "Get rid of one worker from the pool. Raises IndexError if empty." if self._size <= 0: raise IndexError("pool is already empty") self._size -= 1 self.put(SuicideJob())
python
def shrink(self): "Get rid of one worker from the pool. Raises IndexError if empty." if self._size <= 0: raise IndexError("pool is already empty") self._size -= 1 self.put(SuicideJob())
[ "def", "shrink", "(", "self", ")", ":", "if", "self", ".", "_size", "<=", "0", ":", "raise", "IndexError", "(", "\"pool is already empty\"", ")", "self", ".", "_size", "-=", "1", "self", ".", "put", "(", "SuicideJob", "(", ")", ")" ]
Get rid of one worker from the pool. Raises IndexError if empty.
[ "Get", "rid", "of", "one", "worker", "from", "the", "pool", ".", "Raises", "IndexError", "if", "empty", "." ]
train
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L72-L77
shazow/workerpool
workerpool/pools.py
WorkerPool.map
def map(self, fn, *seq): "Perform a map operation distributed among the workers. Will " "block until done." results = Queue() args = zip(*seq) for seq in args: j = SimpleJob(results, fn, seq) self.put(j) # Aggregate results r = [] ...
python
def map(self, fn, *seq): "Perform a map operation distributed among the workers. Will " "block until done." results = Queue() args = zip(*seq) for seq in args: j = SimpleJob(results, fn, seq) self.put(j) # Aggregate results r = [] ...
[ "def", "map", "(", "self", ",", "fn", ",", "*", "seq", ")", ":", "\"block until done.\"", "results", "=", "Queue", "(", ")", "args", "=", "zip", "(", "*", "seq", ")", "for", "seq", "in", "args", ":", "j", "=", "SimpleJob", "(", "results", ",", "f...
Perform a map operation distributed among the workers. Will
[ "Perform", "a", "map", "operation", "distributed", "among", "the", "workers", ".", "Will" ]
train
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L89-L103
nschloe/meshzoo
meshzoo/moebius.py
moebius
def moebius( num_twists=1, # How many twists are there in the 'paper'? nl=60, # Number of nodes along the length of the strip nw=11, # Number of nodes along the width of the strip (>= 2) mode="classical", ): """Creates a simplistic triangular mesh on a slightly Möbius strip. The Möbius strip ...
python
def moebius( num_twists=1, # How many twists are there in the 'paper'? nl=60, # Number of nodes along the length of the strip nw=11, # Number of nodes along the width of the strip (>= 2) mode="classical", ): """Creates a simplistic triangular mesh on a slightly Möbius strip. The Möbius strip ...
[ "def", "moebius", "(", "num_twists", "=", "1", ",", "# How many twists are there in the 'paper'?", "nl", "=", "60", ",", "# Number of nodes along the length of the strip", "nw", "=", "11", ",", "# Number of nodes along the width of the strip (>= 2)", "mode", "=", "\"classical...
Creates a simplistic triangular mesh on a slightly Möbius strip. The Möbius strip here deviates slightly from the ordinary geometry in that it is constructed in such a way that the two halves can be exchanged as to allow better comparison with the pseudo-Möbius geometry. The mode is either `'classical'...
[ "Creates", "a", "simplistic", "triangular", "mesh", "on", "a", "slightly", "Möbius", "strip", ".", "The", "Möbius", "strip", "here", "deviates", "slightly", "from", "the", "ordinary", "geometry", "in", "that", "it", "is", "constructed", "in", "such", "a", "w...
train
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/moebius.py#L7-L83
shazow/workerpool
workerpool/workers.py
Worker.run
def run(self): "Get jobs from the queue and perform them as they arrive." while 1: # Sleep until there is a job to perform. job = self.jobs.get() # Yawn. Time to get some work done. try: job.run() self.jobs.task_done() ...
python
def run(self): "Get jobs from the queue and perform them as they arrive." while 1: # Sleep until there is a job to perform. job = self.jobs.get() # Yawn. Time to get some work done. try: job.run() self.jobs.task_done() ...
[ "def", "run", "(", "self", ")", ":", "while", "1", ":", "# Sleep until there is a job to perform.", "job", "=", "self", ".", "jobs", ".", "get", "(", ")", "# Yawn. Time to get some work done.", "try", ":", "job", ".", "run", "(", ")", "self", ".", "jobs", ...
Get jobs from the queue and perform them as they arrive.
[ "Get", "jobs", "from", "the", "queue", "and", "perform", "them", "as", "they", "arrive", "." ]
train
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/workers.py#L28-L40
jwass/geojsonio.py
geojsonio/geojsonio.py
display
def display(contents, domain=DEFAULT_DOMAIN, force_gist=False): """ Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the cont...
python
def display(contents, domain=DEFAULT_DOMAIN, force_gist=False): """ Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the cont...
[ "def", "display", "(", "contents", ",", "domain", "=", "DEFAULT_DOMAIN", ",", "force_gist", "=", "False", ")", ":", "url", "=", "make_url", "(", "contents", ",", "domain", ",", "force_gist", ")", "webbrowser", ".", "open", "(", "url", ")", "return", "url...
Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the content is small, this step is not needed as the data can be included in the...
[ "Open", "a", "web", "browser", "pointing", "to", "geojson", ".", "io", "with", "the", "specified", "content", "." ]
train
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L18-L38
jwass/geojsonio.py
geojsonio/geojsonio.py
embed
def embed(contents='', width='100%', height=512, *args, **kwargs): """ Embed geojson.io in an iframe in Jupyter/IPython notebook. Parameters ---------- contents - see make_url() width - string, default '100%' - width of the iframe height - string / int, default 512 - height of the iframe ...
python
def embed(contents='', width='100%', height=512, *args, **kwargs): """ Embed geojson.io in an iframe in Jupyter/IPython notebook. Parameters ---------- contents - see make_url() width - string, default '100%' - width of the iframe height - string / int, default 512 - height of the iframe ...
[ "def", "embed", "(", "contents", "=", "''", ",", "width", "=", "'100%'", ",", "height", "=", "512", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "IPython", ".", "display", "import", "HTML", "url", "=", "make_url", "(", "contents", "...
Embed geojson.io in an iframe in Jupyter/IPython notebook. Parameters ---------- contents - see make_url() width - string, default '100%' - width of the iframe height - string / int, default 512 - height of the iframe kwargs - additional arguments are passed to `make_url()`
[ "Embed", "geojson", ".", "io", "in", "an", "iframe", "in", "Jupyter", "/", "IPython", "notebook", "." ]
train
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L43-L60
jwass/geojsonio.py
geojsonio/geojsonio.py
make_url
def make_url(contents, domain=DEFAULT_DOMAIN, force_gist=False, size_for_gist=MAX_URL_LEN): """ Returns the URL to open given the domain and contents. If the file contents are large, an anonymous gist will be created. Parameters ---------- contents * string - assumed to be...
python
def make_url(contents, domain=DEFAULT_DOMAIN, force_gist=False, size_for_gist=MAX_URL_LEN): """ Returns the URL to open given the domain and contents. If the file contents are large, an anonymous gist will be created. Parameters ---------- contents * string - assumed to be...
[ "def", "make_url", "(", "contents", ",", "domain", "=", "DEFAULT_DOMAIN", ",", "force_gist", "=", "False", ",", "size_for_gist", "=", "MAX_URL_LEN", ")", ":", "contents", "=", "make_geojson", "(", "contents", ")", "if", "len", "(", "contents", ")", "<=", "...
Returns the URL to open given the domain and contents. If the file contents are large, an anonymous gist will be created. Parameters ---------- contents * string - assumed to be GeoJSON * an object that implements __geo_interface__ A FeatureCollection will be constructed wi...
[ "Returns", "the", "URL", "to", "open", "given", "the", "domain", "and", "contents", "." ]
train
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L63-L96
jwass/geojsonio.py
geojsonio/geojsonio.py
make_geojson
def make_geojson(contents): """ Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string """ if isinstance(contents, six.string_types): return contents if hasattr(contents, '__g...
python
def make_geojson(contents): """ Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string """ if isinstance(contents, six.string_types): return contents if hasattr(contents, '__g...
[ "def", "make_geojson", "(", "contents", ")", ":", "if", "isinstance", "(", "contents", ",", "six", ".", "string_types", ")", ":", "return", "contents", "if", "hasattr", "(", "contents", ",", "'__geo_interface__'", ")", ":", "features", "=", "[", "_geo_to_fea...
Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string
[ "Return", "a", "GeoJSON", "string", "from", "a", "variety", "of", "inputs", ".", "See", "the", "documentation", "for", "make_url", "for", "the", "possible", "contents", "input", "." ]
train
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L99-L128
jwass/geojsonio.py
geojsonio/geojsonio.py
data_url
def data_url(contents, domain=DEFAULT_DOMAIN): """ Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io """ url = (domain + '#data=data:application/json,' + urllib.parse.qu...
python
def data_url(contents, domain=DEFAULT_DOMAIN): """ Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io """ url = (domain + '#data=data:application/json,' + urllib.parse.qu...
[ "def", "data_url", "(", "contents", ",", "domain", "=", "DEFAULT_DOMAIN", ")", ":", "url", "=", "(", "domain", "+", "'#data=data:application/json,'", "+", "urllib", ".", "parse", ".", "quote", "(", "contents", ")", ")", "return", "url" ]
Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io
[ "Return", "the", "URL", "for", "embedding", "the", "GeoJSON", "data", "in", "the", "URL", "hash" ]
train
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L149-L161
jwass/geojsonio.py
geojsonio/geojsonio.py
_make_gist
def _make_gist(contents, description='', filename='data.geojson'): """ Create and return an anonymous gist with a single file and specified contents """ ghapi = github3.GitHub() files = {filename: {'content': contents}} gist = ghapi.create_gist(description, files) return gist
python
def _make_gist(contents, description='', filename='data.geojson'): """ Create and return an anonymous gist with a single file and specified contents """ ghapi = github3.GitHub() files = {filename: {'content': contents}} gist = ghapi.create_gist(description, files) return gist
[ "def", "_make_gist", "(", "contents", ",", "description", "=", "''", ",", "filename", "=", "'data.geojson'", ")", ":", "ghapi", "=", "github3", ".", "GitHub", "(", ")", "files", "=", "{", "filename", ":", "{", "'content'", ":", "contents", "}", "}", "g...
Create and return an anonymous gist with a single file and specified contents
[ "Create", "and", "return", "an", "anonymous", "gist", "with", "a", "single", "file", "and", "specified", "contents" ]
train
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L164-L174
nschloe/orthopy
orthopy/line_segment/tools.py
clenshaw
def clenshaw(a, alpha, beta, t): """Clenshaw's algorithm for evaluating S(t) = \\sum a_k P_k(alpha, beta)(t) where P_k(alpha, beta) is the kth orthogonal polynomial defined by the recurrence coefficients alpha, beta. See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details. """ ...
python
def clenshaw(a, alpha, beta, t): """Clenshaw's algorithm for evaluating S(t) = \\sum a_k P_k(alpha, beta)(t) where P_k(alpha, beta) is the kth orthogonal polynomial defined by the recurrence coefficients alpha, beta. See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details. """ ...
[ "def", "clenshaw", "(", "a", ",", "alpha", ",", "beta", ",", "t", ")", ":", "n", "=", "len", "(", "alpha", ")", "assert", "len", "(", "beta", ")", "==", "n", "assert", "len", "(", "a", ")", "==", "n", "+", "1", "try", ":", "b", "=", "numpy"...
Clenshaw's algorithm for evaluating S(t) = \\sum a_k P_k(alpha, beta)(t) where P_k(alpha, beta) is the kth orthogonal polynomial defined by the recurrence coefficients alpha, beta. See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details.
[ "Clenshaw", "s", "algorithm", "for", "evaluating" ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/line_segment/tools.py#L8-L39
nschloe/orthopy
orthopy/e1r/orth.py
tree
def tree(X, n, alpha=0, symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. Set alpha=0 (default) to get classical Laguerre. """ args = recurrence_coefficients(n, alpha=alpha, symbolic=symbolic) return line_tree(X, *args)
python
def tree(X, n, alpha=0, symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. Set alpha=0 (default) to get classical Laguerre. """ args = recurrence_coefficients(n, alpha=alpha, symbolic=symbolic) return line_tree(X, *args)
[ "def", "tree", "(", "X", ",", "n", ",", "alpha", "=", "0", ",", "symbolic", "=", "False", ")", ":", "args", "=", "recurrence_coefficients", "(", "n", ",", "alpha", "=", "alpha", ",", "symbolic", "=", "symbolic", ")", "return", "line_tree", "(", "X", ...
Recurrence coefficients for generalized Laguerre polynomials. Set alpha=0 (default) to get classical Laguerre.
[ "Recurrence", "coefficients", "for", "generalized", "Laguerre", "polynomials", ".", "Set", "alpha", "=", "0", "(", "default", ")", "to", "get", "classical", "Laguerre", "." ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/e1r/orth.py#L12-L17
nschloe/orthopy
orthopy/e1r/orth.py
recurrence_coefficients
def recurrence_coefficients(n, alpha, standardization="normal", symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k """ S = sympy.S if symbolic else lambda x: x sqrt = sympy.sqrt if symbolic else numpy.sqrt ...
python
def recurrence_coefficients(n, alpha, standardization="normal", symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k """ S = sympy.S if symbolic else lambda x: x sqrt = sympy.sqrt if symbolic else numpy.sqrt ...
[ "def", "recurrence_coefficients", "(", "n", ",", "alpha", ",", "standardization", "=", "\"normal\"", ",", "symbolic", "=", "False", ")", ":", "S", "=", "sympy", ".", "S", "if", "symbolic", "else", "lambda", "x", ":", "x", "sqrt", "=", "sympy", ".", "sq...
Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k
[ "Recurrence", "coefficients", "for", "generalized", "Laguerre", "polynomials", "." ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/e1r/orth.py#L20-L53
nschloe/orthopy
orthopy/line_segment/recurrence_coefficients.py
jacobi
def jacobi(n, alpha, beta, standardization, symbolic=False): """Generate the recurrence coefficients a_k, b_k, c_k in P_{k+1}(x) = (a_k x - b_k)*P_{k}(x) - c_k P_{k-1}(x) for the Jacobi polynomials which are orthogonal on [-1, 1] with respect to the weight w(x)=[(1-x)^alpha]*[(1+x)^beta]; see <htt...
python
def jacobi(n, alpha, beta, standardization, symbolic=False): """Generate the recurrence coefficients a_k, b_k, c_k in P_{k+1}(x) = (a_k x - b_k)*P_{k}(x) - c_k P_{k-1}(x) for the Jacobi polynomials which are orthogonal on [-1, 1] with respect to the weight w(x)=[(1-x)^alpha]*[(1+x)^beta]; see <htt...
[ "def", "jacobi", "(", "n", ",", "alpha", ",", "beta", ",", "standardization", ",", "symbolic", "=", "False", ")", ":", "gamma", "=", "sympy", ".", "gamma", "if", "symbolic", "else", "lambda", "x", ":", "scipy", ".", "special", ".", "gamma", "(", "flo...
Generate the recurrence coefficients a_k, b_k, c_k in P_{k+1}(x) = (a_k x - b_k)*P_{k}(x) - c_k P_{k-1}(x) for the Jacobi polynomials which are orthogonal on [-1, 1] with respect to the weight w(x)=[(1-x)^alpha]*[(1+x)^beta]; see <https://en.wikipedia.org/wiki/Jacobi_polynomials#Recurrence_relations>.
[ "Generate", "the", "recurrence", "coefficients", "a_k", "b_k", "c_k", "in" ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/line_segment/recurrence_coefficients.py#L28-L211
nschloe/orthopy
orthopy/disk/tools.py
plot
def plot(f, lcar=1.0e-1): """Plot function over a disk. """ import matplotlib import matplotlib.pyplot as plt import pygmsh geom = pygmsh.built_in.Geometry() geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True) points, cells, _, _, _ = pygmsh.generate_mesh(geom, ve...
python
def plot(f, lcar=1.0e-1): """Plot function over a disk. """ import matplotlib import matplotlib.pyplot as plt import pygmsh geom = pygmsh.built_in.Geometry() geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True) points, cells, _, _, _ = pygmsh.generate_mesh(geom, ve...
[ "def", "plot", "(", "f", ",", "lcar", "=", "1.0e-1", ")", ":", "import", "matplotlib", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "pygmsh", "geom", "=", "pygmsh", ".", "built_in", ".", "Geometry", "(", ")", "geom", ".", "add_circle", ...
Plot function over a disk.
[ "Plot", "function", "over", "a", "disk", "." ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/disk/tools.py#L13-L45
nschloe/orthopy
orthopy/ncube/orth.py
tree
def tree(X, n, symbolic=False): """Evaluates the entire tree of orthogonal polynomials for the n-cube The computation is organized such that tree returns a list of arrays, L={0, ..., dim}, where each level corresponds to the polynomial degree L. Further, each level is organized like a discrete (dim-1)-...
python
def tree(X, n, symbolic=False): """Evaluates the entire tree of orthogonal polynomials for the n-cube The computation is organized such that tree returns a list of arrays, L={0, ..., dim}, where each level corresponds to the polynomial degree L. Further, each level is organized like a discrete (dim-1)-...
[ "def", "tree", "(", "X", ",", "n", ",", "symbolic", "=", "False", ")", ":", "p0", ",", "a", ",", "b", ",", "c", "=", "legendre", "(", "n", "+", "1", ",", "\"normal\"", ",", "symbolic", "=", "symbolic", ")", "dim", "=", "X", ".", "shape", "[",...
Evaluates the entire tree of orthogonal polynomials for the n-cube The computation is organized such that tree returns a list of arrays, L={0, ..., dim}, where each level corresponds to the polynomial degree L. Further, each level is organized like a discrete (dim-1)-dimensional simplex. Let's demonstr...
[ "Evaluates", "the", "entire", "tree", "of", "orthogonal", "polynomials", "for", "the", "n", "-", "cube" ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/ncube/orth.py#L11-L76
nschloe/orthopy
orthopy/tools.py
line_evaluate
def line_evaluate(t, p0, a, b, c): """Evaluate the orthogonal polynomial defined by its recurrence coefficients a, b, and c at the point(s) t. """ vals1 = numpy.zeros_like(t, dtype=int) # The order is important here; see # <https://github.com/sympy/sympy/issues/13637>. vals2 = numpy.ones_lik...
python
def line_evaluate(t, p0, a, b, c): """Evaluate the orthogonal polynomial defined by its recurrence coefficients a, b, and c at the point(s) t. """ vals1 = numpy.zeros_like(t, dtype=int) # The order is important here; see # <https://github.com/sympy/sympy/issues/13637>. vals2 = numpy.ones_lik...
[ "def", "line_evaluate", "(", "t", ",", "p0", ",", "a", ",", "b", ",", "c", ")", ":", "vals1", "=", "numpy", ".", "zeros_like", "(", "t", ",", "dtype", "=", "int", ")", "# The order is important here; see", "# <https://github.com/sympy/sympy/issues/13637>.", "v...
Evaluate the orthogonal polynomial defined by its recurrence coefficients a, b, and c at the point(s) t.
[ "Evaluate", "the", "orthogonal", "polynomial", "defined", "by", "its", "recurrence", "coefficients", "a", "b", "and", "c", "at", "the", "point", "(", "s", ")", "t", "." ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/tools.py#L21-L33
nschloe/orthopy
orthopy/triangle/tools.py
plot
def plot(corners, f, n=100): """Plot function over a triangle. """ import matplotlib.tri import matplotlib.pyplot as plt # discretization points def partition(boxes, balls): # <https://stackoverflow.com/a/36748940/353337> def rec(boxes, balls, parent=tuple()): if box...
python
def plot(corners, f, n=100): """Plot function over a triangle. """ import matplotlib.tri import matplotlib.pyplot as plt # discretization points def partition(boxes, balls): # <https://stackoverflow.com/a/36748940/353337> def rec(boxes, balls, parent=tuple()): if box...
[ "def", "plot", "(", "corners", ",", "f", ",", "n", "=", "100", ")", ":", "import", "matplotlib", ".", "tri", "import", "matplotlib", ".", "pyplot", "as", "plt", "# discretization points", "def", "partition", "(", "boxes", ",", "balls", ")", ":", "# <http...
Plot function over a triangle.
[ "Plot", "function", "over", "a", "triangle", "." ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/triangle/tools.py#L16-L63
learningequality/le-utils
le_utils/constants/languages.py
_iget
def _iget(key, lookup_dict): """ Case-insensitive search for `key` within keys of `lookup_dict`. """ for k, v in lookup_dict.items(): if k.lower() == key.lower(): return v return None
python
def _iget(key, lookup_dict): """ Case-insensitive search for `key` within keys of `lookup_dict`. """ for k, v in lookup_dict.items(): if k.lower() == key.lower(): return v return None
[ "def", "_iget", "(", "key", ",", "lookup_dict", ")", ":", "for", "k", ",", "v", "in", "lookup_dict", ".", "items", "(", ")", ":", "if", "k", ".", "lower", "(", ")", "==", "key", ".", "lower", "(", ")", ":", "return", "v", "return", "None" ]
Case-insensitive search for `key` within keys of `lookup_dict`.
[ "Case", "-", "insensitive", "search", "for", "key", "within", "keys", "of", "lookup_dict", "." ]
train
https://github.com/learningequality/le-utils/blob/07a776e3d5c288818764a25170de2e9ec5850c0d/le_utils/constants/languages.py#L83-L90
learningequality/le-utils
le_utils/constants/languages.py
getlang_by_name
def getlang_by_name(name): """ Try to lookup a Language object by name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json. """ direct_match = _iget(name, _LANGUAGE_NAME_LOOKUP) if direct_match: return direct_match ...
python
def getlang_by_name(name): """ Try to lookup a Language object by name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json. """ direct_match = _iget(name, _LANGUAGE_NAME_LOOKUP) if direct_match: return direct_match ...
[ "def", "getlang_by_name", "(", "name", ")", ":", "direct_match", "=", "_iget", "(", "name", ",", "_LANGUAGE_NAME_LOOKUP", ")", "if", "direct_match", ":", "return", "direct_match", "else", ":", "simple_name", "=", "name", ".", "split", "(", "','", ")", "[", ...
Try to lookup a Language object by name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json.
[ "Try", "to", "lookup", "a", "Language", "object", "by", "name", "e", ".", "g", ".", "English", "in", "internal", "language", "list", ".", "Returns", "None", "if", "lookup", "by", "language", "name", "fails", "in", "resources", "/", "languagelookup", ".", ...
train
https://github.com/learningequality/le-utils/blob/07a776e3d5c288818764a25170de2e9ec5850c0d/le_utils/constants/languages.py#L146-L157
learningequality/le-utils
le_utils/constants/languages.py
getlang_by_native_name
def getlang_by_native_name(native_name): """ Try to lookup a Language object by native_name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json. """ direct_match = _iget(native_name, _LANGUAGE_NATIVE_NAME_LOOKUP) if direct_ma...
python
def getlang_by_native_name(native_name): """ Try to lookup a Language object by native_name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json. """ direct_match = _iget(native_name, _LANGUAGE_NATIVE_NAME_LOOKUP) if direct_ma...
[ "def", "getlang_by_native_name", "(", "native_name", ")", ":", "direct_match", "=", "_iget", "(", "native_name", ",", "_LANGUAGE_NATIVE_NAME_LOOKUP", ")", "if", "direct_match", ":", "return", "direct_match", "else", ":", "simple_native_name", "=", "native_name", ".", ...
Try to lookup a Language object by native_name, e.g. 'English', in internal language list. Returns None if lookup by language name fails in resources/languagelookup.json.
[ "Try", "to", "lookup", "a", "Language", "object", "by", "native_name", "e", ".", "g", ".", "English", "in", "internal", "language", "list", ".", "Returns", "None", "if", "lookup", "by", "language", "name", "fails", "in", "resources", "/", "languagelookup", ...
train
https://github.com/learningequality/le-utils/blob/07a776e3d5c288818764a25170de2e9ec5850c0d/le_utils/constants/languages.py#L185-L196
learningequality/le-utils
le_utils/constants/languages.py
getlang_by_alpha2
def getlang_by_alpha2(code): """ Lookup a Language object for language code `code` based on these strategies: - Special case rules for Hebrew and Chinese Hans/Hant scripts - Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a language with the same `name` in the internal...
python
def getlang_by_alpha2(code): """ Lookup a Language object for language code `code` based on these strategies: - Special case rules for Hebrew and Chinese Hans/Hant scripts - Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a language with the same `name` in the internal...
[ "def", "getlang_by_alpha2", "(", "code", ")", ":", "# Handle special cases for language codes returned by YouTube API", "if", "code", "==", "'iw'", ":", "# handle old Hebrew code 'iw' and return modern code 'he'", "return", "getlang", "(", "'he'", ")", "elif", "'zh-Hans'", "i...
Lookup a Language object for language code `code` based on these strategies: - Special case rules for Hebrew and Chinese Hans/Hant scripts - Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a language with the same `name` in the internal representaion Returns `None` if no m...
[ "Lookup", "a", "Language", "object", "for", "language", "code", "code", "based", "on", "these", "strategies", ":", "-", "Special", "case", "rules", "for", "Hebrew", "and", "Chinese", "Hans", "/", "Hant", "scripts", "-", "Using", "alpha_2", "lookup", "in", ...
train
https://github.com/learningequality/le-utils/blob/07a776e3d5c288818764a25170de2e9ec5850c0d/le_utils/constants/languages.py#L200-L231
nschloe/orthopy
orthopy/sphere/tools.py
write
def write(filename, f): """Write a function `f` defined in terms of spherical coordinates to a file. """ import meshio import meshzoo points, cells = meshzoo.iso_sphere(5) # get spherical coordinates from points polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], ...
python
def write(filename, f): """Write a function `f` defined in terms of spherical coordinates to a file. """ import meshio import meshzoo points, cells = meshzoo.iso_sphere(5) # get spherical coordinates from points polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], ...
[ "def", "write", "(", "filename", ",", "f", ")", ":", "import", "meshio", "import", "meshzoo", "points", ",", "cells", "=", "meshzoo", ".", "iso_sphere", "(", "5", ")", "# get spherical coordinates from points", "polar", "=", "numpy", ".", "arccos", "(", "poi...
Write a function `f` defined in terms of spherical coordinates to a file.
[ "Write", "a", "function", "f", "defined", "in", "terms", "of", "spherical", "coordinates", "to", "a", "file", "." ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/sphere/tools.py#L6-L18
nschloe/orthopy
orthopy/sphere/orth.py
tree_sph
def tree_sph(polar, azimuthal, n, standardization, symbolic=False): """Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`. """ cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos # Conventions from # <https://en.wikipedia.org/wiki/Spherical_harmonics#O...
python
def tree_sph(polar, azimuthal, n, standardization, symbolic=False): """Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`. """ cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos # Conventions from # <https://en.wikipedia.org/wiki/Spherical_harmonics#O...
[ "def", "tree_sph", "(", "polar", ",", "azimuthal", ",", "n", ",", "standardization", ",", "symbolic", "=", "False", ")", ":", "cos", "=", "numpy", ".", "vectorize", "(", "sympy", ".", "cos", ")", "if", "symbolic", "else", "numpy", ".", "cos", "# Conven...
Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`.
[ "Evaluate", "all", "spherical", "harmonics", "of", "degree", "at", "most", "n", "at", "angles", "polar", "azimuthal", "." ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/sphere/orth.py#L9-L33
nschloe/orthopy
orthopy/line_segment/orth.py
tree_alp
def tree_alp( x, n, standardization, phi=None, with_condon_shortley_phase=True, symbolic=False ): """Evaluates the entire tree of associated Legendre polynomials up to depth n. There are many recurrence relations that can be used to construct the associated Legendre polynomials. However, only few ar...
python
def tree_alp( x, n, standardization, phi=None, with_condon_shortley_phase=True, symbolic=False ): """Evaluates the entire tree of associated Legendre polynomials up to depth n. There are many recurrence relations that can be used to construct the associated Legendre polynomials. However, only few ar...
[ "def", "tree_alp", "(", "x", ",", "n", ",", "standardization", ",", "phi", "=", "None", ",", "with_condon_shortley_phase", "=", "True", ",", "symbolic", "=", "False", ")", ":", "# assert numpy.all(numpy.abs(x) <= 1.0)", "d", "=", "{", "\"natural\"", ":", "(", ...
Evaluates the entire tree of associated Legendre polynomials up to depth n. There are many recurrence relations that can be used to construct the associated Legendre polynomials. However, only few are numerically stable. Many implementations (including this one) use the classical Legendre recurrence...
[ "Evaluates", "the", "entire", "tree", "of", "associated", "Legendre", "polynomials", "up", "to", "depth", "n", ".", "There", "are", "many", "recurrence", "relations", "that", "can", "be", "used", "to", "construct", "the", "associated", "Legendre", "polynomials",...
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/line_segment/orth.py#L186-L260
nschloe/orthopy
orthopy/disk/orth.py
tree
def tree(X, n, symbolic=False): """Evaluates the entire tree of orthogonal polynomials on the unit disk. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ... ....
python
def tree(X, n, symbolic=False): """Evaluates the entire tree of orthogonal polynomials on the unit disk. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ... ....
[ "def", "tree", "(", "X", ",", "n", ",", "symbolic", "=", "False", ")", ":", "frac", "=", "sympy", ".", "Rational", "if", "symbolic", "else", "lambda", "x", ",", "y", ":", "x", "/", "y", "sqrt", "=", "sympy", ".", "sqrt", "if", "symbolic", "else",...
Evaluates the entire tree of orthogonal polynomials on the unit disk. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ... ... ...
[ "Evaluates", "the", "entire", "tree", "of", "orthogonal", "polynomials", "on", "the", "unit", "disk", "." ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/disk/orth.py#L9-L89
nschloe/orthopy
orthopy/triangle/orth.py
tree
def tree(bary, n, standardization, symbolic=False): """Evaluates the entire tree of orthogonal triangle polynomials. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ...
python
def tree(bary, n, standardization, symbolic=False): """Evaluates the entire tree of orthogonal triangle polynomials. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ...
[ "def", "tree", "(", "bary", ",", "n", ",", "standardization", ",", "symbolic", "=", "False", ")", ":", "S", "=", "numpy", ".", "vectorize", "(", "sympy", ".", "S", ")", "if", "symbolic", "else", "lambda", "x", ":", "x", "sqrt", "=", "numpy", ".", ...
Evaluates the entire tree of orthogonal triangle polynomials. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ... ... ... For reference, see Abedal...
[ "Evaluates", "the", "entire", "tree", "of", "orthogonal", "triangle", "polynomials", "." ]
train
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/triangle/orth.py#L9-L126
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
check_if_this_file_exist
def check_if_this_file_exist(filename): """Check if this file exist and if it's a directory This function will check if the given filename actually exists and if it's not a Directory Arguments: filename {string} -- filename Return: True : if it's not a directory and if this file ...
python
def check_if_this_file_exist(filename): """Check if this file exist and if it's a directory This function will check if the given filename actually exists and if it's not a Directory Arguments: filename {string} -- filename Return: True : if it's not a directory and if this file ...
[ "def", "check_if_this_file_exist", "(", "filename", ")", ":", "#get the absolute path", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "#Boolean", "this_file_exist", "=", "os", ".", "path", ".", "exists", "(", "filename", ")", "a_dir...
Check if this file exist and if it's a directory This function will check if the given filename actually exists and if it's not a Directory Arguments: filename {string} -- filename Return: True : if it's not a directory and if this file exist False : If it's not a file and if...
[ "Check", "if", "this", "file", "exist", "and", "if", "it", "s", "a", "directory" ]
train
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L17-L41
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
command_line
def command_line(cmd): """Handle the command line call keyword arguments: cmd = a list return 0 if error or a string for the command line output """ try: s = subprocess.Popen(cmd, stdout=subprocess.PIPE) s = s.stdout.read() return s.strip() except subproce...
python
def command_line(cmd): """Handle the command line call keyword arguments: cmd = a list return 0 if error or a string for the command line output """ try: s = subprocess.Popen(cmd, stdout=subprocess.PIPE) s = s.stdout.read() return s.strip() except subproce...
[ "def", "command_line", "(", "cmd", ")", ":", "try", ":", "s", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "s", "=", "s", ".", "stdout", ".", "read", "(", ")", "return", "s", ".", "strip", "(", ...
Handle the command line call keyword arguments: cmd = a list return 0 if error or a string for the command line output
[ "Handle", "the", "command", "line", "call" ]
train
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L45-L62
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
information
def information(filename): """Returns the file exif""" check_if_this_file_exist(filename) filename = os.path.abspath(filename) result = get_json(filename) result = result[0] return result
python
def information(filename): """Returns the file exif""" check_if_this_file_exist(filename) filename = os.path.abspath(filename) result = get_json(filename) result = result[0] return result
[ "def", "information", "(", "filename", ")", ":", "check_if_this_file_exist", "(", "filename", ")", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "result", "=", "get_json", "(", "filename", ")", "result", "=", "result", "[", "0",...
Returns the file exif
[ "Returns", "the", "file", "exif" ]
train
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L64-L70
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
get_json
def get_json(filename): """ Return a json value of the exif Get a filename and return a JSON object Arguments: filename {string} -- your filename Returns: [JSON] -- Return a JSON object """ check_if_this_file_exist(filename) #Process this function filename = os.path.a...
python
def get_json(filename): """ Return a json value of the exif Get a filename and return a JSON object Arguments: filename {string} -- your filename Returns: [JSON] -- Return a JSON object """ check_if_this_file_exist(filename) #Process this function filename = os.path.a...
[ "def", "get_json", "(", "filename", ")", ":", "check_if_this_file_exist", "(", "filename", ")", "#Process this function", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "s", "=", "command_line", "(", "[", "'exiftool'", ",", "'-G'", ...
Return a json value of the exif Get a filename and return a JSON object Arguments: filename {string} -- your filename Returns: [JSON] -- Return a JSON object
[ "Return", "a", "json", "value", "of", "the", "exif" ]
train
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L100-L121
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
get_csv
def get_csv(filename): """ Return a csv representation of the exif get a filename and returns a unicode string with a CSV format Arguments: filename {string} -- your filename Returns: [unicode] -- unicode string """ check_if_this_file_exist(filename) #Process this functio...
python
def get_csv(filename): """ Return a csv representation of the exif get a filename and returns a unicode string with a CSV format Arguments: filename {string} -- your filename Returns: [unicode] -- unicode string """ check_if_this_file_exist(filename) #Process this functio...
[ "def", "get_csv", "(", "filename", ")", ":", "check_if_this_file_exist", "(", "filename", ")", "#Process this function", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "s", "=", "command_line", "(", "[", "'exiftool'", ",", "'-G'", ...
Return a csv representation of the exif get a filename and returns a unicode string with a CSV format Arguments: filename {string} -- your filename Returns: [unicode] -- unicode string
[ "Return", "a", "csv", "representation", "of", "the", "exif" ]
train
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L123-L144
guinslym/pyexifinfo
setup.py
print_a_header
def print_a_header(message="-"): """Header This function will output a message in a header Keyword Arguments: message {str} -- [the message string] (default: {"-"}) """ print("-".center(60,'-')) print(message.center(60,'-')) print("-".center(60,'-')) print()
python
def print_a_header(message="-"): """Header This function will output a message in a header Keyword Arguments: message {str} -- [the message string] (default: {"-"}) """ print("-".center(60,'-')) print(message.center(60,'-')) print("-".center(60,'-')) print()
[ "def", "print_a_header", "(", "message", "=", "\"-\"", ")", ":", "print", "(", "\"-\"", ".", "center", "(", "60", ",", "'-'", ")", ")", "print", "(", "message", ".", "center", "(", "60", ",", "'-'", ")", ")", "print", "(", "\"-\"", ".", "center", ...
Header This function will output a message in a header Keyword Arguments: message {str} -- [the message string] (default: {"-"})
[ "Header" ]
train
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/setup.py#L22-L33
guinslym/pyexifinfo
setup.py
check_if_exiftool_is_already_installed
def check_if_exiftool_is_already_installed(): """Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not """ result = 1; command = ["exiftool", "-ver"] with open(os.devnull, "w") as fnull: res...
python
def check_if_exiftool_is_already_installed(): """Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not """ result = 1; command = ["exiftool", "-ver"] with open(os.devnull, "w") as fnull: res...
[ "def", "check_if_exiftool_is_already_installed", "(", ")", ":", "result", "=", "1", "command", "=", "[", "\"exiftool\"", ",", "\"-ver\"", "]", "with", "open", "(", "os", ".", "devnull", ",", "\"w\"", ")", "as", "fnull", ":", "result", "=", "subprocess", "....
Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not
[ "Requirements" ]
train
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/setup.py#L35-L59
artemrizhov/django-mail-templated
mail_templated/message.py
EmailMessage.render
def render(self, context=None, clean=False): """ Render email with provided context Arguments --------- context : dict |context| If not specified then the :attr:`~mail_templated.EmailMessage.context` property is used. Keyword Argument...
python
def render(self, context=None, clean=False): """ Render email with provided context Arguments --------- context : dict |context| If not specified then the :attr:`~mail_templated.EmailMessage.context` property is used. Keyword Argument...
[ "def", "render", "(", "self", ",", "context", "=", "None", ",", "clean", "=", "False", ")", ":", "# Load template if it is not loaded yet.", "if", "not", "self", ".", "template", ":", "self", ".", "load_template", "(", "self", ".", "template_name", ")", "# T...
Render email with provided context Arguments --------- context : dict |context| If not specified then the :attr:`~mail_templated.EmailMessage.context` property is used. Keyword Arguments ----------------- clean : bool If `...
[ "Render", "email", "with", "provided", "context" ]
train
https://github.com/artemrizhov/django-mail-templated/blob/1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932/mail_templated/message.py#L153-L205
artemrizhov/django-mail-templated
mail_templated/message.py
EmailMessage.send
def send(self, *args, **kwargs): """ Send email message, render if it is not rendered yet. Note ---- Any extra arguments are passed to :class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`. Keyword Arguments ----------------- cle...
python
def send(self, *args, **kwargs): """ Send email message, render if it is not rendered yet. Note ---- Any extra arguments are passed to :class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`. Keyword Arguments ----------------- cle...
[ "def", "send", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "clean", "=", "kwargs", ".", "pop", "(", "'clean'", ",", "False", ")", "if", "not", "self", ".", "_is_rendered", ":", "self", ".", "render", "(", ")", "if", "clean",...
Send email message, render if it is not rendered yet. Note ---- Any extra arguments are passed to :class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`. Keyword Arguments ----------------- clean : bool If ``True``, remove any templat...
[ "Send", "email", "message", "render", "if", "it", "is", "not", "rendered", "yet", "." ]
train
https://github.com/artemrizhov/django-mail-templated/blob/1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932/mail_templated/message.py#L207-L227
artemrizhov/django-mail-templated
mail_templated/utils.py
send_mail
def send_mail(template_name, context, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, **kwargs): """ Easy wrapper for sending a single email message to a recipient list using django template system. It works almost the sa...
python
def send_mail(template_name, context, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, **kwargs): """ Easy wrapper for sending a single email message to a recipient list using django template system. It works almost the sa...
[ "def", "send_mail", "(", "template_name", ",", "context", ",", "from_email", ",", "recipient_list", ",", "fail_silently", "=", "False", ",", "auth_user", "=", "None", ",", "auth_password", "=", "None", ",", "connection", "=", "None", ",", "*", "*", "kwargs",...
Easy wrapper for sending a single email message to a recipient list using django template system. It works almost the same way as the standard :func:`send_mail()<django.core.mail.send_mail>` function. .. |main_difference| replace:: The main difference is that two first arguments ``subject`` an...
[ "Easy", "wrapper", "for", "sending", "a", "single", "email", "message", "to", "a", "recipient", "list", "using", "django", "template", "system", "." ]
train
https://github.com/artemrizhov/django-mail-templated/blob/1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932/mail_templated/utils.py#L13-L93
brianhie/scanorama
bin/unsupervised.py
silhouette_score
def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b...
python
def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b...
[ "def", "silhouette_score", "(", "X", ",", "labels", ",", "metric", "=", "'euclidean'", ",", "sample_size", "=", "None", ",", "random_state", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "sample_size", "is", "not", "None", ":", "X", ",", "labels"...
Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. To clarify, ``b`` is the di...
[ "Compute", "the", "mean", "Silhouette", "Coefficient", "of", "all", "samples", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/bin/unsupervised.py#L27-L106
brianhie/scanorama
bin/unsupervised.py
silhouette_samples
def silhouette_samples(X, labels, metric='euclidean', **kwds): """Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to b...
python
def silhouette_samples(X, labels, metric='euclidean', **kwds): """Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to b...
[ "def", "silhouette_samples", "(", "X", ",", "labels", ",", "metric", "=", "'euclidean'", ",", "*", "*", "kwds", ")", ":", "X", ",", "labels", "=", "check_X_y", "(", "X", ",", "labels", ",", "accept_sparse", "=", "[", "'csc'", ",", "'csr'", "]", ")", ...
Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to be dense, where samples in the same cluster are similar to each oth...
[ "Compute", "the", "Silhouette", "Coefficient", "for", "each", "sample", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/bin/unsupervised.py#L109-L213
brianhie/scanorama
bin/unsupervised.py
calinski_harabaz_score
def calinski_harabaz_score(X, labels): """Compute the Calinski and Harabaz score. The score is defined as ratio between the within-cluster dispersion and the between-cluster dispersion. Read more in the :ref:`User Guide <calinski_harabaz_index>`. Parameters ---------- X : array-like, shap...
python
def calinski_harabaz_score(X, labels): """Compute the Calinski and Harabaz score. The score is defined as ratio between the within-cluster dispersion and the between-cluster dispersion. Read more in the :ref:`User Guide <calinski_harabaz_index>`. Parameters ---------- X : array-like, shap...
[ "def", "calinski_harabaz_score", "(", "X", ",", "labels", ")", ":", "X", ",", "labels", "=", "check_X_y", "(", "X", ",", "labels", ")", "le", "=", "LabelEncoder", "(", ")", "labels", "=", "le", ".", "fit_transform", "(", "labels", ")", "n_samples", ","...
Compute the Calinski and Harabaz score. The score is defined as ratio between the within-cluster dispersion and the between-cluster dispersion. Read more in the :ref:`User Guide <calinski_harabaz_index>`. Parameters ---------- X : array-like, shape (``n_samples``, ``n_features``) List...
[ "Compute", "the", "Calinski", "and", "Harabaz", "score", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/bin/unsupervised.py#L216-L263
brianhie/scanorama
scanorama/utils.py
handle_zeros_in_scale
def handle_zeros_in_scale(scale, copy=True): ''' Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features. Adapted from sklearn.preprocessing.data''' # if we are fitting on 1D arrays, scale might be a scalar if np.isscalar(scale): ...
python
def handle_zeros_in_scale(scale, copy=True): ''' Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features. Adapted from sklearn.preprocessing.data''' # if we are fitting on 1D arrays, scale might be a scalar if np.isscalar(scale): ...
[ "def", "handle_zeros_in_scale", "(", "scale", ",", "copy", "=", "True", ")", ":", "# if we are fitting on 1D arrays, scale might be a scalar", "if", "np", ".", "isscalar", "(", "scale", ")", ":", "if", "scale", "==", ".0", ":", "scale", "=", "1.", "return", "s...
Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features. Adapted from sklearn.preprocessing.data
[ "Makes", "sure", "that", "whenever", "scale", "is", "zero", "we", "handle", "it", "correctly", ".", "This", "happens", "in", "most", "scalers", "when", "we", "have", "constant", "features", ".", "Adapted", "from", "sklearn", ".", "preprocessing", ".", "data"...
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/utils.py#L124-L139
brianhie/scanorama
scanorama/t_sne_approx.py
_joint_probabilities
def _joint_probabilities(distances, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances. Parameters ---------- distances : array, shape (n_samples * (n_samples-1) / 2,) Distances of samples are stored as condensed matrices, i.e. we omit the diagonal and dupl...
python
def _joint_probabilities(distances, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances. Parameters ---------- distances : array, shape (n_samples * (n_samples-1) / 2,) Distances of samples are stored as condensed matrices, i.e. we omit the diagonal and dupl...
[ "def", "_joint_probabilities", "(", "distances", ",", "desired_perplexity", ",", "verbose", ")", ":", "# Compute conditional probabilities such that they approximately match", "# the desired perplexity", "distances", "=", "distances", ".", "astype", "(", "np", ".", "float32",...
Compute joint probabilities p_ij from distances. Parameters ---------- distances : array, shape (n_samples * (n_samples-1) / 2,) Distances of samples are stored as condensed matrices, i.e. we omit the diagonal and duplicate entries and store everything in a one-dimensional array. ...
[ "Compute", "joint", "probabilities", "p_ij", "from", "distances", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L39-L68
brianhie/scanorama
scanorama/t_sne_approx.py
_joint_probabilities_nn
def _joint_probabilities_nn(distances, neighbors, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances using just nearest neighbors. This method is approximately equal to _joint_probabilities. The latter is O(N), but limiting the joint probability to nearest neighbors improv...
python
def _joint_probabilities_nn(distances, neighbors, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances using just nearest neighbors. This method is approximately equal to _joint_probabilities. The latter is O(N), but limiting the joint probability to nearest neighbors improv...
[ "def", "_joint_probabilities_nn", "(", "distances", ",", "neighbors", ",", "desired_perplexity", ",", "verbose", ")", ":", "t0", "=", "time", "(", ")", "# Compute conditional probabilities such that they approximately match", "# the desired perplexity", "n_samples", ",", "k...
Compute joint probabilities p_ij from distances using just nearest neighbors. This method is approximately equal to _joint_probabilities. The latter is O(N), but limiting the joint probability to nearest neighbors improves this substantially to O(uN). Parameters ---------- distances : arra...
[ "Compute", "joint", "probabilities", "p_ij", "from", "distances", "using", "just", "nearest", "neighbors", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L71-L124
brianhie/scanorama
scanorama/t_sne_approx.py
_kl_divergence
def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components, skip_num_points=0): """t-SNE objective function: gradient of the KL divergence of p_ijs and q_ijs and the absolute error. Parameters ---------- params : array, shape (n_params,) Unraveled embedding...
python
def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components, skip_num_points=0): """t-SNE objective function: gradient of the KL divergence of p_ijs and q_ijs and the absolute error. Parameters ---------- params : array, shape (n_params,) Unraveled embedding...
[ "def", "_kl_divergence", "(", "params", ",", "P", ",", "degrees_of_freedom", ",", "n_samples", ",", "n_components", ",", "skip_num_points", "=", "0", ")", ":", "X_embedded", "=", "params", ".", "reshape", "(", "n_samples", ",", "n_components", ")", "# Q is a h...
t-SNE objective function: gradient of the KL divergence of p_ijs and q_ijs and the absolute error. Parameters ---------- params : array, shape (n_params,) Unraveled embedding. P : array, shape (n_samples * (n_samples-1) / 2,) Condensed joint probability matrix. degrees_of_free...
[ "t", "-", "SNE", "objective", "function", ":", "gradient", "of", "the", "KL", "divergence", "of", "p_ijs", "and", "q_ijs", "and", "the", "absolute", "error", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L127-L189
brianhie/scanorama
scanorama/t_sne_approx.py
_kl_divergence_bh
def _kl_divergence_bh(params, P, degrees_of_freedom, n_samples, n_components, angle=0.5, skip_num_points=0, verbose=False): """t-SNE objective function: KL divergence of p_ijs and q_ijs. Uses Barnes-Hut tree methods to calculate the gradient that runs in O(NlogN) instead of O(N^2) ...
python
def _kl_divergence_bh(params, P, degrees_of_freedom, n_samples, n_components, angle=0.5, skip_num_points=0, verbose=False): """t-SNE objective function: KL divergence of p_ijs and q_ijs. Uses Barnes-Hut tree methods to calculate the gradient that runs in O(NlogN) instead of O(N^2) ...
[ "def", "_kl_divergence_bh", "(", "params", ",", "P", ",", "degrees_of_freedom", ",", "n_samples", ",", "n_components", ",", "angle", "=", "0.5", ",", "skip_num_points", "=", "0", ",", "verbose", "=", "False", ")", ":", "params", "=", "params", ".", "astype...
t-SNE objective function: KL divergence of p_ijs and q_ijs. Uses Barnes-Hut tree methods to calculate the gradient that runs in O(NlogN) instead of O(N^2) Parameters ---------- params : array, shape (n_params,) Unraveled embedding. P : csr sparse matrix, shape (n_samples, n_sample) ...
[ "t", "-", "SNE", "objective", "function", ":", "KL", "divergence", "of", "p_ijs", "and", "q_ijs", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L192-L258
brianhie/scanorama
scanorama/t_sne_approx.py
_gradient_descent
def _gradient_descent(objective, p0, it, n_iter, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7, verbose=0, args=None, kwargs=None): """Batch gradient descent with momentum and indivi...
python
def _gradient_descent(objective, p0, it, n_iter, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7, verbose=0, args=None, kwargs=None): """Batch gradient descent with momentum and indivi...
[ "def", "_gradient_descent", "(", "objective", ",", "p0", ",", "it", ",", "n_iter", ",", "n_iter_check", "=", "1", ",", "n_iter_without_progress", "=", "300", ",", "momentum", "=", "0.8", ",", "learning_rate", "=", "200.0", ",", "min_gain", "=", "0.01", ","...
Batch gradient descent with momentum and individual gains. Parameters ---------- objective : function or callable Should return a tuple of cost and gradient for a given parameter vector. When expensive to compute, the cost can optionally be None and can be computed every n_iter_chec...
[ "Batch", "gradient", "descent", "with", "momentum", "and", "individual", "gains", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L261-L383
brianhie/scanorama
scanorama/t_sne_approx.py
trustworthiness
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as .. math:: T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} \sum_{j \in U^{(k)}_i} (r(i, j) - k) ...
python
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as .. math:: T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} \sum_{j \in U^{(k)}_i} (r(i, j) - k) ...
[ "def", "trustworthiness", "(", "X", ",", "X_embedded", ",", "n_neighbors", "=", "5", ",", "precomputed", "=", "False", ")", ":", "if", "precomputed", ":", "dist_X", "=", "X", "else", ":", "dist_X", "=", "pairwise_distances", "(", "X", ",", "squared", "="...
Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as .. math:: T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} \sum_{j \in U^{(k)}_i} (r(i, j) - k) where :math:`r(i, j)` is the rank of the embedded datapoint j accordi...
[ "Expresses", "to", "what", "extent", "the", "local", "structure", "is", "retained", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L386-L445
brianhie/scanorama
scanorama/t_sne_approx.py
TSNEApprox._fit
def _fit(self, X, skip_num_points=0): """Fit the model using X as training data. Note that sparse arrays can only be handled by method='exact'. It is recommended that you convert your sparse array to dense (e.g. `X.toarray()`) if it fits in memory, or otherwise using a dimension...
python
def _fit(self, X, skip_num_points=0): """Fit the model using X as training data. Note that sparse arrays can only be handled by method='exact'. It is recommended that you convert your sparse array to dense (e.g. `X.toarray()`) if it fits in memory, or otherwise using a dimension...
[ "def", "_fit", "(", "self", ",", "X", ",", "skip_num_points", "=", "0", ")", ":", "if", "self", ".", "method", "not", "in", "[", "'barnes_hut'", ",", "'exact'", "]", ":", "raise", "ValueError", "(", "\"'method' must be 'barnes_hut' or 'exact'\"", ")", "if", ...
Fit the model using X as training data. Note that sparse arrays can only be handled by method='exact'. It is recommended that you convert your sparse array to dense (e.g. `X.toarray()`) if it fits in memory, or otherwise using a dimensionality reduction technique (e.g. TruncatedSVD). ...
[ "Fit", "the", "model", "using", "X", "as", "training", "data", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L621-L784
brianhie/scanorama
scanorama/t_sne_approx.py
TSNEApprox._tsne
def _tsne(self, P, degrees_of_freedom, n_samples, random_state, X_embedded, neighbors=None, skip_num_points=0): """Runs t-SNE.""" # t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P # and the Student's t-distributions Q. The optimization algorithm that # we ...
python
def _tsne(self, P, degrees_of_freedom, n_samples, random_state, X_embedded, neighbors=None, skip_num_points=0): """Runs t-SNE.""" # t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P # and the Student's t-distributions Q. The optimization algorithm that # we ...
[ "def", "_tsne", "(", "self", ",", "P", ",", "degrees_of_freedom", ",", "n_samples", ",", "random_state", ",", "X_embedded", ",", "neighbors", "=", "None", ",", "skip_num_points", "=", "0", ")", ":", "# t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P"...
Runs t-SNE.
[ "Runs", "t", "-", "SNE", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L792-L853
brianhie/scanorama
scanorama/t_sne_approx.py
TSNEApprox.fit_transform
def fit_transform(self, X, y=None): """Fit X into an embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance mat...
python
def fit_transform(self, X, y=None): """Fit X into an embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance mat...
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "embedding", "=", "self", ".", "_fit", "(", "X", ")", "self", ".", "embedding_", "=", "embedding", "return", "self", ".", "embedding_" ]
Fit X into an embedded space and return that transformed output. Parameters ---------- X : array, shape (n_samples, n_features) or (n_samples, n_samples) If the metric is 'precomputed' X must be a square distance matrix. Otherwise it contains a sample per row. ...
[ "Fit", "X", "into", "an", "embedded", "space", "and", "return", "that", "transformed", "output", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L855-L872
brianhie/scanorama
scanorama/scanorama.py
correct
def correct(datasets_full, genes_list, return_dimred=False, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, return_dense=False, hvg=None, union=False, geosketch=False, geosketch_max=20000): """Int...
python
def correct(datasets_full, genes_list, return_dimred=False, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, return_dense=False, hvg=None, union=False, geosketch=False, geosketch_max=20000): """Int...
[ "def", "correct", "(", "datasets_full", ",", "genes_list", ",", "return_dimred", "=", "False", ",", "batch_size", "=", "BATCH_SIZE", ",", "verbose", "=", "VERBOSE", ",", "ds_names", "=", "None", ",", "dimred", "=", "DIMRED", ",", "approx", "=", "APPROX", "...
Integrate and batch correct a list of data sets. Parameters ---------- datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray` Data sets to integrate and correct. genes_list: `list` of `list` of `string` List of genes for each data set. return_dimred: `bool`, optio...
[ "Integrate", "and", "batch", "correct", "a", "list", "of", "data", "sets", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L37-L111
brianhie/scanorama
scanorama/scanorama.py
integrate
def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, geosketch=False, geosketch_max=20000, n_iter=1, union=False, hvg=None): """Integrate a list of data sets. Pa...
python
def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, geosketch=False, geosketch_max=20000, n_iter=1, union=False, hvg=None): """Integrate a list of data sets. Pa...
[ "def", "integrate", "(", "datasets_full", ",", "genes_list", ",", "batch_size", "=", "BATCH_SIZE", ",", "verbose", "=", "VERBOSE", ",", "ds_names", "=", "None", ",", "dimred", "=", "DIMRED", ",", "approx", "=", "APPROX", ",", "sigma", "=", "SIGMA", ",", ...
Integrate a list of data sets. Parameters ---------- datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray` Data sets to integrate and correct. genes_list: `list` of `list` of `string` List of genes for each data set. batch_size: `int`, optional (default: `5000`) ...
[ "Integrate", "a", "list", "of", "data", "sets", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L114-L169
brianhie/scanorama
scanorama/scanorama.py
correct_scanpy
def correct_scanpy(adatas, **kwargs): """Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of paramet...
python
def correct_scanpy(adatas, **kwargs): """Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of paramet...
[ "def", "correct_scanpy", "(", "adatas", ",", "*", "*", "kwargs", ")", ":", "if", "'return_dimred'", "in", "kwargs", "and", "kwargs", "[", "'return_dimred'", "]", ":", "datasets_dimred", ",", "datasets", ",", "genes", "=", "correct", "(", "[", "adata", ".",...
Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of parameters to use for batch correction. Returns...
[ "Batch", "correct", "a", "list", "of", "scanpy", ".", "api", ".", "AnnData", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L172-L216
brianhie/scanorama
scanorama/scanorama.py
integrate_scanpy
def integrate_scanpy(adatas, **kwargs): """Integrate a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate. kwargs : `dict` See documentation for the `integrate()` method for a full list of parameters to use for ...
python
def integrate_scanpy(adatas, **kwargs): """Integrate a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate. kwargs : `dict` See documentation for the `integrate()` method for a full list of parameters to use for ...
[ "def", "integrate_scanpy", "(", "adatas", ",", "*", "*", "kwargs", ")", ":", "datasets_dimred", ",", "genes", "=", "integrate", "(", "[", "adata", ".", "X", "for", "adata", "in", "adatas", "]", ",", "[", "adata", ".", "var_names", ".", "values", "for",...
Integrate a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate. kwargs : `dict` See documentation for the `integrate()` method for a full list of parameters to use for batch correction. Returns ------- ...
[ "Integrate", "a", "list", "of", "scanpy", ".", "api", ".", "AnnData", "." ]
train
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L219-L242
johntfoster/bspline
bspline/splinelab.py
augknt
def augknt(knots, order): """Augment a knot vector. Parameters: knots: Python list or rank-1 array, the original knot vector (without endpoint repeats) order: int, >= 0, order of spline Returns: list_of_knots: rank-1 array that has (`order` + 1) copies of ``knots[0]``, then ``k...
python
def augknt(knots, order): """Augment a knot vector. Parameters: knots: Python list or rank-1 array, the original knot vector (without endpoint repeats) order: int, >= 0, order of spline Returns: list_of_knots: rank-1 array that has (`order` + 1) copies of ``knots[0]``, then ``k...
[ "def", "augknt", "(", "knots", ",", "order", ")", ":", "if", "isinstance", "(", "knots", ",", "np", ".", "ndarray", ")", "and", "knots", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"knots must be a list or a rank-1 array\"", ")", "knots", "="...
Augment a knot vector. Parameters: knots: Python list or rank-1 array, the original knot vector (without endpoint repeats) order: int, >= 0, order of spline Returns: list_of_knots: rank-1 array that has (`order` + 1) copies of ``knots[0]``, then ``knots[1:-1]``, and finally (`order...
[ "Augment", "a", "knot", "vector", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L23-L47
johntfoster/bspline
bspline/splinelab.py
aveknt
def aveknt(t, k): """Compute the running average of `k` successive elements of `t`. Return the averaged array. Parameters: t: Python list or rank-1 array k: int, >= 2, how many successive elements to average Returns: rank-1 array, averaged data. If k > len(t), returns a zero-length arr...
python
def aveknt(t, k): """Compute the running average of `k` successive elements of `t`. Return the averaged array. Parameters: t: Python list or rank-1 array k: int, >= 2, how many successive elements to average Returns: rank-1 array, averaged data. If k > len(t), returns a zero-length arr...
[ "def", "aveknt", "(", "t", ",", "k", ")", ":", "t", "=", "np", ".", "atleast_1d", "(", "t", ")", "if", "t", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"t must be a list or a rank-1 array\"", ")", "n", "=", "t", ".", "shape", "[", "0"...
Compute the running average of `k` successive elements of `t`. Return the averaged array. Parameters: t: Python list or rank-1 array k: int, >= 2, how many successive elements to average Returns: rank-1 array, averaged data. If k > len(t), returns a zero-length array. Caveat: This is ...
[ "Compute", "the", "running", "average", "of", "k", "successive", "elements", "of", "t", ".", "Return", "the", "averaged", "array", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L50-L78
johntfoster/bspline
bspline/splinelab.py
aptknt
def aptknt(tau, order): """Create an acceptable knot vector. Minimal emulation of MATLAB's ``aptknt``. The returned knot vector can be used to generate splines of desired `order` that are suitable for interpolation to the collocation sites `tau`. Note that this is only possible when ``len(tau)`` >= `order` + 1. ...
python
def aptknt(tau, order): """Create an acceptable knot vector. Minimal emulation of MATLAB's ``aptknt``. The returned knot vector can be used to generate splines of desired `order` that are suitable for interpolation to the collocation sites `tau`. Note that this is only possible when ``len(tau)`` >= `order` + 1. ...
[ "def", "aptknt", "(", "tau", ",", "order", ")", ":", "tau", "=", "np", ".", "atleast_1d", "(", "tau", ")", "k", "=", "order", "+", "1", "if", "tau", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"tau must be a list or a rank-1 array\"", ")"...
Create an acceptable knot vector. Minimal emulation of MATLAB's ``aptknt``. The returned knot vector can be used to generate splines of desired `order` that are suitable for interpolation to the collocation sites `tau`. Note that this is only possible when ``len(tau)`` >= `order` + 1. When this condition does not h...
[ "Create", "an", "acceptable", "knot", "vector", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L81-L145
johntfoster/bspline
bspline/splinelab.py
knt2mlt
def knt2mlt(t): """Count multiplicities of elements in a sorted list or rank-1 array. Minimal emulation of MATLAB's ``knt2mlt``. Parameters: t: Python list or rank-1 array. Must be sorted! Returns: out rank-1 array such that out[k] = #{ t[i] == t[k] for i < k } Example: If ``...
python
def knt2mlt(t): """Count multiplicities of elements in a sorted list or rank-1 array. Minimal emulation of MATLAB's ``knt2mlt``. Parameters: t: Python list or rank-1 array. Must be sorted! Returns: out rank-1 array such that out[k] = #{ t[i] == t[k] for i < k } Example: If ``...
[ "def", "knt2mlt", "(", "t", ")", ":", "t", "=", "np", ".", "atleast_1d", "(", "t", ")", "if", "t", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"t must be a list or a rank-1 array\"", ")", "out", "=", "[", "]", "e", "=", "None", "for", ...
Count multiplicities of elements in a sorted list or rank-1 array. Minimal emulation of MATLAB's ``knt2mlt``. Parameters: t: Python list or rank-1 array. Must be sorted! Returns: out rank-1 array such that out[k] = #{ t[i] == t[k] for i < k } Example: If ``t = [1, 1, 2, 3, 3, 3]`...
[ "Count", "multiplicities", "of", "elements", "in", "a", "sorted", "list", "or", "rank", "-", "1", "array", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L148-L182
johntfoster/bspline
bspline/splinelab.py
spcol
def spcol(knots, order, tau): """Return collocation matrix. Minimal emulation of MATLAB's ``spcol``. Parameters: knots: rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`) order: int, >= 0, order of spline tau: rank-1 array, collocation sit...
python
def spcol(knots, order, tau): """Return collocation matrix. Minimal emulation of MATLAB's ``spcol``. Parameters: knots: rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`) order: int, >= 0, order of spline tau: rank-1 array, collocation sit...
[ "def", "spcol", "(", "knots", ",", "order", ",", "tau", ")", ":", "m", "=", "knt2mlt", "(", "tau", ")", "B", "=", "bspline", ".", "Bspline", "(", "knots", ",", "order", ")", "dummy", "=", "B", "(", "0.", ")", "nbasis", "=", "len", "(", "dummy",...
Return collocation matrix. Minimal emulation of MATLAB's ``spcol``. Parameters: knots: rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`) order: int, >= 0, order of spline tau: rank-1 array, collocation sites Returns: rank-2 array A such ...
[ "Return", "collocation", "matrix", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L185-L220
johntfoster/bspline
bspline/bspline.py
Bspline.__basis0
def __basis0(self, xi): """Order zero basis (for internal use).""" return np.where(np.all([self.knot_vector[:-1] <= xi, xi < self.knot_vector[1:]],axis=0), 1.0, 0.0)
python
def __basis0(self, xi): """Order zero basis (for internal use).""" return np.where(np.all([self.knot_vector[:-1] <= xi, xi < self.knot_vector[1:]],axis=0), 1.0, 0.0)
[ "def", "__basis0", "(", "self", ",", "xi", ")", ":", "return", "np", ".", "where", "(", "np", ".", "all", "(", "[", "self", ".", "knot_vector", "[", ":", "-", "1", "]", "<=", "xi", ",", "xi", "<", "self", ".", "knot_vector", "[", "1", ":", "]...
Order zero basis (for internal use).
[ "Order", "zero", "basis", "(", "for", "internal", "use", ")", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L83-L86
johntfoster/bspline
bspline/bspline.py
Bspline.__basis
def __basis(self, xi, p, compute_derivatives=False): """Recursive Cox - de Boor function (for internal use). Compute basis functions and optionally their first derivatives. """ if p == 0: return self.__basis0(xi) else: basis_p_minus_1 = self.__basis(xi, ...
python
def __basis(self, xi, p, compute_derivatives=False): """Recursive Cox - de Boor function (for internal use). Compute basis functions and optionally their first derivatives. """ if p == 0: return self.__basis0(xi) else: basis_p_minus_1 = self.__basis(xi, ...
[ "def", "__basis", "(", "self", ",", "xi", ",", "p", ",", "compute_derivatives", "=", "False", ")", ":", "if", "p", "==", "0", ":", "return", "self", ".", "__basis0", "(", "xi", ")", "else", ":", "basis_p_minus_1", "=", "self", ".", "__basis", "(", ...
Recursive Cox - de Boor function (for internal use). Compute basis functions and optionally their first derivatives.
[ "Recursive", "Cox", "-", "de", "Boor", "function", "(", "for", "internal", "use", ")", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L88-L123
johntfoster/bspline
bspline/bspline.py
Bspline.d
def d(self, xi): """Convenience function to compute first derivative of basis functions. 'Memoized' for speed.""" return self.__basis(xi, self.p, compute_derivatives=True)
python
def d(self, xi): """Convenience function to compute first derivative of basis functions. 'Memoized' for speed.""" return self.__basis(xi, self.p, compute_derivatives=True)
[ "def", "d", "(", "self", ",", "xi", ")", ":", "return", "self", ".", "__basis", "(", "xi", ",", "self", ".", "p", ",", "compute_derivatives", "=", "True", ")" ]
Convenience function to compute first derivative of basis functions. 'Memoized' for speed.
[ "Convenience", "function", "to", "compute", "first", "derivative", "of", "basis", "functions", ".", "Memoized", "for", "speed", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L131-L133
johntfoster/bspline
bspline/bspline.py
Bspline.plot
def plot(self): """Plot basis functions over full range of knots. Convenience function. Requires matplotlib. """ try: import matplotlib.pyplot as plt except ImportError: from sys import stderr print("ERROR: matplotlib.pyplot not found, matplo...
python
def plot(self): """Plot basis functions over full range of knots. Convenience function. Requires matplotlib. """ try: import matplotlib.pyplot as plt except ImportError: from sys import stderr print("ERROR: matplotlib.pyplot not found, matplo...
[ "def", "plot", "(", "self", ")", ":", "try", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "except", "ImportError", ":", "from", "sys", "import", "stderr", "print", "(", "\"ERROR: matplotlib.pyplot not found, matplotlib must be installed to use this function\...
Plot basis functions over full range of knots. Convenience function. Requires matplotlib.
[ "Plot", "basis", "functions", "over", "full", "range", "of", "knots", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L135-L158
johntfoster/bspline
bspline/bspline.py
Bspline.__diff_internal
def __diff_internal(self): """Differentiate a B-spline once, and return the resulting coefficients and Bspline objects. This preserves the Bspline object nature of the data, enabling recursive implementation of higher-order differentiation (see `diff`). The value of the first derivative of `B` at a point `x` ...
python
def __diff_internal(self): """Differentiate a B-spline once, and return the resulting coefficients and Bspline objects. This preserves the Bspline object nature of the data, enabling recursive implementation of higher-order differentiation (see `diff`). The value of the first derivative of `B` at a point `x` ...
[ "def", "__diff_internal", "(", "self", ")", ":", "assert", "self", ".", "p", ">", "0", ",", "\"order of Bspline must be > 0\"", "# we already handle the other case in diff()", "# https://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-derv.html", "#", "t", "=",...
Differentiate a B-spline once, and return the resulting coefficients and Bspline objects. This preserves the Bspline object nature of the data, enabling recursive implementation of higher-order differentiation (see `diff`). The value of the first derivative of `B` at a point `x` can be obtained as:: def diff1(B,...
[ "Differentiate", "a", "B", "-", "spline", "once", "and", "return", "the", "resulting", "coefficients", "and", "Bspline", "objects", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L186-L222
johntfoster/bspline
bspline/bspline.py
Bspline.diff
def diff(self, order=1): """Differentiate a B-spline `order` number of times. Parameters: order: int, >= 0 Returns: **lambda** `x`: ... that evaluates the `order`-th derivative of `B` at the point `x`. The returned function internally uses __call__, which is 'memoized' for ...
python
def diff(self, order=1): """Differentiate a B-spline `order` number of times. Parameters: order: int, >= 0 Returns: **lambda** `x`: ... that evaluates the `order`-th derivative of `B` at the point `x`. The returned function internally uses __call__, which is 'memoized' for ...
[ "def", "diff", "(", "self", ",", "order", "=", "1", ")", ":", "order", "=", "int", "(", "order", ")", "if", "order", "<", "0", ":", "raise", "ValueError", "(", "\"order must be >= 0, got %d\"", "%", "(", "order", ")", ")", "if", "order", "==", "0", ...
Differentiate a B-spline `order` number of times. Parameters: order: int, >= 0 Returns: **lambda** `x`: ... that evaluates the `order`-th derivative of `B` at the point `x`. The returned function internally uses __call__, which is 'memoized' for speed.
[ "Differentiate", "a", "B", "-", "spline", "order", "number", "of", "times", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L225-L262
johntfoster/bspline
bspline/bspline.py
Bspline.collmat
def collmat(self, tau, deriv_order=0): """Compute collocation matrix. Parameters: tau: Python list or rank-1 array, collocation sites deriv_order: int, >=0, order of derivative for which to compute the collocation matrix. The default is 0, which means the function value itself. ...
python
def collmat(self, tau, deriv_order=0): """Compute collocation matrix. Parameters: tau: Python list or rank-1 array, collocation sites deriv_order: int, >=0, order of derivative for which to compute the collocation matrix. The default is 0, which means the function value itself. ...
[ "def", "collmat", "(", "self", ",", "tau", ",", "deriv_order", "=", "0", ")", ":", "# get number of basis functions and output dtype", "dummy", "=", "self", ".", "__call__", "(", "0.", ")", "nbasis", "=", "dummy", ".", "shape", "[", "0", "]", "tau", "=", ...
Compute collocation matrix. Parameters: tau: Python list or rank-1 array, collocation sites deriv_order: int, >=0, order of derivative for which to compute the collocation matrix. The default is 0, which means the function value itself. Returns: A: if len(tau) > 1, rank-2 a...
[ "Compute", "collocation", "matrix", "." ]
train
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L265-L309
disqus/disqus-python
disqusapi/utils.py
build_interfaces_by_method
def build_interfaces_by_method(interfaces): """ Create new dictionary from INTERFACES hashed by method then the endpoints name. For use when using the disqusapi by the method interface instead of the endpoint interface. For instance: 'blacklists': { 'add': { 'formats': ['jso...
python
def build_interfaces_by_method(interfaces): """ Create new dictionary from INTERFACES hashed by method then the endpoints name. For use when using the disqusapi by the method interface instead of the endpoint interface. For instance: 'blacklists': { 'add': { 'formats': ['jso...
[ "def", "build_interfaces_by_method", "(", "interfaces", ")", ":", "def", "traverse", "(", "block", ",", "parts", ")", ":", "try", ":", "method", "=", "block", "[", "'method'", "]", ".", "lower", "(", ")", "except", "KeyError", ":", "for", "k", ",", "v"...
Create new dictionary from INTERFACES hashed by method then the endpoints name. For use when using the disqusapi by the method interface instead of the endpoint interface. For instance: 'blacklists': { 'add': { 'formats': ['json', 'jsonp'], 'method': 'POST', ...
[ "Create", "new", "dictionary", "from", "INTERFACES", "hashed", "by", "method", "then", "the", "endpoints", "name", ".", "For", "use", "when", "using", "the", "disqusapi", "by", "the", "method", "interface", "instead", "of", "the", "endpoint", "interface", ".",...
train
https://github.com/disqus/disqus-python/blob/605f33c7b735fcb85e16041c27658fbba49d7a7b/disqusapi/utils.py#L8-L48
disqus/disqus-python
disqusapi/utils.py
get_normalized_request_string
def get_normalized_request_string(method, url, nonce, params, ext='', body_hash=None): """ Returns a normalized request string as described iN OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.3.1 """ urlparts = urlparse.urlparse(url) if urlparts.query: ...
python
def get_normalized_request_string(method, url, nonce, params, ext='', body_hash=None): """ Returns a normalized request string as described iN OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.3.1 """ urlparts = urlparse.urlparse(url) if urlparts.query: ...
[ "def", "get_normalized_request_string", "(", "method", ",", "url", ",", "nonce", ",", "params", ",", "ext", "=", "''", ",", "body_hash", "=", "None", ")", ":", "urlparts", "=", "urlparse", ".", "urlparse", "(", "url", ")", "if", "urlparts", ".", "query",...
Returns a normalized request string as described iN OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.3.1
[ "Returns", "a", "normalized", "request", "string", "as", "described", "iN", "OAuth2", "MAC", "spec", "." ]
train
https://github.com/disqus/disqus-python/blob/605f33c7b735fcb85e16041c27658fbba49d7a7b/disqusapi/utils.py#L59-L87
disqus/disqus-python
disqusapi/utils.py
get_body_hash
def get_body_hash(params): """ Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2 """ norm_params = get_normalized_params(params) return binascii.b2a_base64(hashlib.sha1(norm_params).digest())[:-1]
python
def get_body_hash(params): """ Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2 """ norm_params = get_normalized_params(params) return binascii.b2a_base64(hashlib.sha1(norm_params).digest())[:-1]
[ "def", "get_body_hash", "(", "params", ")", ":", "norm_params", "=", "get_normalized_params", "(", "params", ")", "return", "binascii", ".", "b2a_base64", "(", "hashlib", ".", "sha1", "(", "norm_params", ")", ".", "digest", "(", ")", ")", "[", ":", "-", ...
Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec. http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2
[ "Returns", "BASE64", "(", "HASH", "(", "text", ")", ")", "as", "described", "in", "OAuth2", "MAC", "spec", "." ]
train
https://github.com/disqus/disqus-python/blob/605f33c7b735fcb85e16041c27658fbba49d7a7b/disqusapi/utils.py#L90-L98
disqus/disqus-python
disqusapi/utils.py
get_mac_signature
def get_mac_signature(api_secret, norm_request_string): """ Returns HMAC-SHA1 (api secret, normalized request string) """ hashed = hmac.new(str(api_secret), norm_request_string, hashlib.sha1) return binascii.b2a_base64(hashed.digest())[:-1]
python
def get_mac_signature(api_secret, norm_request_string): """ Returns HMAC-SHA1 (api secret, normalized request string) """ hashed = hmac.new(str(api_secret), norm_request_string, hashlib.sha1) return binascii.b2a_base64(hashed.digest())[:-1]
[ "def", "get_mac_signature", "(", "api_secret", ",", "norm_request_string", ")", ":", "hashed", "=", "hmac", ".", "new", "(", "str", "(", "api_secret", ")", ",", "norm_request_string", ",", "hashlib", ".", "sha1", ")", "return", "binascii", ".", "b2a_base64", ...
Returns HMAC-SHA1 (api secret, normalized request string)
[ "Returns", "HMAC", "-", "SHA1", "(", "api", "secret", "normalized", "request", "string", ")" ]
train
https://github.com/disqus/disqus-python/blob/605f33c7b735fcb85e16041c27658fbba49d7a7b/disqusapi/utils.py#L101-L106
codesardine/Jade-Application-Kit
j/Api.py
Fs.open_file
def open_file(self, access_mode="r"): """ input: filename and path. output: file contents. """ try: with open(self, access_mode, encoding='utf-8') as file: return file.read() except IOError: print(self + " File not found."...
python
def open_file(self, access_mode="r"): """ input: filename and path. output: file contents. """ try: with open(self, access_mode, encoding='utf-8') as file: return file.read() except IOError: print(self + " File not found."...
[ "def", "open_file", "(", "self", ",", "access_mode", "=", "\"r\"", ")", ":", "try", ":", "with", "open", "(", "self", ",", "access_mode", ",", "encoding", "=", "'utf-8'", ")", "as", "file", ":", "return", "file", ".", "read", "(", ")", "except", "IOE...
input: filename and path. output: file contents.
[ "input", ":", "filename", "and", "path", ".", "output", ":", "file", "contents", "." ]
train
https://github.com/codesardine/Jade-Application-Kit/blob/f94ba061f1e71c812f23ef4297473a5fce712367/j/Api.py#L8-L19
bhmm/bhmm
bhmm/estimators/maximum_likelihood.py
MaximumLikelihoodEstimator._forward_backward
def _forward_backward(self, itraj): """ Estimation step: Runs the forward-back algorithm on trajectory with index itraj Parameters ---------- itraj : int index of the observation trajectory to process Results ------- logprob : float ...
python
def _forward_backward(self, itraj): """ Estimation step: Runs the forward-back algorithm on trajectory with index itraj Parameters ---------- itraj : int index of the observation trajectory to process Results ------- logprob : float ...
[ "def", "_forward_backward", "(", "self", ",", "itraj", ")", ":", "# get parameters", "A", "=", "self", ".", "_hmm", ".", "transition_matrix", "pi", "=", "self", ".", "_hmm", ".", "initial_distribution", "obs", "=", "self", ".", "_observations", "[", "itraj",...
Estimation step: Runs the forward-back algorithm on trajectory with index itraj Parameters ---------- itraj : int index of the observation trajectory to process Results ------- logprob : float The probability to observe the observation sequence g...
[ "Estimation", "step", ":", "Runs", "the", "forward", "-", "back", "algorithm", "on", "trajectory", "with", "index", "itraj" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/maximum_likelihood.py#L221-L269
bhmm/bhmm
bhmm/estimators/maximum_likelihood.py
MaximumLikelihoodEstimator._update_model
def _update_model(self, gammas, count_matrices, maxiter=10000000): """ Maximization step: Updates the HMM model given the hidden state assignment and count matrices Parameters ---------- gamma : [ ndarray(T,N, dtype=float) ] list of state probabilities for each traje...
python
def _update_model(self, gammas, count_matrices, maxiter=10000000): """ Maximization step: Updates the HMM model given the hidden state assignment and count matrices Parameters ---------- gamma : [ ndarray(T,N, dtype=float) ] list of state probabilities for each traje...
[ "def", "_update_model", "(", "self", ",", "gammas", ",", "count_matrices", ",", "maxiter", "=", "10000000", ")", ":", "gamma0_sum", "=", "self", ".", "_init_counts", "(", "gammas", ")", "C", "=", "self", ".", "_transition_counts", "(", "count_matrices", ")",...
Maximization step: Updates the HMM model given the hidden state assignment and count matrices Parameters ---------- gamma : [ ndarray(T,N, dtype=float) ] list of state probabilities for each trajectory count_matrix : [ ndarray(N,N, dtype=float) ] list of the Baum...
[ "Maximization", "step", ":", "Updates", "the", "HMM", "model", "given", "the", "hidden", "state", "assignment", "and", "count", "matrices" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/maximum_likelihood.py#L284-L330
bhmm/bhmm
bhmm/estimators/maximum_likelihood.py
MaximumLikelihoodEstimator.compute_viterbi_paths
def compute_viterbi_paths(self): """ Computes the viterbi paths using the current HMM model """ # get parameters K = len(self._observations) A = self._hmm.transition_matrix pi = self._hmm.initial_distribution # compute viterbi path for each trajectory ...
python
def compute_viterbi_paths(self): """ Computes the viterbi paths using the current HMM model """ # get parameters K = len(self._observations) A = self._hmm.transition_matrix pi = self._hmm.initial_distribution # compute viterbi path for each trajectory ...
[ "def", "compute_viterbi_paths", "(", "self", ")", ":", "# get parameters", "K", "=", "len", "(", "self", ".", "_observations", ")", "A", "=", "self", ".", "_hmm", ".", "transition_matrix", "pi", "=", "self", ".", "_hmm", ".", "initial_distribution", "# compu...
Computes the viterbi paths using the current HMM model
[ "Computes", "the", "viterbi", "paths", "using", "the", "current", "HMM", "model" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/maximum_likelihood.py#L332-L352
bhmm/bhmm
bhmm/estimators/maximum_likelihood.py
MaximumLikelihoodEstimator.fit
def fit(self): """ Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm Returns ------- model : HMM The maximum likelihood HMM model. """ logger().info("=================================================================") lo...
python
def fit(self): """ Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm Returns ------- model : HMM The maximum likelihood HMM model. """ logger().info("=================================================================") lo...
[ "def", "fit", "(", "self", ")", ":", "logger", "(", ")", ".", "info", "(", "\"=================================================================\"", ")", "logger", "(", ")", ".", "info", "(", "\"Running Baum-Welch:\"", ")", "logger", "(", ")", ".", "info", "(", ...
Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm Returns ------- model : HMM The maximum likelihood HMM model.
[ "Maximum", "-", "likelihood", "estimation", "of", "the", "HMM", "using", "the", "Baum", "-", "Welch", "algorithm" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/maximum_likelihood.py#L354-L446
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
sample_gaussian
def sample_gaussian(mean, covar, covariance_type='diag', n_samples=1, random_state=None): """Generate random samples from a Gaussian distribution. Parameters ---------- mean : array_like, shape (n_features,) Mean of the distribution. covar : array_like, optional ...
python
def sample_gaussian(mean, covar, covariance_type='diag', n_samples=1, random_state=None): """Generate random samples from a Gaussian distribution. Parameters ---------- mean : array_like, shape (n_features,) Mean of the distribution. covar : array_like, optional ...
[ "def", "sample_gaussian", "(", "mean", ",", "covar", ",", "covariance_type", "=", "'diag'", ",", "n_samples", "=", "1", ",", "random_state", "=", "None", ")", ":", "rng", "=", "check_random_state", "(", "random_state", ")", "n_dim", "=", "len", "(", "mean"...
Generate random samples from a Gaussian distribution. Parameters ---------- mean : array_like, shape (n_features,) Mean of the distribution. covar : array_like, optional Covariance of the distribution. The shape depends on `covariance_type`: scalar if 'spherical', ...
[ "Generate", "random", "samples", "from", "a", "Gaussian", "distribution", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L63-L107
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
_covar_mstep_diag
def _covar_mstep_diag(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): """Performing the covariance M step for diagonal cases""" avg_X2 = np.dot(responsibilities.T, X * X) * norm avg_means2 = gmm.means_ ** 2 avg_X_means = gmm.means_ * weighted_X_sum * norm return avg...
python
def _covar_mstep_diag(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): """Performing the covariance M step for diagonal cases""" avg_X2 = np.dot(responsibilities.T, X * X) * norm avg_means2 = gmm.means_ ** 2 avg_X_means = gmm.means_ * weighted_X_sum * norm return avg...
[ "def", "_covar_mstep_diag", "(", "gmm", ",", "X", ",", "responsibilities", ",", "weighted_X_sum", ",", "norm", ",", "min_covar", ")", ":", "avg_X2", "=", "np", ".", "dot", "(", "responsibilities", ".", "T", ",", "X", "*", "X", ")", "*", "norm", "avg_me...
Performing the covariance M step for diagonal cases
[ "Performing", "the", "covariance", "M", "step", "for", "diagonal", "cases" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L684-L690
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
_covar_mstep_spherical
def _covar_mstep_spherical(*args): """Performing the covariance M step for spherical cases""" cv = _covar_mstep_diag(*args) return np.tile(cv.mean(axis=1)[:, np.newaxis], (1, cv.shape[1]))
python
def _covar_mstep_spherical(*args): """Performing the covariance M step for spherical cases""" cv = _covar_mstep_diag(*args) return np.tile(cv.mean(axis=1)[:, np.newaxis], (1, cv.shape[1]))
[ "def", "_covar_mstep_spherical", "(", "*", "args", ")", ":", "cv", "=", "_covar_mstep_diag", "(", "*", "args", ")", "return", "np", ".", "tile", "(", "cv", ".", "mean", "(", "axis", "=", "1", ")", "[", ":", ",", "np", ".", "newaxis", "]", ",", "(...
Performing the covariance M step for spherical cases
[ "Performing", "the", "covariance", "M", "step", "for", "spherical", "cases" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L693-L696
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
_covar_mstep_full
def _covar_mstep_full(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): """Performing the covariance M step for full cases""" # Eq. 12 from K. Murphy, "Fitting a Conditional Linear Gaussian # Distribution" n_features = X.shape[1] cv = np.empty((gmm.n_components, n_fea...
python
def _covar_mstep_full(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): """Performing the covariance M step for full cases""" # Eq. 12 from K. Murphy, "Fitting a Conditional Linear Gaussian # Distribution" n_features = X.shape[1] cv = np.empty((gmm.n_components, n_fea...
[ "def", "_covar_mstep_full", "(", "gmm", ",", "X", ",", "responsibilities", ",", "weighted_X_sum", ",", "norm", ",", "min_covar", ")", ":", "# Eq. 12 from K. Murphy, \"Fitting a Conditional Linear Gaussian", "# Distribution\"", "n_features", "=", "X", ".", "shape", "[", ...
Performing the covariance M step for full cases
[ "Performing", "the", "covariance", "M", "step", "for", "full", "cases" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L699-L714
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM._get_covars
def _get_covars(self): """Covariance parameters for each mixture component. The shape depends on `cvtype`:: (`n_states`, 'n_features') if 'spherical', (`n_features`, `n_features`) if 'tied', (`n_states`, `n_features`) if 'di...
python
def _get_covars(self): """Covariance parameters for each mixture component. The shape depends on `cvtype`:: (`n_states`, 'n_features') if 'spherical', (`n_features`, `n_features`) if 'tied', (`n_states`, `n_features`) if 'di...
[ "def", "_get_covars", "(", "self", ")", ":", "if", "self", ".", "covariance_type", "==", "'full'", ":", "return", "self", ".", "covars_", "elif", "self", ".", "covariance_type", "==", "'diag'", ":", "return", "[", "np", ".", "diag", "(", "cov", ")", "f...
Covariance parameters for each mixture component. The shape depends on `cvtype`:: (`n_states`, 'n_features') if 'spherical', (`n_features`, `n_features`) if 'tied', (`n_states`, `n_features`) if 'diag', (`n_states`, `n_f...
[ "Covariance", "parameters", "for", "each", "mixture", "component", ".", "The", "shape", "depends", "on", "cvtype", "::" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L261-L277
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM._set_covars
def _set_covars(self, covars): """Provide values for covariance""" covars = np.asarray(covars) _validate_covars(covars, self.covariance_type, self.n_components) self.covars_ = covars
python
def _set_covars(self, covars): """Provide values for covariance""" covars = np.asarray(covars) _validate_covars(covars, self.covariance_type, self.n_components) self.covars_ = covars
[ "def", "_set_covars", "(", "self", ",", "covars", ")", ":", "covars", "=", "np", ".", "asarray", "(", "covars", ")", "_validate_covars", "(", "covars", ",", "self", ".", "covariance_type", ",", "self", ".", "n_components", ")", "self", ".", "covars_", "=...
Provide values for covariance
[ "Provide", "values", "for", "covariance" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L279-L283
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.score_samples
def score_samples(self, X): """Return the per-sample likelihood of the data under the model. Compute the log probability of X under the model and return the posterior distribution (responsibilities) of each mixture component for each element of X. Parameters ---------- ...
python
def score_samples(self, X): """Return the per-sample likelihood of the data under the model. Compute the log probability of X under the model and return the posterior distribution (responsibilities) of each mixture component for each element of X. Parameters ---------- ...
[ "def", "score_samples", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "'means_'", ")", "X", "=", "check_array", "(", "X", ")", "if", "X", ".", "ndim", "==", "1", ":", "X", "=", "X", "[", ":", ",", "np", ".", "newaxis", "...
Return the per-sample likelihood of the data under the model. Compute the log probability of X under the model and return the posterior distribution (responsibilities) of each mixture component for each element of X. Parameters ---------- X: array_like, shape (n_samples...
[ "Return", "the", "per", "-", "sample", "likelihood", "of", "the", "data", "under", "the", "model", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L285-L322
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.score
def score(self, X, y=None): """Compute the log probability under the model. Parameters ---------- X : array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ----...
python
def score(self, X, y=None): """Compute the log probability under the model. Parameters ---------- X : array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ----...
[ "def", "score", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "logprob", ",", "_", "=", "self", ".", "score_samples", "(", "X", ")", "return", "logprob" ]
Compute the log probability under the model. Parameters ---------- X : array_like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- logprob : array_like, shape...
[ "Compute", "the", "log", "probability", "under", "the", "model", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L324-L339