repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
constverum/ProxyBroker
proxybroker/proxy.py
Proxy.avg_resp_time
python
def avg_resp_time(self): if not self._runtimes: return 0 return round(sum(self._runtimes) / len(self._runtimes), 2)
The average connection/response time. :rtype: float
train
https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/proxy.py#L188-L195
null
class Proxy: """Proxy. :param str host: IP address of the proxy :param int port: Port of the proxy :param tuple types: (optional) List of types (protocols) which may be supported by the proxy and which can be checked to work with the proxy :param int timeout: (optional) Time...
constverum/ProxyBroker
proxybroker/proxy.py
Proxy.as_json
python
def as_json(self): info = { 'host': self.host, 'port': self.port, 'geo': { 'country': {'code': self._geo.code, 'name': self._geo.name}, 'region': { 'code': self._geo.region_code, 'name': self._geo.region_...
Return the proxy's properties in JSON format. :rtype: dict
train
https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/proxy.py#L236-L260
null
class Proxy: """Proxy. :param str host: IP address of the proxy :param int port: Port of the proxy :param tuple types: (optional) List of types (protocols) which may be supported by the proxy and which can be checked to work with the proxy :param int timeout: (optional) Time...
constverum/ProxyBroker
proxybroker/providers.py
Provider.get_proxies
python
async def get_proxies(self): log.debug('Try to get proxies from %s' % self.domain) async with aiohttp.ClientSession( headers=get_headers(), cookies=self._cookies, loop=self._loop ) as self._session: await self._pipe() log.debug( '%d proxies received ...
Receive proxies from the provider and return them. :return: :attr:`.proxies`
train
https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/providers.py#L70-L86
[ "def get_headers(rv=False):\n _rv = str(random.randint(1000, 9999)) if rv else ''\n headers = {\n # 'User-Agent': 'Mozilla/5.0 (X11; U; Linux i386; ru-RU; rv:2.0) Gecko/20100625 Firefox/3.5.11', # noqa\n 'User-Agent': 'PxBroker/%s/%s' % (version, _rv),\n 'Accept': '*/*',\n 'Accept...
class Provider: """Proxy provider. Provider - a website that publish free public proxy lists. :param str url: Url of page where to find proxies :param tuple proto: (optional) List of the types (protocols) that may be supported by proxies returned by the provider. Then used as :attr:`Pr...
constverum/ProxyBroker
examples/find_and_save.py
save
python
async def save(proxies, filename): with open(filename, 'w') as f: while True: proxy = await proxies.get() if proxy is None: break proto = 'https' if 'HTTPS' in proxy.types else 'http' row = '%s://%s:%d\n' % (proto, proxy.host, proxy.port) ...
Save proxies to a file.
train
https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/examples/find_and_save.py#L8-L17
null
"""Find 10 working HTTP(S) proxies and save them to a file.""" import asyncio from proxybroker import Broker def main(): proxies = asyncio.Queue() broker = Broker(proxies) tasks = asyncio.gather( broker.find(types=['HTTP', 'HTTPS'], limit=10), save(proxies, filename='proxies.txt'), ...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
NYUDSegDataLayer.setup
python
def setup(self, bottom, top): # config params = eval(self.param_str) self.nyud_dir = params['nyud_dir'] self.split = params['split'] self.tops = params['tops'] self.random = params.get('randomize', True) self.seed = params.get('seed', None) # store top da...
Setup data layer according to parameters: - nyud_dir: path to NYUDv2 dir - split: train / val / test - tops: list of tops to output from {color, depth, hha, label} - randomize: load in random order (default: True) - seed: seed for randomization (default: None / current time) ...
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L24-L74
null
class NYUDSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from NYUDv2 one-at-a-time while reshaping the net to preserve dimensions. The labels follow the 40 class task defined by S. Gupta, R. Girshick, p. Arbelaez, and J. Malik. Learning rich features from RGB-D im...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
NYUDSegDataLayer.load_image
python
def load_image(self, idx): im = Image.open('{}/data/images/img_{}.png'.format(self.nyud_dir, idx)) in_ = np.array(im, dtype=np.float32) in_ = in_[:,:,::-1] in_ -= self.mean_bgr in_ = in_.transpose((2,0,1)) return in_
Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L110-L123
null
class NYUDSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from NYUDv2 one-at-a-time while reshaping the net to preserve dimensions. The labels follow the 40 class task defined by S. Gupta, R. Girshick, p. Arbelaez, and J. Malik. Learning rich features from RGB-D im...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
NYUDSegDataLayer.load_label
python
def load_label(self, idx): label = scipy.io.loadmat('{}/segmentation/img_{}.mat'.format(self.nyud_dir, idx))['segmentation'].astype(np.uint8) label -= 1 # rotate labels label = label[np.newaxis, ...] return label
Load label image as 1 x height x width integer array of label indices. Shift labels so that classes are 0-39 and void is 255 (to ignore it). The leading singleton dimension is required by the loss.
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L125-L134
null
class NYUDSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from NYUDv2 one-at-a-time while reshaping the net to preserve dimensions. The labels follow the 40 class task defined by S. Gupta, R. Girshick, p. Arbelaez, and J. Malik. Learning rich features from RGB-D im...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
NYUDSegDataLayer.load_depth
python
def load_depth(self, idx): im = Image.open('{}/data/depth/img_{}.png'.format(self.nyud_dir, idx)) d = np.array(im, dtype=np.float32) d = np.log(d) d -= self.mean_logd d = d[np.newaxis, ...] return d
Load pre-processed depth for NYUDv2 segmentation set.
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L136-L145
null
class NYUDSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from NYUDv2 one-at-a-time while reshaping the net to preserve dimensions. The labels follow the 40 class task defined by S. Gupta, R. Girshick, p. Arbelaez, and J. Malik. Learning rich features from RGB-D im...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
NYUDSegDataLayer.load_hha
python
def load_hha(self, idx): im = Image.open('{}/data/hha/img_{}.png'.format(self.nyud_dir, idx)) hha = np.array(im, dtype=np.float32) hha -= self.mean_hha hha = hha.transpose((2,0,1)) return hha
Load HHA features from Gupta et al. ECCV14. See https://github.com/s-gupta/rcnn-depth/blob/master/rcnn/saveHHA.m
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L147-L156
null
class NYUDSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from NYUDv2 one-at-a-time while reshaping the net to preserve dimensions. The labels follow the 40 class task defined by S. Gupta, R. Girshick, p. Arbelaez, and J. Malik. Learning rich features from RGB-D im...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py
SIFTFlowSegDataLayer.load_image
python
def load_image(self, idx): im = Image.open('{}/Images/spatial_envelope_256x256_static_8outdoorcategories/{}.jpg'.format(self.siftflow_dir, idx)) in_ = np.array(im, dtype=np.float32) in_ = in_[:,:,::-1] in_ -= self.mean in_ = in_.transpose((2,0,1)) return in_
Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py#L92-L105
null
class SIFTFlowSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from SIFT Flow one-at-a-time while reshaping the net to preserve dimensions. This data layer has three tops: 1. the data, pre-processed 2. the semantic labels 0-32 and void 255 3. the geometric labels 0-2 an...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py
SIFTFlowSegDataLayer.load_label
python
def load_label(self, idx, label_type=None): if label_type == 'semantic': label = scipy.io.loadmat('{}/SemanticLabels/spatial_envelope_256x256_static_8outdoorcategories/{}.mat'.format(self.siftflow_dir, idx))['S'] elif label_type == 'geometric': label = scipy.io.loadmat('{}/GeoLab...
Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss.
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/siftflow_layers.py#L107-L122
null
class SIFTFlowSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from SIFT Flow one-at-a-time while reshaping the net to preserve dimensions. This data layer has three tops: 1. the data, pre-processed 2. the semantic labels 0-32 and void 255 3. the geometric labels 0-2 an...
wkentaro/pytorch-fcn
torchfcn/models/fcn32s.py
get_upsampling_weight
python
def get_upsampling_weight(in_channels, out_channels, kernel_size): factor = (kernel_size + 1) // 2 if kernel_size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.ogrid[:kernel_size, :kernel_size] filt = (1 - abs(og[0] - center) / factor) * \ (1 - abs(og[1...
Make a 2D bilinear kernel suitable for upsampling
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/models/fcn32s.py#L10-L23
null
import os.path as osp import fcn import numpy as np import torch import torch.nn as nn # https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/surgery.py class FCN32s(nn.Module): pretrained_model = \ osp.expanduser('~/data/models/pytorch/fcn32s_from_caffe.pth') @classmethod def dow...
wkentaro/pytorch-fcn
torchfcn/utils.py
label_accuracy_score
python
def label_accuracy_score(label_trues, label_preds, n_class): hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += _fast_hist(lt.flatten(), lp.flatten(), n_class) acc = np.diag(hist).sum() / hist.sum() with np.errstate(divide='ignore', invalid='ignore'): ...
Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/utils.py#L12-L34
[ "def _fast_hist(label_true, label_pred, n_class):\n mask = (label_true >= 0) & (label_true < n_class)\n hist = np.bincount(\n n_class * label_true[mask].astype(int) +\n label_pred[mask], minlength=n_class ** 2).reshape(n_class, n_class)\n return hist\n" ]
import numpy as np def _fast_hist(label_true, label_pred, n_class): mask = (label_true >= 0) & (label_true < n_class) hist = np.bincount( n_class * label_true[mask].astype(int) + label_pred[mask], minlength=n_class ** 2).reshape(n_class, n_class) return hist
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/surgery.py
transplant
python
def transplant(new_net, net, suffix=''): for p in net.params: p_new = p + suffix if p_new not in new_net.params: print 'dropping', p continue for i in range(len(net.params[p])): if i > (len(new_net.params[p_new]) - 1): print 'dropping', p, ...
Transfer weights by copying matching parameters, coercing parameters of incompatible shape, and dropping unmatched parameters. The coercion is useful to convert fully connected layers to their equivalent convolutional layers, since the weights are the same and only the shapes are different. In particu...
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/surgery.py#L5-L31
null
from __future__ import division import caffe import numpy as np def upsample_filt(size): """ Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size. """ factor = (size + 1) // 2 if size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = np.og...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/surgery.py
interp
python
def interp(net, layers): for l in layers: m, k, h, w = net.params[l][0].data.shape if m != k and k != 1: print 'input + output channels need to be the same or |output| == 1' raise if h != w: print 'filters need to be square' raise filt ...
Set weights of each layer in layers to bilinear kernels for interpolation.
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/surgery.py#L46-L59
[ "def upsample_filt(size):\n \"\"\"\n Make a 2D bilinear kernel suitable for upsampling of the given (h, w) size.\n \"\"\"\n factor = (size + 1) // 2\n if size % 2 == 1:\n center = factor - 1\n else:\n center = factor - 0.5\n og = np.ogrid[:size, :size]\n return (1 - abs(og[0] -...
from __future__ import division import caffe import numpy as np def transplant(new_net, net, suffix=''): """ Transfer weights by copying matching parameters, coercing parameters of incompatible shape, and dropping unmatched parameters. The coercion is useful to convert fully connected layers to their ...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/surgery.py
expand_score
python
def expand_score(new_net, new_layer, net, layer): old_cl = net.params[layer][0].num new_net.params[new_layer][0].data[:old_cl][...] = net.params[layer][0].data new_net.params[new_layer][1].data[0,0,0,:old_cl][...] = net.params[layer][1].data
Transplant an old score layer's parameters, with k < k' classes, into a new score layer with k classes s.t. the first k' are the old classes.
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/surgery.py#L61-L68
null
from __future__ import division import caffe import numpy as np def transplant(new_net, net, suffix=''): """ Transfer weights by copying matching parameters, coercing parameters of incompatible shape, and dropping unmatched parameters. The coercion is useful to convert fully connected layers to their ...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/voc_layers.py
VOCSegDataLayer.setup
python
def setup(self, bottom, top): # config params = eval(self.param_str) self.voc_dir = params['voc_dir'] self.split = params['split'] self.mean = np.array(params['mean']) self.random = params.get('randomize', True) self.seed = params.get('seed', None) # two ...
Setup data layer according to parameters: - voc_dir: path to PASCAL VOC year dir - split: train / val / test - mean: tuple of mean values to subtract - randomize: load in random order (default: True) - seed: seed for randomization (default: None / current time) for PASC...
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/voc_layers.py#L16-L62
null
class VOCSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from PASCAL VOC one-at-a-time while reshaping the net to preserve dimensions. Use this to feed data to a fully convolutional network. """ def reshape(self, bottom, top): # load image + label image pair ...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/pascalcontext_layers.py
PASCALContextSegDataLayer.setup
python
def setup(self, bottom, top): # config params = eval(self.param_str) self.voc_dir = params['voc_dir'] + '/VOC2010' self.context_dir = params['context_dir'] self.split = params['split'] self.mean = np.array((104.007, 116.669, 122.679), dtype=np.float32) self.random...
Setup data layer according to parameters: - voc_dir: path to PASCAL VOC dir (must contain 2010) - context_dir: path to PASCAL-Context annotations - split: train / val / test - randomize: load in random order (default: True) - seed: seed for randomization (default: None / current...
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/pascalcontext_layers.py#L23-L72
null
class PASCALContextSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from PASCAL-Context one-at-a-time while reshaping the net to preserve dimensions. The labels follow the 59 class task defined by R. Mottaghi, X. Chen, X. Liu, N.-G. Cho, S.-W. Lee, S. Fidler, R. Urt...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/pascalcontext_layers.py
PASCALContextSegDataLayer.load_label
python
def load_label(self, idx): label_400 = scipy.io.loadmat('{}/trainval/{}.mat'.format(self.context_dir, idx))['LabelMap'] label = np.zeros_like(label_400, dtype=np.uint8) for idx, l in enumerate(self.labels_59): idx_400 = self.labels_400.index(l) + 1 label[label_400 == idx_...
Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss. The full 400 labels are translated to the 59 class task labels.
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/pascalcontext_layers.py#L113-L125
null
class PASCALContextSegDataLayer(caffe.Layer): """ Load (input image, label image) pairs from PASCAL-Context one-at-a-time while reshaping the net to preserve dimensions. The labels follow the 59 class task defined by R. Mottaghi, X. Chen, X. Liu, N.-G. Cho, S.-W. Lee, S. Fidler, R. Urt...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/voc_helper.py
voc.load_label
python
def load_label(self, idx): label = Image.open('{}/SegmentationClass/{}.png'.format(self.dir, idx)) label = np.array(label, dtype=np.uint8) label = label[np.newaxis, ...] return label
Load label image as 1 x height x width integer array of label indices. The leading singleton dimension is required by the loss.
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/voc_helper.py#L27-L35
null
class voc: def __init__(self, data_path): # data_path is /path/to/PASCAL/VOC2011 self.dir = data_path self.classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'ho...
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/voc_helper.py
voc.palette
python
def palette(self, label_im): ''' Transfer the VOC color palette to an output mask for visualization. ''' if label_im.ndim == 3: label_im = label_im[0] label = Image.fromarray(label_im, mode='P') label.palette = copy.copy(self.palette) return label
Transfer the VOC color palette to an output mask for visualization.
train
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/voc_helper.py#L37-L45
null
class voc: def __init__(self, data_path): # data_path is /path/to/PASCAL/VOC2011 self.dir = data_path self.classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'ho...
msiemens/tinydb
tinydb/database.py
TinyDB.table
python
def table(self, name=DEFAULT_TABLE, **options): if name in self._table_cache: return self._table_cache[name] table_class = options.pop('table_class', self._cls_table) table = table_class(self._cls_storage_proxy(self._storage, name), name, **options) self._table_cache[name]...
Get access to a specific table. Creates a new table, if it hasn't been created before, otherwise it returns the cached :class:`~tinydb.Table` object. :param name: The name of the table. :type name: str :param cache_size: How many query results to cache. :param table_cla...
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L179-L200
null
class TinyDB(object): """ The main class of TinyDB. Gives access to the database, provides methods to insert/search/remove and getting tables. """ DEFAULT_TABLE = '_default' DEFAULT_STORAGE = JSONStorage def __init__(self, *args, **kwargs): """ Create a new instance of...
msiemens/tinydb
tinydb/database.py
TinyDB.purge_table
python
def purge_table(self, name): if name in self._table_cache: del self._table_cache[name] proxy = StorageProxy(self._storage, name) proxy.purge_table()
Purge a specific table from the database. **CANNOT BE REVERSED!** :param name: The name of the table. :type name: str
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L220-L231
[ "def purge_table(self):\n try:\n data = self._storage.read() or {}\n del data[self._table_name]\n self._storage.write(data)\n except KeyError:\n pass\n" ]
class TinyDB(object): """ The main class of TinyDB. Gives access to the database, provides methods to insert/search/remove and getting tables. """ DEFAULT_TABLE = '_default' DEFAULT_STORAGE = JSONStorage def __init__(self, *args, **kwargs): """ Create a new instance of...
msiemens/tinydb
tinydb/database.py
Table.process_elements
python
def process_elements(self, func, cond=None, doc_ids=None, eids=None): doc_ids = _get_doc_ids(doc_ids, eids) data = self._read() if doc_ids is not None: # Processed document specified by id for doc_id in doc_ids: func(data, doc_id) elif cond is n...
Helper function for processing all documents specified by condition or IDs. A repeating pattern in TinyDB is to run some code on all documents that match a condition or are specified by their ID. This is implemented in this function. The function passed as ``func`` has to be a c...
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L327-L376
[ "def _get_doc_ids(doc_ids, eids):\n # Backwards-compatibility shim\n if eids is not None:\n if doc_ids is not None:\n raise TypeError('cannot pass both eids and doc_ids')\n\n warnings.warn('eids has been renamed to doc_ids', DeprecationWarning)\n return eids\n else:\n ...
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/database.py
Table.insert
python
def insert(self, document): doc_id = self._get_doc_id(document) data = self._read() data[doc_id] = dict(document) self._write(data) return doc_id
Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L449-L462
[ "def _get_doc_id(self, document):\n if not isinstance(document, Mapping):\n raise ValueError('Document is not a Mapping')\n return self._get_next_id()\n", "def _read(self):\n \"\"\"\n Reading access to the DB.\n\n :returns: all values\n :rtype: DataProxy\n \"\"\"\n\n return self._st...
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/database.py
Table.insert_multiple
python
def insert_multiple(self, documents): doc_ids = [] data = self._read() for doc in documents: doc_id = self._get_doc_id(doc) doc_ids.append(doc_id) data[doc_id] = dict(doc) self._write(data) return doc_ids
Insert multiple documents into the table. :param documents: a list of documents to insert :returns: a list containing the inserted documents' IDs
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L464-L483
[ "def _get_doc_id(self, document):\n if not isinstance(document, Mapping):\n raise ValueError('Document is not a Mapping')\n return self._get_next_id()\n", "def _read(self):\n \"\"\"\n Reading access to the DB.\n\n :returns: all values\n :rtype: DataProxy\n \"\"\"\n\n return self._st...
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/database.py
Table.remove
python
def remove(self, cond=None, doc_ids=None, eids=None): doc_ids = _get_doc_ids(doc_ids, eids) if cond is None and doc_ids is None: raise RuntimeError('Use purge() to remove all documents') return self.process_elements( lambda data, doc_id: data.pop(doc_id), co...
Remove all matching documents. :param cond: the condition to check against :type cond: query :param doc_ids: a list of document IDs :type doc_ids: list :returns: a list containing the removed document's ID
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L485-L503
[ "def _get_doc_ids(doc_ids, eids):\n # Backwards-compatibility shim\n if eids is not None:\n if doc_ids is not None:\n raise TypeError('cannot pass both eids and doc_ids')\n\n warnings.warn('eids has been renamed to doc_ids', DeprecationWarning)\n return eids\n else:\n ...
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/database.py
Table.update
python
def update(self, fields, cond=None, doc_ids=None, eids=None): doc_ids = _get_doc_ids(doc_ids, eids) if callable(fields): return self.process_elements( lambda data, doc_id: fields(data[doc_id]), cond, doc_ids ) else: return self...
Update all matching documents to have a given set of fields. :param fields: the fields that the matching documents will have or a method that will update the documents :type fields: dict | dict -> None :param cond: which documents to update :type cond: query ...
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L505-L529
[ "def _get_doc_ids(doc_ids, eids):\n # Backwards-compatibility shim\n if eids is not None:\n if doc_ids is not None:\n raise TypeError('cannot pass both eids and doc_ids')\n\n warnings.warn('eids has been renamed to doc_ids', DeprecationWarning)\n return eids\n else:\n ...
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/database.py
Table.write_back
python
def write_back(self, documents, doc_ids=None, eids=None): doc_ids = _get_doc_ids(doc_ids, eids) if doc_ids is not None and not len(documents) == len(doc_ids): raise ValueError( 'The length of documents and doc_ids is not match.') if doc_ids is None: doc_...
Write back documents by doc_id :param documents: a list of document to write back :param doc_ids: a list of document IDs which need to be written back :returns: a list of document IDs that have been written
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L531-L564
[ "def _get_doc_ids(doc_ids, eids):\n # Backwards-compatibility shim\n if eids is not None:\n if doc_ids is not None:\n raise TypeError('cannot pass both eids and doc_ids')\n\n warnings.warn('eids has been renamed to doc_ids', DeprecationWarning)\n return eids\n else:\n ...
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/database.py
Table.upsert
python
def upsert(self, document, cond): updated_docs = self.update(document, cond) if updated_docs: return updated_docs else: return [self.insert(document)]
Update a document, if it exist - insert it otherwise. Note: this will update *all* documents matching the query. :param document: the document to insert or the fields to update :param cond: which document to look for :returns: a list containing the updated document's ID
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L566-L581
[ "def insert(self, document):\n \"\"\"\n Insert a new document into the table.\n\n :param document: the document to insert\n :returns: the inserted document's ID\n \"\"\"\n\n doc_id = self._get_doc_id(document)\n data = self._read()\n data[doc_id] = dict(document)\n self._write(data)\n\n ...
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/database.py
Table.search
python
def search(self, cond): if cond in self._query_cache: return self._query_cache.get(cond, [])[:] docs = [doc for doc in self.all() if cond(doc)] self._query_cache[cond] = docs return docs[:]
Search for all documents matching a 'where' cond. :param cond: the condition to check against :type cond: Query :returns: list of matching documents :rtype: list[Element]
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L591-L608
[ "def all(self):\n \"\"\"\n Get all documents stored in the table.\n\n :returns: a list with all documents.\n :rtype: list[Element]\n \"\"\"\n\n return list(itervalues(self._read()))\n" ]
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/database.py
Table.get
python
def get(self, cond=None, doc_id=None, eid=None): doc_id = _get_doc_id(doc_id, eid) # Cannot use process_elements here because we want to return a # specific document if doc_id is not None: # Document specified by ID return self._read().get(doc_id, None) ...
Get exactly one document specified by a query or and ID. Returns ``None`` if the document doesn't exist :param cond: the condition to check against :type cond: Query :param doc_id: the document's ID :returns: the document or None :rtype: Element | None
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L610-L636
[ "def _get_doc_id(doc_id, eid):\n # Backwards-compatibility shim\n if eid is not None:\n if doc_id is not None:\n raise TypeError('cannot pass both eid and doc_id')\n\n warnings.warn('eid has been renamed to doc_id', DeprecationWarning)\n return eid\n else:\n return do...
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/database.py
Table.contains
python
def contains(self, cond=None, doc_ids=None, eids=None): doc_ids = _get_doc_ids(doc_ids, eids) if doc_ids is not None: # Documents specified by ID return any(self.get(doc_id=doc_id) for doc_id in doc_ids) # Document specified by condition return self.get(cond) is...
Check wether the database contains a document matching a condition or an ID. If ``eids`` is set, it checks if the db contains a document with one of the specified. :param cond: the condition use :type cond: Query :param doc_ids: the document IDs to look for
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/database.py#L648-L667
[ "def _get_doc_ids(doc_ids, eids):\n # Backwards-compatibility shim\n if eids is not None:\n if doc_ids is not None:\n raise TypeError('cannot pass both eids and doc_ids')\n\n warnings.warn('eids has been renamed to doc_ids', DeprecationWarning)\n return eids\n else:\n ...
class Table(object): """ Represents a single TinyDB Table. """ def __init__(self, storage, name, cache_size=10): """ Get access to a table. :param storage: Access to the storage :type storage: StorageProxy :param name: The table name :param cache_size: M...
msiemens/tinydb
tinydb/middlewares.py
CachingMiddleware.flush
python
def flush(self): if self._cache_modified_count > 0: self.storage.write(self.cache) self._cache_modified_count = 0
Flush all unwritten data to disk.
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/middlewares.py#L106-L112
null
class CachingMiddleware(Middleware): """ Add some caching to TinyDB. This Middleware aims to improve the performance of TinyDB by writing only the last DB state every :attr:`WRITE_CACHE_SIZE` time and reading always from cache. """ #: The number of write operations to cache before writing ...
msiemens/tinydb
tinydb/queries.py
Query.matches
python
def matches(self, regex, flags=0): return self._generate_test( lambda value: re.match(regex, value, flags), ('matches', self._path, regex) )
Run a regex test against a dict value (whole string has to match). >>> Query().f1.matches(r'^\w+$') :param regex: The regular expression to use for matching
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/queries.py#L264-L275
[ "def _generate_test(self, test, hashval):\n \"\"\"\n Generate a query based on a test function.\n\n :param test: The test the query executes.\n :param hashval: The hash of the query.\n :return: A :class:`~tinydb.queries.QueryImpl` object\n \"\"\"\n if not self._path:\n raise ValueError('...
class Query(QueryImpl): """ TinyDB Queries. Allows to build queries for TinyDB databases. There are two main ways of using queries: 1) ORM-like usage: >>> User = Query() >>> db.search(User.name == 'John Doe') >>> db.search(User['logged-in'] == True) 2) Classical usage: >>> d...
msiemens/tinydb
tinydb/queries.py
Query.search
python
def search(self, regex, flags=0): return self._generate_test( lambda value: re.search(regex, value, flags), ('search', self._path, regex) )
Run a regex test against a dict value (only substring string has to match). >>> Query().f1.search(r'^\w+$') :param regex: The regular expression to use for matching
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/queries.py#L277-L289
[ "def _generate_test(self, test, hashval):\n \"\"\"\n Generate a query based on a test function.\n\n :param test: The test the query executes.\n :param hashval: The hash of the query.\n :return: A :class:`~tinydb.queries.QueryImpl` object\n \"\"\"\n if not self._path:\n raise ValueError('...
class Query(QueryImpl): """ TinyDB Queries. Allows to build queries for TinyDB databases. There are two main ways of using queries: 1) ORM-like usage: >>> User = Query() >>> db.search(User.name == 'John Doe') >>> db.search(User['logged-in'] == True) 2) Classical usage: >>> d...
msiemens/tinydb
tinydb/queries.py
Query.any
python
def any(self, cond): if callable(cond): def _cmp(value): return is_sequence(value) and any(cond(e) for e in value) else: def _cmp(value): return is_sequence(value) and any(e in cond for e in value) return self._generate_test( ...
Check if a condition is met by any document in a list, where a condition can also be a sequence (e.g. list). >>> Query().f1.any(Query().f2 == 1) Matches:: {'f1': [{'f2': 1}, {'f2': 0}]} >>> Query().f1.any([1, 2, 3]) Matches:: {'f1': [1, 2]} ...
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/queries.py#L309-L342
[ "def freeze(obj):\n if isinstance(obj, dict):\n return FrozenDict((k, freeze(v)) for k, v in obj.items())\n elif isinstance(obj, list):\n return tuple(freeze(el) for el in obj)\n elif isinstance(obj, set):\n return frozenset(obj)\n else:\n return obj\n", "def _generate_test...
class Query(QueryImpl): """ TinyDB Queries. Allows to build queries for TinyDB databases. There are two main ways of using queries: 1) ORM-like usage: >>> User = Query() >>> db.search(User.name == 'John Doe') >>> db.search(User['logged-in'] == True) 2) Classical usage: >>> d...
msiemens/tinydb
tinydb/queries.py
Query.one_of
python
def one_of(self, items): return self._generate_test( lambda value: value in items, ('one_of', self._path, freeze(items)) )
Check if the value is contained in a list or generator. >>> Query().f1.one_of(['value 1', 'value 2']) :param items: The list of items to check with
train
https://github.com/msiemens/tinydb/blob/10052cb1ae6a3682d26eb4272c44e3b020aa5877/tinydb/queries.py#L377-L388
[ "def freeze(obj):\n if isinstance(obj, dict):\n return FrozenDict((k, freeze(v)) for k, v in obj.items())\n elif isinstance(obj, list):\n return tuple(freeze(el) for el in obj)\n elif isinstance(obj, set):\n return frozenset(obj)\n else:\n return obj\n", "def _generate_test...
class Query(QueryImpl): """ TinyDB Queries. Allows to build queries for TinyDB databases. There are two main ways of using queries: 1) ORM-like usage: >>> User = Query() >>> db.search(User.name == 'John Doe') >>> db.search(User['logged-in'] == True) 2) Classical usage: >>> d...
JinnLynn/genpac
genpac/pysocks/socks.py
set_default_proxy
python
def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): socksocket.default_proxy = (proxy_type, addr, port, rdns, username.encode() if username else None, password.encode() if password else None)
set_default_proxy(proxy_type, addr[, port[, rdns[, username, password]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. All parameters are as for socket.set_proxy().
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L146-L155
null
""" SocksiPy - Python SOCKS module. Copyright 2006 Dan-Haim. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of con...
JinnLynn/genpac
genpac/pysocks/socks.py
create_connection
python
def create_connection(dest_pair, proxy_type=None, proxy_addr=None, proxy_port=None, proxy_rdns=True, proxy_username=None, proxy_password=None, timeout=None, source_address=None, socket_options=None): # Remove IPv6 brackets on th...
create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object Like socket.create_connection(), but connects to proxy before returning the socket object. dest_pair - 2-tuple of (IP/hostname, port). **proxy_args - Same args passed to socksocket.set_proxy() if present. timeout - Optional ...
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L184-L241
[ "def settimeout(self, timeout):\n self._timeout = timeout\n try:\n # test if we're connected, if so apply timeout\n peer = self.get_proxy_peername()\n super(socksocket, self).settimeout(self._timeout)\n except socket.error:\n pass\n", "def set_proxy(self, proxy_type=None, addr...
""" SocksiPy - Python SOCKS module. Copyright 2006 Dan-Haim. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of con...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket._readall
python
def _readall(self, file, count): data = b"" while len(data) < count: d = file.read(count - len(data)) if not d: raise GeneralProxyError("Connection closed unexpectedly") data += d return data
Receive EXACTLY the number of bytes requested from the file object. Blocks until the required number of bytes have been received.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L297-L308
null
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket.set_proxy
python
def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): self.proxy = (proxy_type, addr, port, rdns, username.encode() if username else None, password.encode() if password else None)
set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxy_type - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP ...
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L328-L348
null
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket.bind
python
def bind(self, *pos, **kw): proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy if not proxy_type or self.type != socket.SOCK_DGRAM: return _orig_socket.bind(self, *pos, **kw) if self._proxyconn: raise socket.error(EINVAL, "Socket already bound to a...
Implements proxy connection for UDP sockets, which happens during the bind() phase.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L355-L390
[ "def _SOCKS5_request(self, conn, cmd, dst):\n \"\"\"\n Send SOCKS5 request with given command (CMD field) and\n address (DST field). Returns resolved DST address that was used.\n \"\"\"\n proxy_type, addr, port, rdns, username, password = self.proxy\n\n writer = conn.makefile(\"wb\")\n reader =...
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket._negotiate_SOCKS5
python
def _negotiate_SOCKS5(self, *dest_addr): CONNECT = b"\x01" self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(self, CONNECT, dest_addr)
Negotiates a stream connection through a SOCKS5 server.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L471-L477
null
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket._SOCKS5_request
python
def _SOCKS5_request(self, conn, cmd, dst): proxy_type, addr, port, rdns, username, password = self.proxy writer = conn.makefile("wb") reader = conn.makefile("rb", 0) # buffering=0 renamed in Python 3 try: # First we'll send the authentication packages we support. ...
Send SOCKS5 request with given command (CMD field) and address (DST field). Returns resolved DST address that was used.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L479-L561
[ "def _readall(self, file, count):\n \"\"\"\n Receive EXACTLY the number of bytes requested from the file object.\n Blocks until the required number of bytes have been received.\n \"\"\"\n data = b\"\"\n while len(data) < count:\n d = file.read(count - len(data))\n if not d:\n ...
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket._write_SOCKS5_address
python
def _write_SOCKS5_address(self, addr, file): host, port = addr proxy_type, _, _, rdns, username, password = self.proxy family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"} # If the given destination address is an IP address, we'll # use the IP address request eve...
Return the host and port packed for the SOCKS5 protocol, and the resolved address as a tuple object.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L563-L603
null
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket._negotiate_SOCKS4
python
def _negotiate_SOCKS4(self, dest_addr, dest_port): proxy_type, addr, port, rdns, username, password = self.proxy writer = self.makefile("wb") reader = self.makefile("rb", 0) # buffering=0 renamed in Python 3 try: # Check if the destination address provided is an IP address ...
Negotiates a connection through a SOCKS4 server.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L620-L677
null
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket._negotiate_HTTP
python
def _negotiate_HTTP(self, dest_addr, dest_port): proxy_type, addr, port, rdns, username, password = self.proxy # If we need to resolve locally, we do this now addr = dest_addr if rdns else socket.gethostbyname(dest_addr) http_headers = [ b"CONNECT " + addr.encode('idna') + ...
Negotiates a connection through an HTTP server. NOTE: This currently only supports HTTP CONNECT-style proxies.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L679-L731
null
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket.connect
python
def connect(self, dest_pair): if len(dest_pair) != 2 or dest_pair[0].startswith("["): # Probably IPv6, not supported -- raise an error, and hope # Happy Eyeballs (RFC6555) makes sure at least the IPv4 # connection works... raise socket.error("PySocks doesn't suppo...
Connects to the specified destination through a proxy. Uses the same API as socket's connect(). To select the proxy server, use set_proxy(). dest_pair - 2-tuple of (IP/hostname, port).
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L740-L821
[ "def bind(self, *pos, **kw):\n \"\"\"\n Implements proxy connection for UDP sockets,\n which happens during the bind() phase.\n \"\"\"\n proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy\n if not proxy_type or self.type != socket.SOCK_DGRAM:\n return _orig_socket.bin...
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/pysocks/socks.py
socksocket._proxy_addr
python
def _proxy_addr(self): proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type) if not proxy_port: raise GeneralProxyError("Invalid proxy type") return proxy_addr, proxy_port
Return proxy address to connect to as tuple object
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/pysocks/socks.py#L823-L831
null
class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_ST...
JinnLynn/genpac
genpac/publicsuffixlist/__init__.py
PublicSuffixList._parse
python
def _parse(self, source, accept_encoded_idn, only_icann=False): publicsuffix = set() maxlabel = 0 section_is_icann = None if isinstance(source, decodablestr): source = source.splitlines() ln = 0 for line in source: ln += 1 if only_ic...
PSL parser core
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/publicsuffixlist/__init__.py#L81-L119
[ "def u(s):\n return s if isinstance(s, str) else s.decode(ENCODING)\n", "def encode_idn(domain):\n return u(domain).encode(\"idna\").decode(\"ascii\")\n" ]
class PublicSuffixList(object): """ PublicSuffixList parser. After __init__(), all instance methods become thread-safe. Most methods accept str or unicode as input in Python 2.x, str (not bytes) in Python 3.x. """ def __init__(self, source=None, accept_unknown=True, accept_encoded_idn=True, ...
JinnLynn/genpac
genpac/publicsuffixlist/__init__.py
PublicSuffixList.privatesuffix
python
def privatesuffix(self, domain, accept_unknown=None): if accept_unknown is None: accept_unknown = self.accept_unknown if not isinstance(domain, basestr): raise TypeError() labels = domain.lower().rsplit(".", self._maxlabel + 2) ll = len(labels) if "\0"...
Return shortest suffix assigned for an individual. domain: str or unicode to parse. (Required) accept_unknown: bool, assume unknown TLDs to be public suffix. (Default: object default) Return None if domain has invalid format. Return None if domain has no private part.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/publicsuffixlist/__init__.py#L125-L182
null
class PublicSuffixList(object): """ PublicSuffixList parser. After __init__(), all instance methods become thread-safe. Most methods accept str or unicode as input in Python 2.x, str (not bytes) in Python 3.x. """ def __init__(self, source=None, accept_unknown=True, accept_encoded_idn=True, ...
JinnLynn/genpac
genpac/publicsuffixlist/__init__.py
PublicSuffixList.privateparts
python
def privateparts(self, domain): s = self.privatesuffix(domain) if s is None: return None else: # I know the domain is valid and ends with private suffix pre = domain[0:-(len(s)+1)] if pre == "": return (s,) else: ...
Return tuple of labels and the private suffix.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/publicsuffixlist/__init__.py#L249-L260
[ "def privatesuffix(self, domain, accept_unknown=None):\n \"\"\" Return shortest suffix assigned for an individual.\n\n domain: str or unicode to parse. (Required)\n accept_unknown: bool, assume unknown TLDs to be public suffix. (Default: object default)\n\n Return None if domain has invalid format.\n ...
class PublicSuffixList(object): """ PublicSuffixList parser. After __init__(), all instance methods become thread-safe. Most methods accept str or unicode as input in Python 2.x, str (not bytes) in Python 3.x. """ def __init__(self, source=None, accept_unknown=True, accept_encoded_idn=True, ...
JinnLynn/genpac
genpac/publicsuffixlist/__init__.py
PublicSuffixList.subdomain
python
def subdomain(self, domain, depth): p = self.privateparts(domain) if p is None or depth > len(p) - 1: return None else: return ".".join(p[-(depth+1):])
Return so-called subdomain of specified depth in the private suffix.
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/publicsuffixlist/__init__.py#L262-L268
[ "def privateparts(self, domain):\n \"\"\" Return tuple of labels and the private suffix. \"\"\"\n s = self.privatesuffix(domain)\n if s is None:\n return None\n else:\n # I know the domain is valid and ends with private suffix\n pre = domain[0:-(len(s)+1)]\n if pre == \"\":\n...
class PublicSuffixList(object): """ PublicSuffixList parser. After __init__(), all instance methods become thread-safe. Most methods accept str or unicode as input in Python 2.x, str (not bytes) in Python 3.x. """ def __init__(self, source=None, accept_unknown=True, accept_encoded_idn=True, ...
JinnLynn/genpac
genpac/publicsuffixlist/update.py
updatePSL
python
def updatePSL(psl_file=PSLFILE): if requests is None: raise Exception("Please install python-requests http(s) library. $ sudo pip install requests") r = requests.get(PSLURL) if r.status_code != requests.codes.ok or len(r.content) == 0: raise Exception("Could not download PSL from " + PSLUR...
Updates a local copy of PSL file :param psl_file: path for the file to store the list. Default: PSLFILE
train
https://github.com/JinnLynn/genpac/blob/2f466d28f403a9a5624e02edcd538475fe475fc8/genpac/publicsuffixlist/update.py#L22-L50
null
# -*- coding: utf-8 -*- # # Copyright 2014 ko-zu <causeless@gmail.com> # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # import os import time from email.utils import...
larsyencken/csvdiff
csvdiff/patch.py
apply
python
def apply(diff, recs, strict=True): index_columns = diff['_index'] indexed = records.index(copy.deepcopy(list(recs)), index_columns) _add_records(indexed, diff['added'], index_columns, strict=strict) _remove_records(indexed, diff['removed'], index_columns, strict=strict) _update_records(indexed, dif...
Transform the records with the patch. May fail if the records do not match those expected in the patch.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L106-L116
[ "def index(record_seq: Iterator[Record], index_columns: List[str]) -> Index:\n if not index_columns:\n raise InvalidKeyError('must provide on or more columns to index on')\n\n try:\n obj = {\n tuple(r[i] for i in index_columns): r\n for r in record_seq\n }\n\n ...
# -*- coding: utf-8 -*- # # patch.py # csvdiff # """ The the patch format. """ import sys import json import copy import itertools import jsonschema from . import records from . import error SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'csvdiff', 'description': 'The patc...
larsyencken/csvdiff
csvdiff/patch.py
load
python
def load(istream, strict=True): "Deserialize a patch object." try: diff = json.load(istream) if strict: jsonschema.validate(diff, SCHEMA) except ValueError: raise InvalidPatchError('patch is not valid JSON') except jsonschema.exceptions.ValidationError as e: ...
Deserialize a patch object.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L175-L187
null
# -*- coding: utf-8 -*- # # patch.py # csvdiff # """ The the patch format. """ import sys import json import copy import itertools import jsonschema from . import records from . import error SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'csvdiff', 'description': 'The patc...
larsyencken/csvdiff
csvdiff/patch.py
save
python
def save(diff, stream=sys.stdout, compact=False): "Serialize a patch object." flags = {'sort_keys': True} if not compact: flags['indent'] = 2 json.dump(diff, stream, **flags)
Serialize a patch object.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L190-L196
null
# -*- coding: utf-8 -*- # # patch.py # csvdiff # """ The the patch format. """ import sys import json import copy import itertools import jsonschema from . import records from . import error SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'csvdiff', 'description': 'The patc...
larsyencken/csvdiff
csvdiff/patch.py
create
python
def create(from_records, to_records, index_columns, ignore_columns=None): from_indexed = records.index(from_records, index_columns) to_indexed = records.index(to_records, index_columns) if ignore_columns is not None: from_indexed = records.filter_ignored(from_indexed, ignore_columns) to_ind...
Diff two sets of records, using the index columns as the primary key for both datasets.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L199-L211
[ "def index(record_seq: Iterator[Record], index_columns: List[str]) -> Index:\n if not index_columns:\n raise InvalidKeyError('must provide on or more columns to index on')\n\n try:\n obj = {\n tuple(r[i] for i in index_columns): r\n for r in record_seq\n }\n\n ...
# -*- coding: utf-8 -*- # # patch.py # csvdiff # """ The the patch format. """ import sys import json import copy import itertools import jsonschema from . import records from . import error SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'csvdiff', 'description': 'The patc...
larsyencken/csvdiff
csvdiff/patch.py
_compare_rows
python
def _compare_rows(from_recs, to_recs, keys): "Return the set of keys which have changed." return set( k for k in keys if sorted(from_recs[k].items()) != sorted(to_recs[k].items()) )
Return the set of keys which have changed.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L236-L241
null
# -*- coding: utf-8 -*- # # patch.py # csvdiff # """ The the patch format. """ import sys import json import copy import itertools import jsonschema from . import records from . import error SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'csvdiff', 'description': 'The patc...
larsyencken/csvdiff
csvdiff/patch.py
record_diff
python
def record_diff(lhs, rhs): "Diff an individual row." delta = {} for k in set(lhs).union(rhs): from_ = lhs[k] to_ = rhs[k] if from_ != to_: delta[k] = {'from': from_, 'to': to_} return delta
Diff an individual row.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L260-L269
null
# -*- coding: utf-8 -*- # # patch.py # csvdiff # """ The the patch format. """ import sys import json import copy import itertools import jsonschema from . import records from . import error SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'csvdiff', 'description': 'The patc...
larsyencken/csvdiff
csvdiff/patch.py
filter_significance
python
def filter_significance(diff, significance): changed = diff['changed'] # remove individual field changes that are significant reduced = [{'key': delta['key'], 'fields': {k: v for k, v in delta['fields'].items() if _is_significant(v, sign...
Prune any changes in the patch which are due to numeric changes less than this level of significance.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L304-L323
null
# -*- coding: utf-8 -*- # # patch.py # csvdiff # """ The the patch format. """ import sys import json import copy import itertools import jsonschema from . import records from . import error SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'csvdiff', 'description': 'The patc...
larsyencken/csvdiff
csvdiff/patch.py
_is_significant
python
def _is_significant(change, significance): try: a = float(change['from']) b = float(change['to']) except ValueError: return True return abs(a - b) > 10 ** (-significance)
Return True if a change is genuinely significant given our tolerance.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/patch.py#L326-L337
null
# -*- coding: utf-8 -*- # # patch.py # csvdiff # """ The the patch format. """ import sys import json import copy import itertools import jsonschema from . import records from . import error SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'csvdiff', 'description': 'The patc...
larsyencken/csvdiff
csvdiff/__init__.py
diff_files
python
def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None): with open(from_file) as from_stream: with open(to_file) as to_stream: from_records = records.load(from_stream, sep=sep) to_records = records.load(to_stream, sep=sep) return patch.create(from...
Diff two CSV files, returning the patch which transforms one into the other.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L28-L38
[ "def load(file_or_stream: Any, sep: str = ',') -> SafeDictReader:\n istream = (open(file_or_stream)\n if not hasattr(file_or_stream, 'read')\n else file_or_stream)\n return SafeDictReader(istream, sep=sep)\n", "def create(from_records, to_records, index_columns, ignore_columns=No...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py # csvdiff # import sys from typing.io import TextIO import io import click from . import records, patch, error __author__ = 'Lars Yencken' __email__ = 'lars@yencken.org' __version__ = '0.3.1' # exit codes for the command-line EXIT_SAME = 0 EXIT_DIFF...
larsyencken/csvdiff
csvdiff/__init__.py
patch_file
python
def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO, strict: bool = True, sep: str = ','): diff = patch.load(patch_stream) from_records = records.load(fromcsv_stream, sep=sep) to_records = patch.apply(diff, from_records, strict=strict) # what order should t...
Apply the patch to the source CSV file, and save the result to the target file.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L49-L70
[ "def save(records: Sequence[Record], fieldnames: List[Column], ostream: TextIO):\n writer = csv.DictWriter(ostream, fieldnames)\n writer.writeheader()\n for r in records:\n writer.writerow(r)\n", "def load(istream, strict=True):\n \"Deserialize a patch object.\"\n try:\n diff = json.l...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py # csvdiff # import sys from typing.io import TextIO import io import click from . import records, patch, error __author__ = 'Lars Yencken' __email__ = 'lars@yencken.org' __version__ = '0.3.1' # exit codes for the command-line EXIT_SAME = 0 EXIT_DIFF...
larsyencken/csvdiff
csvdiff/__init__.py
patch_records
python
def patch_records(diff, from_records, strict=True): return patch.apply(diff, from_records, strict=strict)
Apply the patch to the sequence of records, returning the transformed records.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L73-L78
[ "def apply(diff, recs, strict=True):\n \"\"\"\n Transform the records with the patch. May fail if the records do not\n match those expected in the patch.\n \"\"\"\n index_columns = diff['_index']\n indexed = records.index(copy.deepcopy(list(recs)), index_columns)\n _add_records(indexed, diff['a...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py # csvdiff # import sys from typing.io import TextIO import io import click from . import records, patch, error __author__ = 'Lars Yencken' __email__ = 'lars@yencken.org' __version__ = '0.3.1' # exit codes for the command-line EXIT_SAME = 0 EXIT_DIFF...
larsyencken/csvdiff
csvdiff/__init__.py
_nice_fieldnames
python
def _nice_fieldnames(all_columns, index_columns): "Indexes on the left, other fields in alphabetical order on the right." non_index_columns = set(all_columns).difference(index_columns) return index_columns + sorted(non_index_columns)
Indexes on the left, other fields in alphabetical order on the right.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L81-L84
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py # csvdiff # import sys from typing.io import TextIO import io import click from . import records, patch, error __author__ = 'Lars Yencken' __email__ = 'lars@yencken.org' __version__ = '0.3.1' # exit codes for the command-line EXIT_SAME = 0 EXIT_DIFF...
larsyencken/csvdiff
csvdiff/__init__.py
csvdiff_cmd
python
def csvdiff_cmd(index_columns, from_csv, to_csv, style=None, output=None, sep=',', quiet=False, ignore_columns=None, significance=None): if ignore_columns is not None: for i in ignore_columns: if i in index_columns: error.abort("You can't ignore an index column")...
Compare two csv files to see what rows differ between them. The files are each expected to have a header row, and for each row to be uniquely identified by one or more indexing columns.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L128-L160
[ "def abort(message=None):\n if DEBUG:\n raise FatalError(message)\n\n print('ERROR: {0}'.format(message), file=sys.stderr)\n sys.exit(2)\n", "def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout,\n sep=',', ignored_columns=None, significance=None):\n ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py # csvdiff # import sys from typing.io import TextIO import io import click from . import records, patch, error __author__ = 'Lars Yencken' __email__ = 'lars@yencken.org' __version__ = '0.3.1' # exit codes for the command-line EXIT_SAME = 0 EXIT_DIFF...
larsyencken/csvdiff
csvdiff/__init__.py
_diff_and_summarize
python
def _diff_and_summarize(from_csv, to_csv, index_columns, stream=sys.stdout, sep=',', ignored_columns=None, significance=None): from_records = list(records.load(from_csv, sep=sep)) to_records = records.load(to_csv, sep=sep) diff = patch.create(from_records, to_records, index_columns,...
Print a summary of the difference between the two files.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L178-L194
[ "def load(file_or_stream: Any, sep: str = ',') -> SafeDictReader:\n istream = (open(file_or_stream)\n if not hasattr(file_or_stream, 'read')\n else file_or_stream)\n return SafeDictReader(istream, sep=sep)\n", "def create(from_records, to_records, index_columns, ignore_columns=No...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py # csvdiff # import sys from typing.io import TextIO import io import click from . import records, patch, error __author__ = 'Lars Yencken' __email__ = 'lars@yencken.org' __version__ = '0.3.1' # exit codes for the command-line EXIT_SAME = 0 EXIT_DIFF...
larsyencken/csvdiff
csvdiff/__init__.py
csvpatch_cmd
python
def csvpatch_cmd(input_csv, input=None, output=None, strict=True): patch_stream = (sys.stdin if input is None else open(input)) tocsv_stream = (sys.stdout if output is None else open(output, 'w')) fromcsv_stream = open(input_csv...
Apply the changes from a csvdiff patch to an existing CSV file.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/__init__.py#L229-L250
[ "def patch_file(patch_stream: TextIO, fromcsv_stream: TextIO, tocsv_stream: TextIO,\n strict: bool = True, sep: str = ','):\n \"\"\"\n Apply the patch to the source CSV file, and save the result to the target\n file.\n \"\"\"\n diff = patch.load(patch_stream)\n\n from_records = recor...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py # csvdiff # import sys from typing.io import TextIO import io import click from . import records, patch, error __author__ = 'Lars Yencken' __email__ = 'lars@yencken.org' __version__ = '0.3.1' # exit codes for the command-line EXIT_SAME = 0 EXIT_DIFF...
larsyencken/csvdiff
csvdiff/records.py
sort
python
def sort(records: Sequence[Record]) -> List[Record]: "Sort records into a canonical order, suitable for comparison." return sorted(records, key=_record_key)
Sort records into a canonical order, suitable for comparison.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/records.py#L86-L88
null
# -*- coding: utf-8 -*- # # records.py # csvdiff # from typing.io import TextIO from typing import Any, Dict, Tuple, Iterator, List, Sequence import csv import sys from . import error Column = str PrimaryKey = Tuple[str, ...] Record = Dict[Column, Any] Index = Dict[PrimaryKey, Record] class InvalidKeyError(Exce...
larsyencken/csvdiff
csvdiff/records.py
_record_key
python
def _record_key(record: Record) -> List[Tuple[Column, str]]: "An orderable representation of this record." return sorted(record.items())
An orderable representation of this record.
train
https://github.com/larsyencken/csvdiff/blob/163dd9da676a8e5f926a935803726340261f03ae/csvdiff/records.py#L91-L93
null
# -*- coding: utf-8 -*- # # records.py # csvdiff # from typing.io import TextIO from typing import Any, Dict, Tuple, Iterator, List, Sequence import csv import sys from . import error Column = str PrimaryKey = Tuple[str, ...] Record = Dict[Column, Any] Index = Dict[PrimaryKey, Record] class InvalidKeyError(Exce...
rhelmot/nclib
nclib/process.py
Process.launch
python
def launch(program, sock, stderr=True, cwd=None, env=None): if stderr is True: err = sock # redirect to socket elif stderr is False: err = open(os.devnull, 'wb') # hide elif stderr is None: err = None # redirect to console p = subprocess.Popen(program...
A static method for launching a process that is connected to a given socket. Same rules from the Process constructor apply.
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/process.py#L85-L104
null
class Process(Netcat): """ A mechanism for launching a local process and interacting with it programatically. This class is a subclass of the basic `Netcat` object so you may use any method from that class to interact with the process you've launched! :param program: The program to launch....
rhelmot/nclib
nclib/server.py
UDPServer.respond
python
def respond(self, packet, peer, flags=0): self.sock.sendto(packet, flags, peer)
Send a message back to a peer. :param packet: The data to send :param peer: The address to send to, as a tuple (host, port) :param flags: Any sending flags you want to use for some reason
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/server.py#L75-L83
null
class UDPServer(object): """ A simple UDP server model. Iterating over it will yield of tuples of datagrams and peer addresses. To respond, use the respond method, which takes the response and the peer address. :param bindto: The address to bind to, a tuple (host, port) :param dgram_size: ...
rhelmot/nclib
nclib/netcat.py
Netcat._parse_target
python
def _parse_target(target, listen, udp, ipv6): if isinstance(target, str): if target.startswith('nc '): out_host = None out_port = None try: opts, pieces = getopt.getopt(target.split()[1:], 'u46lp:', ...
Takes the basic version of the user args and extract as much data as possible from target. Returns a tuple that is its arguments but sanitized.
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L232-L361
[ "def _is_ipv6_addr(addr):\n try:\n socket.inet_pton(socket.AF_INET6, addr)\n except socket.error:\n return False\n else:\n return True\n" ]
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat._connect
python
def _connect(self, target, listen, udp, ipv6, retry): ty = socket.SOCK_DGRAM if udp else socket.SOCK_STREAM fam = socket.AF_INET6 if ipv6 else socket.AF_INET self.sock = socket.socket(fam, ty) if listen: self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ...
Takes target/listen/udp/ipv6 and sets self.sock and self.peer
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L363-L400
[ "def _print_verbose(self, s):\n assert isinstance(s, str), \"s should be str\"\n sys.stdout.write(s + '\\n')\n", "def _log_recv(self, data, yielding):\n if yielding == self.log_yield:\n if self.verbose and self.echo_recving:\n self._log_something(data, self.echo_recv_prefix)\n if...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.close
python
def close(self): if self._sock_send is not None: self._sock_send.close() return self.sock.close()
Close the socket.
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L402-L408
null
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.shutdown
python
def shutdown(self, how=socket.SHUT_RDWR): if self._sock_send is not None: self._sock_send.shutdown(how) return self.sock.shutdown(how)
Send a shutdown signal for both reading and writing, or whatever socket.SHUT_* constant you like. Shutdown differs from closing in that it explicitly changes the state of the socket resource to closed, whereas closing will only decrement the number of peers on this end of the socket, si...
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L424-L441
null
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.shutdown_rd
python
def shutdown_rd(self): if self._sock_send is not None: self.sock.close() else: return self.shutdown(socket.SHUT_RD)
Send a shutdown signal for reading - you may no longer read from this socket.
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L443-L451
[ "def shutdown(self, how=socket.SHUT_RDWR):\n \"\"\"\n Send a shutdown signal for both reading and writing, or whatever\n socket.SHUT_* constant you like.\n\n Shutdown differs from closing in that it explicitly changes the state of\n the socket resource to closed, whereas closing will only decrement t...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.shutdown_wr
python
def shutdown_wr(self): if self._sock_send is not None: self._sock_send.close() else: return self.shutdown(socket.SHUT_WR)
Send a shutdown signal for writing - you may no longer write to this socket.
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L453-L461
[ "def shutdown(self, how=socket.SHUT_RDWR):\n \"\"\"\n Send a shutdown signal for both reading and writing, or whatever\n socket.SHUT_* constant you like.\n\n Shutdown differs from closing in that it explicitly changes the state of\n the socket resource to closed, whereas closing will only decrement t...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat._recv_predicate
python
def _recv_predicate(self, predicate, timeout='default', raise_eof=True): if timeout == 'default': timeout = self._timeout self.timed_out = False start = time.time() try: while True: cut_at = predicate(self.buf) if cut_at > 0: ...
Receive until predicate returns a positive integer. The returned number is the size to return.
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L569-L618
[ "def _print_header(self, header):\n if self.verbose and self.echo_headers:\n self._print_verbose(header)\n", "def _log_recv(self, data, yielding):\n if yielding == self.log_yield:\n if self.verbose and self.echo_recving:\n self._log_something(data, self.echo_recv_prefix)\n if...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.recv
python
def recv(self, n=4096, timeout='default'): self._print_recv_header( '======== Receiving {0}B{timeout_text} ========', timeout, n) return self._recv_predicate(lambda s: min(n, len(s)), timeout)
Receive at most n bytes (default 4096) from the socket Aliases: read, get
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L640-L650
[ "def _print_recv_header(self, fmt, timeout, *args):\n if self.verbose and self.echo_headers:\n if timeout == 'default':\n timeout = self._timeout\n if timeout is not None:\n timeout_text = ' or until timeout ({0})'.format(timeout)\n else:\n timeout_text = ''\...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.recv_until
python
def recv_until(self, s, max_size=None, timeout='default'): self._print_recv_header( '======== Receiving until {0}{timeout_text} ========', timeout, repr(s)) if max_size is None: max_size = 2 ** 62 def _predicate(buf): try: return min(buf.ind...
Recieve data from the socket until the given substring is observed. Data in the same datagram as the substring, following the substring, will not be returned and will be cached for future receives. Aliases: read_until, readuntil, recvuntil
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L652-L672
[ "def _print_recv_header(self, fmt, timeout, *args):\n if self.verbose and self.echo_headers:\n if timeout == 'default':\n timeout = self._timeout\n if timeout is not None:\n timeout_text = ' or until timeout ({0})'.format(timeout)\n else:\n timeout_text = ''\...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.recv_all
python
def recv_all(self, timeout='default'): self._print_recv_header('======== Receiving until close{timeout_text} ========', timeout) return self._recv_predicate(lambda s: 0, timeout, raise_eof=False)
Return all data recieved until connection closes. Aliases: read_all, readall, recvall
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L674-L683
[ "def _print_recv_header(self, fmt, timeout, *args):\n if self.verbose and self.echo_headers:\n if timeout == 'default':\n timeout = self._timeout\n if timeout is not None:\n timeout_text = ' or until timeout ({0})'.format(timeout)\n else:\n timeout_text = ''\...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.recv_exactly
python
def recv_exactly(self, n, timeout='default'): self._print_recv_header( '======== Receiving until exactly {0}B{timeout_text} ========', timeout, n) return self._recv_predicate(lambda s: n if len(s) >= n else 0, timeout)
Recieve exactly n bytes Aliases: read_exactly, readexactly, recvexactly
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L685-L695
[ "def _print_recv_header(self, fmt, timeout, *args):\n if self.verbose and self.echo_headers:\n if timeout == 'default':\n timeout = self._timeout\n if timeout is not None:\n timeout_text = ' or until timeout ({0})'.format(timeout)\n else:\n timeout_text = ''\...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.send
python
def send(self, s): self._print_header('======== Sending ({0}) ========'.format(len(s))) self._log_send(s) out = len(s) while s: s = s[self._send(s):] return out
Sends all the given data to the socket. Aliases: write, put, sendall, send_all
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L697-L710
[ "def _print_header(self, header):\n if self.verbose and self.echo_headers:\n self._print_verbose(header)\n", "def _log_send(self, data):\n if self.verbose and self.echo_sending:\n self._log_something(data, self.echo_send_prefix)\n if self.log_send:\n self.log_send.write(data)\n", "...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.interact
python
def interact(self, insock=sys.stdin, outsock=sys.stdout): self._print_header('======== Beginning interactive session ========') if hasattr(outsock, 'buffer'): outsock = outsock.buffer # pylint: disable=no-member self.timed_out = False save_verbose = self.verbose ...
Connects the socket to the terminal for user interaction. Alternate input and output files may be specified. This method cannot be used with a timeout. Aliases: interactive, interaction
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L712-L758
[ "def select(*args, **kwargs):\n timeout = kwargs.get('timeout', None)\n\n if len(args) == 1 and hasattr(args, '__iter__'):\n args = list(args[0])\n\n socks = flatten(args)\n\n out = []\n toselect = []\n for sock in socks:\n if type(sock) is Netcat and sock.buf:\n out.appen...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.recv_line
python
def recv_line(self, max_size=None, timeout='default', ending=None): if ending is None: ending = self.LINE_ENDING return self.recv_until(ending, max_size, timeout)
Recieve until the next newline , default "\\n". The newline string can be changed by changing ``nc.LINE_ENDING``. The newline will be returned as part of the string. Aliases: recvline, readline, read_line, readln, recvln
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L762-L772
[ "def recv_until(self, s, max_size=None, timeout='default'):\n \"\"\"\n Recieve data from the socket until the given substring is observed.\n Data in the same datagram as the substring, following the substring,\n will not be returned and will be cached for future receives.\n\n Aliases: read_until, rea...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
rhelmot/nclib
nclib/netcat.py
Netcat.send_line
python
def send_line(self, line, ending=None): if ending is None: ending = self.LINE_ENDING return self.send(line + ending)
Write the string to the wire, followed by a newline. The newline string can be changed by changing ``nc.LINE_ENDING``. Aliases: sendline, writeline, write_line, writeln, sendln
train
https://github.com/rhelmot/nclib/blob/6147779766557ee4fafcbae683bdd2f74157e825/nclib/netcat.py#L774-L783
[ "def send(self, s):\n \"\"\"\n Sends all the given data to the socket.\n\n Aliases: write, put, sendall, send_all\n \"\"\"\n self._print_header('======== Sending ({0}) ========'.format(len(s)))\n\n self._log_send(s)\n out = len(s)\n\n while s:\n s = s[self._send(s):]\n return out\n...
class Netcat(object): """ This is the main class you will use to interact with a peer over the network! You may instanciate this class to either connect to a server or listen for a one-off client. One of the following must be passed in order to initialize a Netcat object: :param connect: ...
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.name
python
def name(self): return self.inquire(name=True, lifetime=False, usage=False, mechs=False).name
Get the name associated with these credentials
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L70-L73
null
class Credentials(rcreds.Creds): """GSSAPI Credentials This class represents a set of GSSAPI credentials which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.creds.Creds` class, and thus may used with both low-level and high-leve...
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.acquire
python
def acquire(cls, name=None, lifetime=None, mechs=None, usage='both', store=None): if store is None: res = rcreds.acquire_cred(name, lifetime, mechs, usage) else: if rcred_cred_store is None: raise NotImplement...
Acquire GSSAPI credentials This method acquires credentials. If the `store` argument is used, the credentials will be acquired from the given credential store (if supported). Otherwise, the credentials are acquired from the default store. The credential store information is a...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L94-L151
null
class Credentials(rcreds.Creds): """GSSAPI Credentials This class represents a set of GSSAPI credentials which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.creds.Creds` class, and thus may used with both low-level and high-leve...
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.store
python
def store(self, store=None, usage='both', mech=None, overwrite=False, set_default=False): if store is None: if rcred_rfc5588 is None: raise NotImplementedError("Your GSSAPI implementation does " "not have support for RFC 5588")...
Store these credentials into the given store This method stores the current credentials into the specified credentials store. If the default store is used, support for :rfc:`5588` is required. Otherwise, support for the credentials store extension is required. :requires-ext:`...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L153-L203
null
class Credentials(rcreds.Creds): """GSSAPI Credentials This class represents a set of GSSAPI credentials which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.creds.Creds` class, and thus may used with both low-level and high-leve...
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.impersonate
python
def impersonate(self, name=None, lifetime=None, mechs=None, usage='initiate'): if rcred_s4u is None: raise NotImplementedError("Your GSSAPI implementation does not " "have support for S4U") res = rcred_s4u.acquire_cred_impersonate_n...
Impersonate a name using the current credentials This method acquires credentials by impersonating another name using the current credentials. :requires-ext:`s4u` Args: name (Name): the name to impersonate lifetime (int): the desired lifetime of the new credent...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L205-L236
null
class Credentials(rcreds.Creds): """GSSAPI Credentials This class represents a set of GSSAPI credentials which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.creds.Creds` class, and thus may used with both low-level and high-leve...
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.inquire
python
def inquire(self, name=True, lifetime=True, usage=True, mechs=True): res = rcreds.inquire_cred(self, name, lifetime, usage, mechs) if res.name is not None: res_name = names.Name(res.name) else: res_name = None return tuples.InquireCredResult(res_name, res.lifet...
Inspect these credentials for information This method inspects these credentials for information about them. Args: name (bool): get the name associated with the credentials lifetime (bool): get the remaining lifetime for the credentials usage (bool): get the usage f...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L238-L267
null
class Credentials(rcreds.Creds): """GSSAPI Credentials This class represents a set of GSSAPI credentials which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.creds.Creds` class, and thus may used with both low-level and high-leve...
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.inquire_by_mech
python
def inquire_by_mech(self, mech, name=True, init_lifetime=True, accept_lifetime=True, usage=True): res = rcreds.inquire_cred_by_mech(self, mech, name, init_lifetime, accept_lifetime, usage) if res.name is not None: res_name =...
Inspect these credentials for per-mechanism information This method inspects these credentials for per-mechanism information about them. Args: mech (OID): the mechanism for which to retrive the information name (bool): get the name associated with the credentials ...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L269-L301
null
class Credentials(rcreds.Creds): """GSSAPI Credentials This class represents a set of GSSAPI credentials which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.creds.Creds` class, and thus may used with both low-level and high-leve...
pythongssapi/python-gssapi
gssapi/creds.py
Credentials.add
python
def add(self, name, mech, usage='both', init_lifetime=None, accept_lifetime=None, impersonator=None, store=None): if store is not None and impersonator is not None: raise ValueError('You cannot use both the `impersonator` and ' '`store` arguments...
Acquire more credentials to add to the current set This method works like :meth:`acquire`, except that it adds the acquired credentials for a single mechanism to a copy of the current set, instead of creating a new set for multiple mechanisms. Unlike :meth:`acquire`, you cannot pass Non...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/creds.py#L303-L386
null
class Credentials(rcreds.Creds): """GSSAPI Credentials This class represents a set of GSSAPI credentials which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.creds.Creds` class, and thus may used with both low-level and high-leve...
pythongssapi/python-gssapi
gssapi/names.py
Name.display_as
python
def display_as(self, name_type): if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does not " "support RFC 6680 (the GSSAPI naming " "extensions)") return rname_rfc6680.display_name_ext...
Display this name as the given name type. This method attempts to display the current :class:`Name` using the syntax of the given :class:`NameType`, if possible. Warning: In MIT krb5 versions below 1.13.3, this method can segfault if the name was not *originally* creat...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/names.py#L125-L165
null
class Name(rname.Name): """A GSSAPI Name This class represents a GSSAPI name which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.names.Name` class, and thus may used with both low-level and high-level API methods. This clas...
pythongssapi/python-gssapi
gssapi/names.py
Name.export
python
def export(self, composite=False): if composite: if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does " "not support RFC 6680 (the GSSAPI " "naming extensions)") ...
Export this name as a token. This method exports the name into a byte string which can then be imported by using the `token` argument of the constructor. Args: composite (bool): whether or not use to a composite token -- :requires-ext:`rfc6680` Returns: ...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/names.py#L188-L215
null
class Name(rname.Name): """A GSSAPI Name This class represents a GSSAPI name which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.names.Name` class, and thus may used with both low-level and high-level API methods. This clas...
pythongssapi/python-gssapi
gssapi/names.py
Name._inquire
python
def _inquire(self, **kwargs): if rname_rfc6680 is None: raise NotImplementedError("Your GSSAPI implementation does not " "support RFC 6680 (the GSSAPI naming " "extensions)") if not kwargs: default_val ...
Inspect this name for information. This method inspects the name for information. If no keyword arguments are passed, all available information is returned. Otherwise, only the keyword arguments that are passed and set to `True` are returned. Args: mech_name (bool...
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/names.py#L243-L279
null
class Name(rname.Name): """A GSSAPI Name This class represents a GSSAPI name which may be used with and/or returned by other GSSAPI methods. It inherits from the low-level GSSAPI :class:`~gssapi.raw.names.Name` class, and thus may used with both low-level and high-level API methods. This clas...
pythongssapi/python-gssapi
gssapi/mechs.py
Mechanism.from_sasl_name
python
def from_sasl_name(cls, name=None): if rfc5801 is None: raise NotImplementedError("Your GSSAPI implementation does not " "have support for RFC 5801") if isinstance(name, six.text_type): name = name.encode(_utils._get_encoding()) m = ...
Create a Mechanism from its SASL name Args: name (str): SASL name of the desired mechanism Returns: Mechanism: the desired mechanism Raises: GSSError :requires-ext:`rfc5801`
train
https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/mechs.py#L141-L164
null
class Mechanism(roids.OID): """ A GSSAPI Mechanism This class represents a mechanism and centralizes functions dealing with mechanisms and can be used with any calls. It inherits from the low-level GSSAPI :class:`~gssapi.raw.oids.OID` class, and thus can be used with both low-level and high-le...