desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Remove all nodes and edges from the graph. This also removes the name, and all graph, node, and edge attributes. Examples >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.clear() >>> list(G.nodes()) >>> list(G.edges())'
def clear(self):
self.name = '' self._adj.clear() self._node.clear() self.graph.clear()
'Return a copy of the graph. All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four types of copies of a graph that people might want. Deepcopy -- The default behavior is a "deepcopy" where the graph structure as well as all data attributes and any objects they mi...
def copy(self, with_data=True):
if with_data: return deepcopy(self) return self.subgraph(self)
'Return True if graph is a multigraph, False otherwise.'
def is_multigraph(self):
return False
'Return True if graph is directed, False otherwise.'
def is_directed(self):
return False
'Return a directed representation of the graph. Returns G : DiGraph A 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). Notes This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all...
def to_directed(self):
from networkx import DiGraph G = DiGraph() G.name = self.name G.add_nodes_from(self) G.add_edges_from(((u, v, deepcopy(data)) for (u, nbrs) in self.adjacency() for (v, data) in nbrs.items())) G.graph = deepcopy(self.graph) G._node = deepcopy(self._node) return G
'Return an undirected copy of the graph. Returns G : Graph/MultiGraph A deepcopy of the graph. See Also copy, add_edge, add_edges_from Notes This returns a "deepcopy" of the edge, node, and graph attributes which attempts to completely copy all of the data and references. This is in contrast to the similar `G = nx.DiGr...
def to_undirected(self):
return deepcopy(self)
'Return the subgraph induced on nodes in nbunch. The induced subgraph of the graph contains the nodes in nbunch and the edges between those nodes. Parameters nbunch : list, iterable A container of nodes which will be iterated through once. Returns G : Graph A subgraph of the graph with the same edge attributes. Notes T...
def subgraph(self, nbunch):
bunch = self.nbunch_iter(nbunch) H = self.__class__() for n in bunch: H._node[n] = self._node[n] H_adj = H._adj self_adj = self._adj for n in H._node: Hnbrs = H.adjlist_inner_dict_factory() H_adj[n] = Hnbrs for (nbr, d) in self_adj[n].items(): if (nbr ...
'Returns the subgraph induced by the specified edges. The induced subgraph contains each edge in `edges` and each node incident to any one of those edges. Parameters edges : iterable An iterable of edges in this graph. Returns G : Graph An edge-induced subgraph of this graph with the same edge attributes. Notes The gra...
def edge_subgraph(self, edges):
H = self.__class__() adj = self._adj edges = ((u, v) for (u, v) in edges if ((u in adj) and (v in adj[u]))) for (u, v) in edges: if (u not in H._node): H._node[u] = self._node[u] if (v not in H._node): H._node[v] = self._node[v] if (u not in H._adj): ...
'Returns an iterator over nodes with self loops. A node with a self loop has an edge with both ends adjacent to that node. Returns nodelist : iterator A iterator over nodes with self loops. See Also selfloop_edges, number_of_selfloops Examples >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_e...
def nodes_with_selfloops(self):
return (n for (n, nbrs) in self._adj.items() if (n in nbrs))
'Returns an iterator over selfloop edges. A selfloop edge has the same node at both ends. Parameters data : string or bool, optional (default=False) Return selfloop edges as two tuples (u, v) (data=False) or three-tuples (u, v, datadict) (data=True) or three-tuples (u, v, datavalue) (data=\'attrname\') default : value,...
def selfloop_edges(self, data=False, default=None):
if (data is True): return ((n, n, nbrs[n]) for (n, nbrs) in self._adj.items() if (n in nbrs)) elif (data is not False): return ((n, n, nbrs[n].get(data, default)) for (n, nbrs) in self._adj.items() if (n in nbrs)) else: return ((n, n) for (n, nbrs) in self._adj.items() if (n in nbrs)...
'Return the number of selfloop edges. A selfloop edge has the same node at both ends. Returns nloops : int The number of selfloops. See Also nodes_with_selfloops, selfloop_edges Examples >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge(1, 1) >>> G.add_edge(1, 2) >>> G.number_of_selfloops(...
def number_of_selfloops(self):
return sum((1 for _ in self.selfloop_edges()))
'Return the number of edges or total of all edge weights. Parameters weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. Returns size : numeric The number of edges or (if weight keyword is provided) the total weight s...
def size(self, weight=None):
s = sum((d for (v, d) in self.degree(weight=weight))) return ((s // 2) if (weight is None) else (s / 2))
'Return the number of edges between two nodes. 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 the total number of all edges. Returns nedges : int The number of edges in the graph. If nodes `u` and `v` are specified return the...
def number_of_edges(self, u=None, v=None):
if (u is None): return int(self.size()) if (v in self._adj[u]): return 1 return 0
'Return an iterator over nodes contained in nbunch that are also in the graph. The nodes in nbunch are checked for membership in the graph and if not are silently ignored. Parameters nbunch : iterable container, optional (default=all nodes) A container of nodes. The container will be iterated through once. Returns nit...
def nbunch_iter(self, nbunch=None):
if (nbunch is None): bunch = iter(self._adj) elif (nbunch in self): bunch = iter([nbunch]) else: def bunch_iter(nlist, adj): try: for n in nlist: if (n in adj): (yield n) except TypeError as e: ...
'Add an edge between u and v. The nodes u and v will be automatically added if they are not already in the graph. Edge attributes can be specified with keywords or by directly accessing the edge\'s attribute dictionary. See examples below. Parameters u, v : nodes Nodes can be, for example, strings or numbers. Nodes mus...
def add_edge(self, u, v, key=None, **attr):
if (u not in self._succ): self._succ[u] = self.adjlist_inner_dict_factory() self._pred[u] = self.adjlist_inner_dict_factory() self._node[u] = {} if (v not in self._succ): self._succ[v] = self.adjlist_inner_dict_factory() self._pred[v] = self.adjlist_inner_dict_factory() ...
'Remove an edge between u and v. Parameters u, v : nodes Remove an edge between nodes u and v. key : hashable identifier, optional (default=None) Used to distinguish multiple edges between a pair of nodes. If None remove a single (arbitrary) edge between u and v. Raises NetworkXError If there is not an edge between u a...
def remove_edge(self, u, v, key=None):
try: d = self._adj[u][v] except KeyError: raise NetworkXError(('The edge %s-%s is not in the graph.' % (u, v))) if (key is None): d.popitem() else: try: del d[key] except KeyError: msg = 'The edge %s-%s with ...
'Return an iterator over the edges. edges(self, nbunch=None, data=False, keys=False, default=None) Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data). Parameters nbunch : iterable container, optional (default= all nodes) A container of nodes. The container will be iterate...
@property def edges(self):
self.__dict__['edges'] = edges = OutMultiEdgeView(self) self.__dict__['out_edges'] = edges return edges
'Return an iterator over the incoming edges. in_edges(self, nbunch=None, data=False, keys=False, default=None) Parameters nbunch : iterable container, optional (default= all nodes) A container of nodes. The container will be iterated through once. data : string or bool, optional (default=False) The edge attribute retu...
@property def in_edges(self):
self.__dict__['in_edges'] = in_edges = InMultiEdgeView(self) return in_edges
'Return an iterator for (node, degree) or degree for single node. degree(self, nbunch=None, weight=None) The node degree is the number of edges adjacent to the node. This function returns the degree for a single node or an iterator for a bunch of nodes or if nothing is passed as argument. Parameters nbunch : iterable c...
@property def degree(self):
self.__dict__['degree'] = degree = DiMultiDegreeView(self) return degree
'Return an iterator for (node, in-degree) or in-degree for single node. in_degree(self, nbunch=None, weight=None) The node in-degree is the number of edges pointing in to the node. This function returns the in-degree for a single node or an iterator for a bunch of nodes or if nothing is passed as argument. Parameters n...
@property def in_degree(self):
self.__dict__['in_degree'] = in_degree = InMultiDegreeView(self) return in_degree
'Return an iterator for (node, out-degree) or out-degree for single node. out_degree(self, nbunch=None, weight=None) The node out-degree is the number of edges pointing out of the node. This function returns the out-degree for a single node or an iterator for a bunch of nodes or if nothing is passed as argument. Parame...
@property def out_degree(self):
self.__dict__['out_degree'] = out_degree = OutMultiDegreeView(self) return out_degree
'Return True if graph is a multigraph, False otherwise.'
def is_multigraph(self):
return True
'Return True if graph is directed, False otherwise.'
def is_directed(self):
return True
'Return a directed copy of the graph. Returns G : MultiDiGraph A deepcopy of the graph. Notes If edges in both directions (u, v) and (v, u) exist in the graph, attributes for the new undirected edge will be a combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that th...
def to_directed(self):
return deepcopy(self)
'Return an undirected representation of the digraph. Parameters reciprocal : bool (optional) If True only keep edges that appear in both directions in the original digraph. Returns G : MultiGraph An undirected graph with the same name and nodes and with edge (u, v, data) if either (u, v, data) or (v, u, data) is in the...
def to_undirected(self, reciprocal=False):
H = MultiGraph() H.name = self.name H.add_nodes_from(self) if (reciprocal is True): H.add_edges_from(((u, v, key, deepcopy(data)) for (u, nbrs) in self.adjacency() for (v, keydict) in nbrs.items() for (key, data) in keydict.items() if self.has_edge(v, u, key))) else: H.add_edges_from...
'Return the subgraph induced on nodes in nbunch. The induced subgraph of the graph contains the nodes in nbunch and the edges between those nodes. Parameters nbunch : list, iterable A container of nodes which will be iterated through once. Returns G : Graph A subgraph of the graph with the same edge attributes. Notes T...
def subgraph(self, nbunch):
bunch = self.nbunch_iter(nbunch) H = self.__class__() for n in bunch: H._node[n] = self._node[n] H_succ = H._succ H_pred = H._pred self_succ = self._succ self_pred = self._pred for n in H: H_succ[n] = H.adjlist_inner_dict_factory() H_pred[n] = H.adjlist_inner_dict...
'Returns the subgraph induced by the specified edges. The induced subgraph contains each edge in `edges` and each node incident to any one of those edges. Parameters edges : iterable An iterable of edges in this graph. Returns G : Graph An edge-induced subgraph of this graph with the same edge attributes. Notes The gra...
def edge_subgraph(self, edges):
H = self.__class__() succ = self._succ def is_in_graph(u, v, k): return ((u in succ) and (v in succ[u]) and (k in succ[u][v])) edges = (e for e in edges if is_in_graph(*e)) for (u, v, k) in edges: if (u not in H.node): H._node[u] = self._node[u] if (v not in H.nod...
'Return the reverse of the graph. The reverse is a graph with the same nodes and edges but with the directions of the edges reversed. Parameters copy : bool optional (default=True) If True, return a new DiGraph holding the reversed edges. If False, reverse the reverse graph is created using the original graph (this cha...
def reverse(self, copy=True):
if copy: H = self.__class__(name=('Reverse of (%s)' % self.name)) H.add_nodes_from(self) H.add_edges_from(((v, u, k, deepcopy(d)) for (u, v, k, d) in self.edges(keys=True, data=True))) H.graph = deepcopy(self.graph) H._node = deepcopy(self._node) else: (self...
'Create a new empty union-find structure. If *elements* is an iterable, this structure will be initialized with the discrete partition on the given set of elements.'
def __init__(self, elements=None):
if (elements is None): elements = () self.parents = {} self.weights = {} for x in elements: self.weights[x] = 1 self.parents[x] = x
'Find and return the name of the set containing the object.'
def __getitem__(self, object):
if (object not in self.parents): self.parents[object] = object self.weights[object] = 1 return object path = [object] root = self.parents[object] while (root != path[(-1)]): path.append(root) root = self.parents[root] for ancestor in path: self.parents...
'Iterate through all items ever found or unioned by this structure.'
def __iter__(self):
return iter(self.parents)
'Iterates over the sets stored in this structure. For example:: >>> partition = UnionFind(\'xyz\') >>> sorted(map(sorted, partition.to_sets())) [[\'x\'], [\'y\'], [\'z\']] >>> partition.union(\'x\', \'y\') >>> sorted(map(sorted, partition.to_sets())) [[\'x\', \'y\'], [\'z\']]'
def to_sets(self):
for block in groups(self.parents).values(): (yield block)
'Find the sets containing the objects and merge them all.'
def union(self, *objects):
roots = [self[x] for x in objects] heaviest = max(roots, key=(lambda r: self.weights[r])) for r in roots: if (r != heaviest): self.weights[heaviest] += self.weights[r] self.parents[r] = heaviest
'Initialize a new min-heap.'
def __init__(self):
self._dict = {}
'Query the minimum key-value pair. Returns key, value : tuple The key-value pair with the minimum value in the heap. Raises NetworkXError If the heap is empty.'
def min(self):
raise NotImplementedError
'Delete the minimum pair in the heap. Returns key, value : tuple The key-value pair with the minimum value in the heap. Raises NetworkXError If the heap is empty.'
def pop(self):
raise NotImplementedError
'Return the value associated with a key. Parameters key : hashable object The key to be looked up. default : object Default value to return if the key is not present in the heap. Default value: None. Returns value : object. The value associated with the key.'
def get(self, key, default=None):
raise NotImplementedError
'Insert a new key-value pair or modify the value in an existing pair. Parameters key : hashable object The key. value : object comparable with existing values. The value. allow_increase : bool Whether the value is allowed to increase. If False, attempts to increase an existing value have no effect. Default value: False...
def insert(self, key, value, allow_increase=False):
raise NotImplementedError
'Return whether the heap if empty.'
def __nonzero__(self):
return bool(self._dict)
'Return whether the heap if empty.'
def __bool__(self):
return bool(self._dict)
'Return the number of key-value pairs in the heap.'
def __len__(self):
return len(self._dict)
'Return whether a key exists in the heap. Parameters key : any hashable object. The key to be looked up.'
def __contains__(self, key):
return (key in self._dict)
'Initialize a pairing heap.'
def __init__(self):
super(PairingHeap, self).__init__() self._root = None
'Link two nodes, making the one with the smaller value the parent of the other.'
def _link(self, root, other):
if (other.value < root.value): (root, other) = (other, root) next = root.left other.next = next if (next is not None): next.prev = other other.prev = None root.left = other other.parent = root return root
'Merge the subtrees of the root using the standard two-pass method. The resulting subtree is detached from the root.'
def _merge_children(self, root):
node = root.left root.left = None if (node is not None): link = self._link prev = None while True: next = node.next if (next is None): node.prev = prev break next_next = next.next node = link(node, next) ...
'Cut a node from its parent.'
def _cut(self, node):
prev = node.prev next = node.next if (prev is not None): prev.next = next else: node.parent.left = next node.prev = None if (next is not None): next.prev = prev node.next = None node.parent = None
'Initialize a binary heap.'
def __init__(self):
super(BinaryHeap, self).__init__() self._heap = [] self._count = count()
'Return a dict of neighbors of node n in the dense graph. Parameters n : node A node in the graph. Returns adj_dict : dictionary The adjacency dictionary for nodes connected to n.'
def __getitem__(self, n):
return dict(((node, self.all_edge_dict) for node in ((set(self.adj) - set(self.adj[n])) - set([n]))))
'Return an iterator over all neighbors of node n in the dense graph.'
def neighbors(self, n):
try: return iter(((set(self.adj) - set(self.adj[n])) - set([n]))) except KeyError: raise NetworkXError(('The node %s is not in the graph.' % (n,)))
'Return an iterator for (node, degree) in the dense graph. The node degree is the number of edges adjacent to the node. Parameters nbunch : iterable container, optional (default=all nodes) A container of nodes. The container will be iterated through once. weight : string or None, optional (default=None) The edge attri...
def degree(self, nbunch=None, weight=None):
if (nbunch is None): nodes_nbrs = ((n, {v: self.all_edge_dict for v in ((set(self.adj) - set(self.adj[n])) - set([n]))}) for n in self.nodes()) elif (nbunch in self): nbrs = ((set(self.nodes()) - set(self.adj[nbunch])) - {nbunch}) return len(nbrs) else: nodes_nbrs = ((n, {v: ...
'Return an iterator of (node, adjacency set) tuples for all nodes in the dense graph. This is the fastest way to look at every edge. For directed graphs, only outgoing adjacencies are included. Returns adj_iter : iterator An iterator of (node, adjacency set) for all nodes in the graph.'
def adjacency_iter(self):
for n in self.adj: (yield (n, ((set(self.adj) - set(self.adj[n])) - set([n]))))
'Called when a method is about to be executed on the server.'
def hook_server_before_exec(self, request_event):
for functor in self._hooks['server_before_exec']: functor(request_event)
'Called when a method has been executed successfully. This hook is called right before the answer is sent back to the client. If the method streams its answer (i.e: it uses the zerorpc.stream decorator) then this hook will be called once the reply has been fully streamed (and right before the stream is "closed"). The r...
def hook_server_after_exec(self, request_event, reply_event):
for functor in self._hooks['server_after_exec']: functor(request_event, reply_event)
'Called when a method raised an exception. The reply_event argument will be None if the Push/Pull pattern is used.'
def hook_server_inspect_exception(self, request_event, reply_event, exc_infos):
task_context = self.hook_get_task_context() for functor in self._hooks['server_inspect_exception']: functor(request_event, reply_event, task_context, exc_infos)
'Called when the Client is about to send a request. You can see it as the counterpart of ``hook_server_before_exec``.'
def hook_client_before_request(self, event):
for functor in self._hooks['client_before_request']: functor(event)
'Called when an answer or a timeout has been received from the server. This hook is called right before the answer is returned to the client. You can see it as the counterpart of the ``hook_server_after_exec``. If the called method was returning a stream (i.e: it uses the zerorpc.stream decorator) then this hook will b...
def hook_client_after_request(self, request_event, reply_event, exception=None):
for functor in self._hooks['client_after_request']: functor(request_event, reply_event, exception)
'Configuration of the agent for serialization.'
def get_config(self):
return {}
'Trains the agent on the given environment. # Arguments env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details. nb_steps (integer): Number of training steps to be performed. action_repetition (integer): Number of times the agent repeats the same action without observing the enviro...
def fit(self, env, nb_steps, action_repetition=1, callbacks=None, verbose=1, visualize=False, nb_max_start_steps=0, start_step_policy=None, log_interval=10000, nb_max_episode_steps=None):
if (not self.compiled): raise RuntimeError("Your tried to fit your agent but it hasn't been compiled yet. Please call `compile()` before `fit()`.") if (action_repetition < 1): raise ValueError('action_repetition must be >= 1, is {...
'Callback that is called before training begins."'
def test(self, env, nb_episodes=1, action_repetition=1, callbacks=None, visualize=True, nb_max_episode_steps=None, nb_max_start_steps=0, start_step_policy=None, verbose=1):
if (not self.compiled): raise RuntimeError("Your tried to test your agent but it hasn't been compiled yet. Please call `compile()` before `test()`.") if (action_repetition < 1): raise ValueError('action_repetition must be >= 1, is ...
'Resets all internally kept states after an episode is completed.'
def reset_states(self):
pass
'Takes the an observation from the environment and returns the action to be taken next. If the policy is implemented by a neural network, this corresponds to a forward (inference) pass. # Argument observation (object): The current observation from the environment. # Returns The next action to be executed in the environ...
def forward(self, observation):
raise NotImplementedError()
'Updates the agent after having executed the action returned by `forward`. If the policy is implemented by a neural network, this corresponds to a weight update using back-prop. # Argument reward (float): The observed reward after executing the action returned by `forward`. terminal (boolean): `True` if the new state o...
def backward(self, reward, terminal):
raise NotImplementedError()
'Compiles an agent and the underlaying models to be used for training and testing. # Arguments optimizer (`keras.optimizers.Optimizer` instance): The optimizer to be used during training. metrics (list of functions `lambda y_true, y_pred: metric`): The metrics to run during training.'
def compile(self, optimizer, metrics=[]):
raise NotImplementedError()
'Loads the weights of an agent from an HDF5 file. # Arguments filepath (str): The path to the HDF5 file.'
def load_weights(self, filepath):
raise NotImplementedError()
'Saves the weights of an agent as an HDF5 file. # Arguments filepath (str): The path to where the weights should be saved. overwrite (boolean): If `False` and `filepath` already exists, raises an error.'
def save_weights(self, filepath, overwrite=False):
raise NotImplementedError()
'Returns all layers of the underlying model(s). If the concrete implementation uses multiple internal models, this method returns them in a concatenated list.'
@property def layers(self):
raise NotImplementedError()
'The human-readable names of the agent\'s metrics. Must return as many names as there are metrics (see also `compile`).'
@property def metrics_names(self):
return []
'Callback that is called before training begins."'
def _on_train_begin(self):
pass
'Callback that is called after training ends."'
def _on_train_end(self):
pass
'Callback that is called before testing begins."'
def _on_test_begin(self):
pass
'Callback that is called after testing ends."'
def _on_test_end(self):
pass
'Processes an entire step by applying the processor to the observation, reward, and info arguments. # Arguments observation (object): An observation as obtained by the environment. reward (float): A reward as obtained by the environment. done (boolean): `True` if the environment is in a terminal state, `False` otherwis...
def process_step(self, observation, reward, done, info):
observation = self.process_observation(observation) reward = self.process_reward(reward) info = self.process_info(info) return (observation, reward, done, info)
'Processes the observation as obtained from the environment for use in an agent and returns it.'
def process_observation(self, observation):
return observation
'Processes the reward as obtained from the environment for use in an agent and returns it.'
def process_reward(self, reward):
return reward
'Processes the info as obtained from the environment for use in an agent and returns it.'
def process_info(self, info):
return info
'Processes an action predicted by an agent but before execution in an environment.'
def process_action(self, action):
return action
'Processes an entire batch of states and returns it.'
def process_state_batch(self, batch):
return batch
'The metrics of the processor, which will be reported during training. # Returns List of `lambda y_true, y_pred: metric` functions.'
@property def metrics(self):
return []
'The human-readable names of the agent\'s metrics. Must return as many names as there are metrics (see also `compile`).'
@property def metrics_names(self):
return []
'Run one timestep of the environment\'s dynamics. Accepts an action and returns a tuple (observation, reward, done, info). # Arguments action (object): An action provided by the environment. # Returns observation (object): Agent\'s observation of the current environment. reward (float) : Amount of reward returned after...
def step(self, action):
raise NotImplementedError()
'Resets the state of the environment and returns an initial observation. # Returns observation (object): The initial observation of the space. Initial reward is assumed to be 0.'
def reset(self):
raise NotImplementedError()
'Renders the environment. The set of supported modes varies per environment. (And some environments do not support rendering at all.) # Arguments mode (str): The mode to render with. close (bool): Close all open renderings.'
def render(self, mode='human', close=False):
raise NotImplementedError()
'Override in your subclass to perform any necessary cleanup. Environments will automatically close() themselves when garbage collected or when the program exits.'
def close(self):
raise NotImplementedError()
'Sets the seed for this env\'s random number generator(s). # Returns Returns the list of seeds used in this env\'s random number generators'
def seed(self, seed=None):
raise NotImplementedError()
'Provides runtime configuration to the environment. This configuration should consist of data that tells your environment how to run (such as an address of a remote server, or path to your ImageNet data). It should not affect the semantics of the environment.'
def configure(self, *args, **kwargs):
raise NotImplementedError()
'Uniformly randomly sample a random element of this space.'
def sample(self, seed=None):
raise NotImplementedError()
'Return boolean specifying if x is a valid member of this space'
def contains(self, x):
raise NotImplementedError()
'Alias for output attribute, to match stderr'
@property def stdout(self):
return self.output
'By liuwons (https://github.com/liuwons) 增加获取知乎识甚户的倎像url scale对应的倎像尺寞: 1 - 25×25 3 - 75×75 4 - 100×100 6 - 150×150 10 - 250×250'
def get_head_img_url(self, scale=4):
scale_list = [1, 3, 4, 6, 10] scale_name = '0s0ml0t000b' if (self.user_url == None): print "I'm anonymous user." return None else: if (scale not in scale_list): print 'Illegal scale.' return None if (self.soup == None): self.pa...
'By yannisxu (https://github.com/yannisxu) 增加获取知乎 data-id 的方法来确定标识甚户的唯䞀性 #24 (https://github.com/egrcc/zhihu-python/pull/24)'
def get_data_id(self):
if (self.user_url == None): print "I'm anonymous user." return 0 else: if (self.soup == None): self.parser() soup = self.soup data_id = soup.find('button', class_='zg-btn zg-btn-follow zm-rich-follow-btn')['data-id'] return data_id
'By Mukosame (https://github.com/mukosame)'
def get_gender(self):
if (self.user_url == None): print "I'm anonymous user." return 'unknown' else: if (self.soup == None): self.parser() soup = self.soup try: gender = str(soup.find('span', class_='item gender').i) if (gender == '<i class="icon...
'By ecsys (https://github.com/ecsys) 增加了获取某甚户所有赞过答案的功胜 #29 (https://github.com/egrcc/zhihu-python/pull/29)'
def get_asks(self):
if (self.user_url == None): print "I'm anonymous user." return (yield) else: asks_num = self.get_asks_num() if (asks_num == 0): return (yield) else: for i in xrange((((asks_num - 1) / 20) + 1)): ask_url = (...
'Retrieve the source location associated with a given file/line/column in a particular translation unit.'
@staticmethod def from_position(tu, file, line, column):
return conf.lib.clang_getLocation(tu, file, line, column)
'Retrieve a SourceLocation from a given character offset. tu -- TranslationUnit file belongs to file -- File instance to obtain offset from offset -- Integer character offset within file'
@staticmethod def from_offset(tu, file, offset):
return conf.lib.clang_getLocationForOffset(tu, file, offset)
'Get the file represented by this source location.'
@property def file(self):
return self._get_instantiation()[0]
'Get the line represented by this source location.'
@property def line(self):
return self._get_instantiation()[1]
'Get the column represented by this source location.'
@property def column(self):
return self._get_instantiation()[2]
'Get the file offset represented by this source location.'
@property def offset(self):
return self._get_instantiation()[3]
'Return a SourceLocation representing the first character within a source range.'
@property def start(self):
return conf.lib.clang_getRangeStart(self)
'Return a SourceLocation representing the last character within a source range.'
@property def end(self):
return conf.lib.clang_getRangeEnd(self)