_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q5400
get_thread_block_dimensions
train
def get_thread_block_dimensions(params, block_size_names=None): """thread block size from tuning params, currently using convention""" if not block_size_names: block_size_names = default_block_size_names block_size_x = params.get(block_size_names[0], 256) block_size_y = params.get(block_size_na...
python
{ "resource": "" }
q5401
looks_like_a_filename
train
def looks_like_a_filename(kernel_source): """ attempt to detect whether source code or a filename was passed """ logging.debug('looks_like_a_filename called') result = False if isinstance(kernel_source, str): result = True #test if not too long if len(kernel_source) > 250: ...
python
{ "resource": "" }
q5402
prepare_kernel_string
train
def prepare_kernel_string(kernel_name, kernel_string, params, grid, threads, block_size_names): """ prepare kernel string for compilation Prepends the kernel with a series of C preprocessor defines specific to this kernel instance: * the thread block dimensions * the grid dimensions * tunab...
python
{ "resource": "" }
q5403
prepare_list_of_files
train
def prepare_list_of_files(kernel_name, kernel_file_list, params, grid, threads, block_size_names): """ prepare the kernel string along with any additional files The first file in the list is allowed to include or read in the others The files beyond the first are considered additional files that may also co...
python
{ "resource": "" }
q5404
read_file
train
def read_file(filename): """ return the contents of the file named filename or None if file not found """ if os.path.isfile(filename): with open(filename, 'r') as f: return f.read()
python
{ "resource": "" }
q5405
replace_param_occurrences
train
def replace_param_occurrences(string, params): """replace occurrences of the tuning params with their current value""" for k, v in params.items(): string = string.replace(k, str(v)) return string
python
{ "resource": "" }
q5406
setup_block_and_grid
train
def setup_block_and_grid(problem_size, grid_div, params, block_size_names=None): """compute problem size, thread block and grid dimensions for this kernel""" threads = get_thread_block_dimensions(params, block_size_names) current_problem_size = get_problem_size(problem_size, params) grid = get_grid_dime...
python
{ "resource": "" }
q5407
write_file
train
def write_file(filename, string): """dump the contents of string to a file called filename""" import sys #ugly fix, hopefully we can find a better one if sys.version_info[0] >= 3: with open(filename, 'w', encoding="utf-8") as f: f.write(string) else: with open(filename, '...
python
{ "resource": "" }
q5408
OpenCLFunctions.compile
train
def compile(self, kernel_name, kernel_string): """call the OpenCL compiler to compile the kernel, return the device function :param kernel_name: The name of the kernel to be compiled, used to lookup the function after compilation. :type kernel_name: string :param kernel_str...
python
{ "resource": "" }
q5409
OpenCLFunctions.run_kernel
train
def run_kernel(self, func, gpu_args, threads, grid): """runs the OpenCL kernel passed as 'func' :param func: An OpenCL Kernel :type func: pyopencl.Kernel :param gpu_args: A list of arguments to the kernel, order should match the order in the code. Allowed values are either ...
python
{ "resource": "" }
q5410
weighted_choice
train
def weighted_choice(population): """Randomly select, fitness determines probability of being selected""" random_number = random.betavariate(1, 2.5) #increased probability of selecting members early in the list #random_number = random.random() ind = int(random_number*len(population)) ind = min(max(in...
python
{ "resource": "" }
q5411
random_population
train
def random_population(dna_size, pop_size, tune_params): """create a random population""" population = [] for _ in range(pop_size): dna = [] for i in range(dna_size): dna.append(random_val(i, tune_params)) population.append(dna) return population
python
{ "resource": "" }
q5412
random_val
train
def random_val(index, tune_params): """return a random value for a parameter""" key = list(tune_params.keys())[index] return random.choice(tune_params[key])
python
{ "resource": "" }
q5413
crossover
train
def crossover(dna1, dna2): """crossover dna1 and dna2 at a random index""" pos = int(random.random()*len(dna1)) if random.random() < 0.5: return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:]) else: return (dna2[:pos]+dna1[pos:], dna1[:pos]+dna2[pos:])
python
{ "resource": "" }
q5414
_cost_func
train
def _cost_func(x, kernel_options, tuning_options, runner, results, cache): """ Cost function used by minimize """ error_time = 1e20 logging.debug('_cost_func called') logging.debug('x: ' + str(x)) x_key = ",".join([str(i) for i in x]) if x_key in cache: return cache[x_key] #snap v...
python
{ "resource": "" }
q5415
get_bounds
train
def get_bounds(tune_params): """ create a bounds array from the tunable parameters """ bounds = [] for values in tune_params.values(): sorted_values = numpy.sort(values) bounds.append((sorted_values[0], sorted_values[-1])) return bounds
python
{ "resource": "" }
q5416
setup_method_options
train
def setup_method_options(method, tuning_options): """ prepare method specific options """ kwargs = {} #pass size of parameter space as max iterations to methods that support it #it seems not all methods iterpret this value in the same manner maxiter = numpy.prod([len(v) for v in tuning_options.tune...
python
{ "resource": "" }
q5417
snap_to_nearest_config
train
def snap_to_nearest_config(x, tune_params): """helper func that for each param selects the closest actual value""" params = [] for i, k in enumerate(tune_params.keys()): values = numpy.array(tune_params[k]) idx = numpy.abs(values-x[i]).argmin() params.append(int(values[idx])) ret...
python
{ "resource": "" }
q5418
unscale_and_snap_to_nearest
train
def unscale_and_snap_to_nearest(x, tune_params, eps): """helper func that snaps a scaled variable to the nearest config""" x_u = [i for i in x] for i, v in enumerate(tune_params.values()): #create an evenly spaced linear space to map [0,1]-interval #to actual values, giving each value an equ...
python
{ "resource": "" }
q5419
SequentialRunner.run
train
def run(self, parameter_space, kernel_options, tuning_options): """ Iterate through the entire parameter space using a single Python process :param parameter_space: The parameter space as an iterable. :type parameter_space: iterable :param kernel_options: A dictionary with all options ...
python
{ "resource": "" }
q5420
allocate
train
def allocate(n, dtype=numpy.float32): """ allocate context-portable pinned host memory """ return drv.pagelocked_empty(int(n), dtype, order='C', mem_flags=drv.host_alloc_flags.PORTABLE)
python
{ "resource": "" }
q5421
CudaFunctions.compile
train
def compile(self, kernel_name, kernel_string): """call the CUDA compiler to compile the kernel, return the device function :param kernel_name: The name of the kernel to be compiled, used to lookup the function after compilation. :type kernel_name: string :param kernel_strin...
python
{ "resource": "" }
q5422
CudaFunctions.copy_constant_memory_args
train
def copy_constant_memory_args(self, cmem_args): """adds constant memory arguments to the most recently compiled module :param cmem_args: A dictionary containing the data to be passed to the device constant memory. The format to be used is as follows: A string key is used to name...
python
{ "resource": "" }
q5423
CudaFunctions.copy_texture_memory_args
train
def copy_texture_memory_args(self, texmem_args): """adds texture memory arguments to the most recently compiled module :param texmem_args: A dictionary containing the data to be passed to the device texture memory. TODO """ filter_mode_map = { 'point': drv.filter_mode.POIN...
python
{ "resource": "" }
q5424
CudaFunctions.run_kernel
train
def run_kernel(self, func, gpu_args, threads, grid): """runs the CUDA kernel passed as 'func' :param func: A PyCuda kernel compiled for this specific kernel configuration :type func: pycuda.driver.Function :param gpu_args: A list of arguments to the kernel, order should match the ...
python
{ "resource": "" }
q5425
CudaFunctions.memcpy_htod
train
def memcpy_htod(self, dest, src): """perform a host to device memory copy :param dest: A GPU memory allocation unit :type dest: pycuda.driver.DeviceAllocation :param src: A numpy array in host memory to store the data :type src: numpy.ndarray """ if isinstance(d...
python
{ "resource": "" }
q5426
acceptance_prob
train
def acceptance_prob(old_cost, new_cost, T): """annealing equation, with modifications to work towards a lower value""" #if start pos is not valid, always move if old_cost == 1e20: return 1.0 #if we have found a valid ps before, never move to nonvalid pos if new_cost == 1e20: return 0...
python
{ "resource": "" }
q5427
neighbor
train
def neighbor(pos, tune_params): """return a random neighbor of pos""" size = len(pos) pos_out = [] # random mutation # expected value is set that values all dimensions attempt to get mutated for i in range(size): key = list(tune_params.keys())[i] values = tune_params[key] ...
python
{ "resource": "" }
q5428
tune
train
def tune(runner, kernel_options, device_options, tuning_options): """ Tune all instances in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: kernel_tun...
python
{ "resource": "" }
q5429
CFunctions.ready_argument_list
train
def ready_argument_list(self, arguments): """ready argument list to be passed to the C function :param arguments: List of arguments to be passed to the C function. The order should match the argument list on the C function. Allowed values are numpy.ndarray, and/or numpy.int32, n...
python
{ "resource": "" }
q5430
CFunctions.compile
train
def compile(self, kernel_name, kernel_string): """call the C compiler to compile the kernel, return the function :param kernel_name: The name of the kernel to be compiled, used to lookup the function after compilation. :type kernel_name: string :param kernel_string: The C c...
python
{ "resource": "" }
q5431
CFunctions.benchmark
train
def benchmark(self, func, c_args, threads, grid, times): """runs the kernel repeatedly, returns averaged returned value The C function tuning is a little bit more flexible than direct CUDA or OpenCL kernel tuning. The C function needs to measure time, or some other quality metric you wi...
python
{ "resource": "" }
q5432
CFunctions.run_kernel
train
def run_kernel(self, func, c_args, threads, grid): """runs the kernel once, returns whatever the kernel returns :param func: A C function compiled for this specific configuration :type func: ctypes._FuncPtr :param c_args: A list of arguments to the function, order should match the ...
python
{ "resource": "" }
q5433
CFunctions.cleanup_lib
train
def cleanup_lib(self): """ unload the previously loaded shared library """ if not self.using_openmp: #this if statement is necessary because shared libraries that use #OpenMP will core dump when unloaded, this is a well-known issue with OpenMP logging.debug('unloading...
python
{ "resource": "" }
q5434
clock
train
def clock(rpc): """ This task runs forever and notifies all clients subscribed to 'clock' once a second. """ while True: yield from rpc.notify('clock', str(datetime.datetime.now())) yield from asyncio.sleep(1)
python
{ "resource": "" }
q5435
patch_db_connections
train
def patch_db_connections(): """ This wraps django.db.connections._connections with a TaskLocal object. The Django transactions are only thread-safe, using threading.local, and don't know about coroutines. """ global __already_patched if not __already_patched: from django.db import...
python
{ "resource": "" }
q5436
decode_msg
train
def decode_msg(raw_msg): """ Decodes jsonrpc 2.0 raw message objects into JsonRpcMsg objects. Examples: Request: { "jsonrpc": "2.0", "id": 1, "method": "subtract", "params": [42, 23] } Notification: ...
python
{ "resource": "" }
q5437
switch_schema
train
def switch_schema(task, kwargs, **kw): """ Switches schema of the task, before it has been run. """ # Lazily load needed functions, as they import django model functions which # in turn load modules that need settings to be loaded and we can't # guarantee this module was loaded when the settings were re...
python
{ "resource": "" }
q5438
restore_schema
train
def restore_schema(task, **kwargs): """ Switches the schema back to the one from before running the task. """ from .compat import get_public_schema_name schema_name = get_public_schema_name() include_public = True if hasattr(task, '_old_schema'): schema_name, include_public = task._old_sch...
python
{ "resource": "" }
q5439
node_link_data
train
def node_link_data(G, attrs=_attrs): """Return data in node-link format that is suitable for JSON serialization and use in Javascript documents. Parameters ---------- G : DyNetx graph attrs : dict A dictionary that contains three keys 'id', 'source' and 'target'. The correspon...
python
{ "resource": "" }
q5440
compact_timeslot
train
def compact_timeslot(sind_list): """ Test method. Compact all snapshots into a single one. :param sind_list: :return: """ tls = sorted(sind_list) conversion = {val: idx for idx, val in enumerate(tls)} return conversion
python
{ "resource": "" }
q5441
DynGraph.nodes_iter
train
def nodes_iter(self, t=None, data=False): """Return an iterator over the nodes with respect to a given temporal snapshot. Parameters ---------- t : snapshot id (default=None). If None the iterator returns all the nodes of the flattened graph. data : boolean, optional...
python
{ "resource": "" }
q5442
DynGraph.nodes
train
def nodes(self, t=None, data=False): """Return a list of the nodes in the graph at a given snapshot. Parameters ---------- t : snapshot id (default=None) If None the the method returns all the nodes of the flattened graph. data : boolean, optional (default=False) ...
python
{ "resource": "" }
q5443
DynGraph.add_interactions_from
train
def add_interactions_from(self, ebunch, t=None, e=None): """Add all the interaction in ebunch at time t. Parameters ---------- ebunch : container of interaction Each interaction given in the container will be added to the graph. The interaction must be given as a...
python
{ "resource": "" }
q5444
DynGraph.neighbors
train
def neighbors(self, n, t=None): """Return a list of the nodes connected to the node n at time t. Parameters ---------- n : node A node in the graph t : snapshot id (default=None) If None will be returned the neighbors of the node on the flattened graph. ...
python
{ "resource": "" }
q5445
DynGraph.neighbors_iter
train
def neighbors_iter(self, n, t=None): """Return an iterator over all neighbors of node n at time t. Parameters ---------- n : node A node in the graph t : snapshot id (default=None) If None will be returned an iterator over the neighbors of the node on the ...
python
{ "resource": "" }
q5446
DynGraph.degree
train
def degree(self, nbunch=None, t=None): """Return the degree of a node or nodes at time t. The node degree is the number of interaction adjacent to that node in a given time frame. Parameters ---------- nbunch : iterable container, optional (default=all nodes) A cont...
python
{ "resource": "" }
q5447
DynGraph.size
train
def size(self, t=None): """Return the number of edges at time t. Parameters ---------- t : snapshot id (default=None) If None will be returned the size of the flattened graph. Returns ------- nedges : int The number of edges See...
python
{ "resource": "" }
q5448
DynGraph.number_of_nodes
train
def number_of_nodes(self, t=None): """Return the number of nodes in the t snpashot of a dynamic graph. Parameters ---------- t : snapshot id (default=None) If None return the number of nodes in the flattened graph. Returns ------- nnodes : int ...
python
{ "resource": "" }
q5449
DynGraph.has_node
train
def has_node(self, n, t=None): """Return True if the graph, at time t, contains the node n. Parameters ---------- n : node t : snapshot id (default None) If None return the presence of the node in the flattened graph. Examples -------- >>...
python
{ "resource": "" }
q5450
DynGraph.to_directed
train
def to_directed(self): """Return a directed representation of the graph. Returns ------- G : DynDiGraph A dynamic directed graph with the same name, same nodes, and with each edge (u,v,data) replaced by two directed edges (u,v,data) and (v,u,data). ...
python
{ "resource": "" }
q5451
DynGraph.stream_interactions
train
def stream_interactions(self): """Generate a temporal ordered stream of interactions. Returns ------- nd_iter : an iterator The iterator returns a 4-tuples of (node, node, op, timestamp). Examples -------- >>> G = dn.DynGraph() >>> G.add_pat...
python
{ "resource": "" }
q5452
DynGraph.interactions_per_snapshots
train
def interactions_per_snapshots(self, t=None): """Return the number of interactions within snapshot t. Parameters ---------- t : snapshot id (default=None) If None will be returned total number of interactions across all snapshots Returns ------- nd...
python
{ "resource": "" }
q5453
DynDiGraph.in_interactions_iter
train
def in_interactions_iter(self, nbunch=None, t=None): """Return an iterator over the in interactions present in a given snapshot. Edges are returned as tuples in the order (node, neighbor). Parameters ---------- nbunch : iterable container, optional (default= all nodes) ...
python
{ "resource": "" }
q5454
DynDiGraph.out_interactions_iter
train
def out_interactions_iter(self, nbunch=None, t=None): """Return an iterator over the out interactions present in a given snapshot. Edges are returned as tuples in the order (node, neighbor). Parameters ---------- nbunch : iterable container, optional (default= all nodes...
python
{ "resource": "" }
q5455
DynDiGraph.number_of_interactions
train
def number_of_interactions(self, u=None, v=None, t=None): """Return the number of interaction between two nodes at time t. Parameters ---------- u, v : nodes, optional (default=all interaction) If u and v are specified, return the number of interaction between u ...
python
{ "resource": "" }
q5456
DynDiGraph.in_degree
train
def in_degree(self, nbunch=None, t=None): """Return the in degree of a node or nodes at time t. The node in degree is the number of incoming interaction to that node in a given time frame. Parameters ---------- nbunch : iterable container, optional (default=all nodes) ...
python
{ "resource": "" }
q5457
DynDiGraph.out_degree
train
def out_degree(self, nbunch=None, t=None): """Return the out degree of a node or nodes at time t. The node degree is the number of interaction outgoing from that node in a given time frame. Parameters ---------- nbunch : iterable container, optional (default=all nodes) ...
python
{ "resource": "" }
q5458
DynDiGraph.to_undirected
train
def to_undirected(self, reciprocal=False): """Return an undirected representation of the dyndigraph. Parameters ---------- reciprocal : bool (optional) If True only keep edges that appear in both directions in the original dyndigraph. Returns -------...
python
{ "resource": "" }
q5459
write_interactions
train
def write_interactions(G, path, delimiter=' ', encoding='utf-8'): """Write a DyNetx graph in interaction list format. Parameters ---------- G : graph A DyNetx graph. path : basestring The desired output filename delimiter : character ...
python
{ "resource": "" }
q5460
read_interactions
train
def read_interactions(path, comments="#", directed=False, delimiter=None, nodetype=None, timestamptype=None, encoding='utf-8', keys=False): """Read a DyNetx graph from interaction list format. Parameters ---------- path : basestring The desired output filenam...
python
{ "resource": "" }
q5461
write_snapshots
train
def write_snapshots(G, path, delimiter=' ', encoding='utf-8'): """Write a DyNetx graph in snapshot graph list format. Parameters ---------- G : graph A DyNetx graph. path : basestring The desired output filename delimiter : character C...
python
{ "resource": "" }
q5462
read_snapshots
train
def read_snapshots(path, comments="#", directed=False, delimiter=None, nodetype=None, timestamptype=None, encoding='utf-8', keys=False): """Read a DyNetx graph from snapshot graph list format. Parameters ---------- path : basestring The desired output filena...
python
{ "resource": "" }
q5463
open_file
train
def open_file(path_arg, mode='r'): """Decorator to ensure clean opening and closing of files. Parameters ---------- path_arg : int Location of the path argument in args. Even if the argument is a named positional argument (with a default value), you must specify its index as a ...
python
{ "resource": "" }
q5464
number_of_interactions
train
def number_of_interactions(G, u=None, v=None, t=None): """Return the number of edges between two nodes at time t. Parameters ---------- u, v : nodes, optional (default=all edges) If u and v are specified, return the number of edges between u and v. Otherwise return t...
python
{ "resource": "" }
q5465
density
train
def density(G, t=None): r"""Return the density of a graph at timestamp t. The density for undirected graphs is .. math:: d = \frac{2m}{n(n-1)}, and for directed graphs is .. math:: d = \frac{m}{n(n-1)}, where `n` is the number of nodes and `m` is th...
python
{ "resource": "" }
q5466
degree_histogram
train
def degree_histogram(G, t=None): """Return a list of the frequency of each degree value. Parameters ---------- G : Graph opject DyNetx graph object t : snapshot id (default=None) snapshot id Returns ------- hist : list ...
python
{ "resource": "" }
q5467
freeze
train
def freeze(G): """Modify graph to prevent further change by adding or removing nodes or edges. Node and edge data can still be modified. Parameters ---------- G : graph A NetworkX graph Notes ----- To "unfreeze" a graph you must make a...
python
{ "resource": "" }
q5468
set_node_attributes
train
def set_node_attributes(G, values, name=None): """Set node attributes from dictionary of nodes and values Parameters ---------- G : DyNetx Graph name : string Attribute name values: dict Dictionary of attribute values keyed by node. If `values` is not...
python
{ "resource": "" }
q5469
get_node_attributes
train
def get_node_attributes(G, name): """Get node attributes from graph Parameters ---------- G : DyNetx Graph name : string Attribute name Returns ------- Dictionary of attributes keyed by node. """ return {n: d[name] for n, d in G.node.item...
python
{ "resource": "" }
q5470
all_neighbors
train
def all_neighbors(graph, node, t=None): """ Returns all of the neighbors of a node in the graph at time t. If the graph is directed returns predecessors as well as successors. Parameters ---------- graph : DyNetx graph Graph to find neighbors. node : node ...
python
{ "resource": "" }
q5471
non_neighbors
train
def non_neighbors(graph, node, t=None): """Returns the non-neighbors of the node in the graph at time t. Parameters ---------- graph : DyNetx graph Graph to find neighbors. node : node The node whose neighbors will be returned. t : snapshot id (defa...
python
{ "resource": "" }
q5472
non_interactions
train
def non_interactions(graph, t=None): """Returns the non-existent edges in the graph at time t. Parameters ---------- graph : NetworkX graph. Graph to find non-existent edges. t : snapshot id (default=None) If None the non-existent edges are identified on th...
python
{ "resource": "" }
q5473
FunctionTimedOut.getMsg
train
def getMsg(self): ''' getMsg - Generate a default message based on parameters to FunctionTimedOut exception' @return <str> - Message ''' return 'Function %s (args=%s) (kwargs=%s) timed out after %f seconds.\n' %(self.timedOutFunction.__name__, repr(self.timedOutArgs), re...
python
{ "resource": "" }
q5474
FunctionTimedOut.retry
train
def retry(self, timeout=RETRY_SAME_TIMEOUT): ''' retry - Retry the timed-out function with same arguments. @param timeout <float/RETRY_SAME_TIMEOUT/None> Default RETRY_SAME_TIMEOUT If RETRY_SAME_TIMEOUT : Will retry the function same args, same timeout ...
python
{ "resource": "" }
q5475
JoinThread.run
train
def run(self): ''' run - The thread main. Will attempt to stop and join the attached thread. ''' # Try to silence default exception printing. self.otherThread._Thread__stderr = self._stderr if hasattr(self.otherThread, '_Thread__stop'): # If py2, call thi...
python
{ "resource": "" }
q5476
PDFIntegrator._make_map
train
def _make_map(self, limit): """ Make vegas grid that is adapted to the pdf. """ ny = 2000 y = numpy.random.uniform(0., 1., (ny,1)) limit = numpy.arctan(limit) m = AdaptiveMap([[-limit, limit]], ninc=100) theta = numpy.empty(y.shape, float) jac = numpy.empty(y.shap...
python
{ "resource": "" }
q5477
PDFIntegrator._expval
train
def _expval(self, f, nopdf): """ Return integrand using the tan mapping. """ def ff(theta, nopdf=nopdf): tan_theta = numpy.tan(theta) x = self.scale * tan_theta jac = self.scale * (tan_theta ** 2 + 1.) if nopdf: pdf = jac * self.pdf.pjac[No...
python
{ "resource": "" }
q5478
REPL.dump
train
def dump(self, function_name): """ Pretty-dump the bytecode for the function with the given name. """ assert isinstance(function_name, str) self.stdout.write(function_name) self.stdout.write("\n") self.stdout.write("-" * len(function_name)) self.stdout.w...
python
{ "resource": "" }
q5479
Command.handle
train
def handle(self, **options): """Call "startapp" to generate app with custom user model.""" template = os.path.dirname(os.path.abspath(__file__)) + "/app_template" name = options.pop("name") call_command("startapp", name, template=template, **options)
python
{ "resource": "" }
q5480
BaseUserManager._create_user
train
def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) us...
python
{ "resource": "" }
q5481
nwise
train
def nwise(iterable, n): """ Iterate through a sequence with a defined length window >>> list(nwise(range(8), 3)) [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (5, 6, 7)] >>> list(nwise(range(3), 5)) [] Parameters ---------- iterable n : length of each sequence Yields ...
python
{ "resource": "" }
q5482
step
train
def step(g, n1, n2, inbound=False, backward=False, continue_fn=None): """ Step along a path through a directed graph unless there is an intersection Example graph: Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and (3, 2) are also edges 1 -- 2 -- 3 -->-- 5 -->-- 7 ...
python
{ "resource": "" }
q5483
move
train
def move(g, n1, n2, **kwargs): """ Step along a graph until it ends or reach an intersection Example graph: Note that edge (1, 2) and (2, 3) are bidirectional, i.e., (2, 1) and (3, 2) are also edges 1 -- 2 -- 3 -->-- 5 -->-- 7 | | ^ v | ...
python
{ "resource": "" }
q5484
is_intersection
train
def is_intersection(g, n): """ Determine if a node is an intersection graph: 1 -->-- 2 -->-- 3 >>> is_intersection(g, 2) False graph: 1 -- 2 -- 3 | 4 >>> is_intersection(g, 2) True Parameters ---------- g : networkx DiGraph n : node id R...
python
{ "resource": "" }
q5485
LazyModel.as_dict
train
def as_dict(self): """ Returns the model as a dict """ if not self._is_valid: self.validate() from .converters import to_dict return to_dict(self)
python
{ "resource": "" }
q5486
GraphImporter.coords_callback
train
def coords_callback(self, data): """ Callback for nodes that have no tags """ for node_id, lon, lat in data: self.coords[node_id] = (lon, lat)
python
{ "resource": "" }
q5487
GraphImporter.nodes_callback
train
def nodes_callback(self, data): """ Callback for nodes with tags """ for node_id, tags, coords in data: # Discard the coords because they go into add_coords self.nodes[node_id] = tags
python
{ "resource": "" }
q5488
GraphImporter.ways_callback
train
def ways_callback(self, data): """ Callback for all ways """ for way_id, tags, nodes in data: # Imposm passes all ways through regardless of whether the tags # have been filtered or not. It needs to do this in order to # handle relations, but we don't care about relat...
python
{ "resource": "" }
q5489
GraphImporter.get_graph
train
def get_graph(self, parse_direction=False): """ Return the networkx directed graph of received data """ g = nx.DiGraph() for way_id, (tags, nodes) in self.ways.items(): # If oneway is '-1', reverse the way and treat as a normal oneway if tags.get('oneway') == '-1': ...
python
{ "resource": "" }
q5490
parse_file
train
def parse_file(filename, parse_direction=False, **kwargs): """ Return an OSM networkx graph from the input OSM file Only works with OSM xml, xml.bz2 and pbf files. This function cannot take OSM QA tile files. Use parse_qa_tile() for QA tiles. >>> graph = parse_file(filename) """ importer,...
python
{ "resource": "" }
q5491
parse_data
train
def parse_data(data, type, **kwargs): """ Return an OSM networkx graph from the input OSM data Parameters ---------- data : string type : string ('xml' or 'pbf') >>> graph = parse_data(data, 'xml') """ suffixes = { 'xml': '.osm', 'pbf': '.pbf', } try: ...
python
{ "resource": "" }
q5492
parse_qa_tile
train
def parse_qa_tile(x, y, zoom, data, parse_direction=False, **kwargs): """ Return an OSM networkx graph from the input OSM QA tile data Parameters ---------- data : string x : int tile's x coordinate y : int tile's y coordinate zoom : int tile's zoom level >>...
python
{ "resource": "" }
q5493
_basename
train
def _basename(fname): """Return file name without path.""" if not isinstance(fname, Path): fname = Path(fname) path, name, ext = fname.parent, fname.stem, fname.suffix return path, name, ext
python
{ "resource": "" }
q5494
from_btl
train
def from_btl(fname): """ DataFrame constructor to open Seabird CTD BTL-ASCII format. Examples -------- >>> from pathlib import Path >>> import ctd >>> data_path = Path(__file__).parents[1].joinpath("tests", "data") >>> bottles = ctd.from_btl(data_path.joinpath('btl', 'bottletest.btl')) ...
python
{ "resource": "" }
q5495
from_edf
train
def from_edf(fname): """ DataFrame constructor to open XBT EDF ASCII format. Examples -------- >>> from pathlib import Path >>> import ctd >>> data_path = Path(__file__).parents[1].joinpath("tests", "data") >>> cast = ctd.from_edf(data_path.joinpath('XBT.EDF.gz')) >>> ax = cast['tem...
python
{ "resource": "" }
q5496
from_cnv
train
def from_cnv(fname): """ DataFrame constructor to open Seabird CTD CNV-ASCII format. Examples -------- >>> from pathlib import Path >>> import ctd >>> data_path = Path(__file__).parents[1].joinpath("tests", "data") >>> cast = ctd.from_cnv(data_path.joinpath('CTD_big.cnv.bz2')) >>> d...
python
{ "resource": "" }
q5497
extrap_sec
train
def extrap_sec(data, dist, depth, w1=1.0, w2=0): """ Extrapolates `data` to zones where the shallow stations are shadowed by the deep stations. The shadow region usually cannot be extrapolates via linear interpolation. The extrapolation is applied using the gradients of the `data` at a certain ...
python
{ "resource": "" }
q5498
gen_topomask
train
def gen_topomask(h, lon, lat, dx=1.0, kind="linear", plot=False): """ Generates a topography mask from an oceanographic transect taking the deepest CTD scan as the depth of each station. Inputs ------ h : array Pressure of the deepest CTD scan for each station [dbar]. lons : array ...
python
{ "resource": "" }
q5499
plot_cast
train
def plot_cast(df, secondary_y=False, label=None, *args, **kwargs): """ Plot a CTD variable with the index in the y-axis instead of x-axis. """ ax = kwargs.pop("ax", None) fignums = plt.get_fignums() if ax is None and not fignums: ax = plt.axes() fig = ax.get_figure() fi...
python
{ "resource": "" }