nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
linhaow/TextClassify
aa479ae0941c008602631c50124d8c07d159bfb1
hubconfs/xlnet_hubconf.1.py
python
xlnetLMHeadModel
(*args, **kwargs)
return model
xlnetModel is the basic XLNet Transformer model from "XLNet: Generalized Autoregressive Pretraining for Language Understanding" by Zhilin Yang, Zihang Dai1, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le with a tied (pre-trained) language modeling head on top. Example: # Load the tokenizer import torch tokenizer = torch.hub.load('huggingface/pytorch-transformers', 'xlnetTokenizer', 'xlnet-large-cased') # Prepare tokenized input text_1 = "Who was Jim Henson ?" text_2 = "Jim Henson was a puppeteer" indexed_tokens_1 = tokenizer.encode(text_1) indexed_tokens_2 = tokenizer.encode(text_2) tokens_tensor_1 = torch.tensor([indexed_tokens_1]) tokens_tensor_2 = torch.tensor([indexed_tokens_2]) # Load xlnetLMHeadModel model = torch.hub.load('huggingface/pytorch-transformers', 'xlnetLMHeadModel', 'xlnet-large-cased') model.eval() # Predict hidden states features for each layer with torch.no_grad(): predictions_1, mems = model(tokens_tensor_1) predictions_2, mems = model(tokens_tensor_2, mems=mems) # Get the predicted last token predicted_index = torch.argmax(predictions_2[0, -1, :]).item() predicted_token = tokenizer.decode([predicted_index]) assert predicted_token == ' who'
xlnetModel is the basic XLNet Transformer model from "XLNet: Generalized Autoregressive Pretraining for Language Understanding" by Zhilin Yang, Zihang Dai1, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le with a tied (pre-trained) language modeling head on top.
[ "xlnetModel", "is", "the", "basic", "XLNet", "Transformer", "model", "from", "XLNet", ":", "Generalized", "Autoregressive", "Pretraining", "for", "Language", "Understanding", "by", "Zhilin", "Yang\u0003", "Zihang", "Dai\u00031", "Yiming", "Yang", "Jaime", "Carbonell",...
def xlnetLMHeadModel(*args, **kwargs): """ xlnetModel is the basic XLNet Transformer model from "XLNet: Generalized Autoregressive Pretraining for Language Understanding" by Zhilin Yang, Zihang Dai1, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, Quoc V. Le with a tied (pre-trained) language modeling head on top. Example: # Load the tokenizer import torch tokenizer = torch.hub.load('huggingface/pytorch-transformers', 'xlnetTokenizer', 'xlnet-large-cased') # Prepare tokenized input text_1 = "Who was Jim Henson ?" text_2 = "Jim Henson was a puppeteer" indexed_tokens_1 = tokenizer.encode(text_1) indexed_tokens_2 = tokenizer.encode(text_2) tokens_tensor_1 = torch.tensor([indexed_tokens_1]) tokens_tensor_2 = torch.tensor([indexed_tokens_2]) # Load xlnetLMHeadModel model = torch.hub.load('huggingface/pytorch-transformers', 'xlnetLMHeadModel', 'xlnet-large-cased') model.eval() # Predict hidden states features for each layer with torch.no_grad(): predictions_1, mems = model(tokens_tensor_1) predictions_2, mems = model(tokens_tensor_2, mems=mems) # Get the predicted last token predicted_index = torch.argmax(predictions_2[0, -1, :]).item() predicted_token = tokenizer.decode([predicted_index]) assert predicted_token == ' who' """ model = XLNetLMHeadModel.from_pretrained(*args, **kwargs) return model
[ "def", "xlnetLMHeadModel", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "model", "=", "XLNetLMHeadModel", ".", "from_pretrained", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "model" ]
https://github.com/linhaow/TextClassify/blob/aa479ae0941c008602631c50124d8c07d159bfb1/hubconfs/xlnet_hubconf.1.py#L100-L135
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/calendar.py
python
HTMLCalendar.formatmonthname
(self, theyear, themonth, withyear=True)
return '<tr><th colspan="7" class="%s">%s</th></tr>' % ( self.cssclass_month_head, s)
Return a month name as a table row.
Return a month name as a table row.
[ "Return", "a", "month", "name", "as", "a", "table", "row", "." ]
def formatmonthname(self, theyear, themonth, withyear=True): """ Return a month name as a table row. """ if withyear: s = '%s %s' % (month_name[themonth], theyear) else: s = '%s' % month_name[themonth] return '<tr><th colspan="7" class="%s">%s</th></tr>' % ( self.cssclass_month_head, s)
[ "def", "formatmonthname", "(", "self", ",", "theyear", ",", "themonth", ",", "withyear", "=", "True", ")", ":", "if", "withyear", ":", "s", "=", "'%s %s'", "%", "(", "month_name", "[", "themonth", "]", ",", "theyear", ")", "else", ":", "s", "=", "'%s...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/calendar.py#L467-L476
tranluan/Nonlinear_Face_3DMM
662098a602d542c3505cd16ba01dd302f33eeee8
model_non_linear_3DMM_proxy.py
python
DCGAN.setupParaStat
(self)
[]
def setupParaStat(self): if self.is_reduce: self.tri = load_3DMM_tri_reduce() self.vertex_tri = load_3DMM_vertex_tri_reduce() self.vt2pixel_u, self.vt2pixel_v = load_FaceAlignment_vt2pixel_reduce() self.uv_tri, self.uv_mask = load_FaceAlignment_tri_2d_reduce(with_mask = True) else: self.tri = load_3DMM_tri() self.vertex_tri = load_3DMM_vertex_tri() self.vt2pixel_u, self.vt2pixel_v = load_FaceAlignment_vt2pixel() self.uv_tri, self.uv_mask = load_FaceAlignment_tri_2d(with_mask = True) # Basis mu_shape, w_shape = load_FaceAlignment_basic('shape', is_reduce = self.is_reduce) mu_exp, w_exp = load_FaceAlignment_basic('exp', is_reduce = self.is_reduce) self.mean_shape = mu_shape + mu_exp if self.is_2d_normalize: #self.mean_shape = np.tile(np.array([0, 0, 6e4]), VERTEX_NUM) self.std_shape = np.tile(np.array([1e4, 1e4, 1e4]), self.vertexNum) else: #self.mean_shape = np.load('mean_shape.npy') self.std_shape = np.load('std_shape.npy') self.mean_shape_tf = tf.constant(self.mean_shape, tf.float32) self.std_shape_tf = tf.constant(self.std_shape, tf.float32) self.mean_m = np.load('mean_m.npy') self.std_m = np.load('std_m.npy') self.mean_m_tf = tf.constant(self.mean_m, tf.float32) self.std_m_tf = tf.constant(self.std_m, tf.float32) self.w_shape = w_shape self.w_exp = w_exp
[ "def", "setupParaStat", "(", "self", ")", ":", "if", "self", ".", "is_reduce", ":", "self", ".", "tri", "=", "load_3DMM_tri_reduce", "(", ")", "self", ".", "vertex_tri", "=", "load_3DMM_vertex_tri_reduce", "(", ")", "self", ".", "vt2pixel_u", ",", "self", ...
https://github.com/tranluan/Nonlinear_Face_3DMM/blob/662098a602d542c3505cd16ba01dd302f33eeee8/model_non_linear_3DMM_proxy.py#L639-L678
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/upstart_service.py
python
start
(name)
return not __salt__["cmd.retcode"](cmd, python_shell=False)
Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name>
Start the specified service
[ "Start", "the", "specified", "service" ]
def start(name): """ Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> """ cmd = ["service", name, "start"] return not __salt__["cmd.retcode"](cmd, python_shell=False)
[ "def", "start", "(", "name", ")", ":", "cmd", "=", "[", "\"service\"", ",", "name", ",", "\"start\"", "]", "return", "not", "__salt__", "[", "\"cmd.retcode\"", "]", "(", "cmd", ",", "python_shell", "=", "False", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/upstart_service.py#L357-L368
los-cocos/cocos
3b47281f95d6ee52bb2a357a767f213e670bd601
cocos/audio/pygame/base.py
python
get_sdl_version
()
return v.major, v.minor, v.patch
Get the version of the linked SDL runtime. :rtype: int, int, int :return: major, minor, patch
Get the version of the linked SDL runtime.
[ "Get", "the", "version", "of", "the", "linked", "SDL", "runtime", "." ]
def get_sdl_version(): """Get the version of the linked SDL runtime. :rtype: int, int, int :return: major, minor, patch """ v = SDL.SDL_Linked_Version() return v.major, v.minor, v.patch
[ "def", "get_sdl_version", "(", ")", ":", "v", "=", "SDL", ".", "SDL_Linked_Version", "(", ")", "return", "v", ".", "major", ",", "v", ".", "minor", ",", "v", ".", "patch" ]
https://github.com/los-cocos/cocos/blob/3b47281f95d6ee52bb2a357a767f213e670bd601/cocos/audio/pygame/base.py#L117-L124
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/OpenSSL/crypto.py
python
PKey.generate_key
(self, type, bits)
Generate a key pair of the given type, with the given number of bits. This generates a key "into" the this object. :param type: The key type. :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA` :param bits: The number of bits. :type bits: :py:data:`int` ``>= 0`` :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't of the appropriate type. :raises ValueError: If the number of bits isn't an integer of the appropriate size. :return: ``None``
Generate a key pair of the given type, with the given number of bits.
[ "Generate", "a", "key", "pair", "of", "the", "given", "type", "with", "the", "given", "number", "of", "bits", "." ]
def generate_key(self, type, bits): """ Generate a key pair of the given type, with the given number of bits. This generates a key "into" the this object. :param type: The key type. :type type: :py:data:`TYPE_RSA` or :py:data:`TYPE_DSA` :param bits: The number of bits. :type bits: :py:data:`int` ``>= 0`` :raises TypeError: If :py:data:`type` or :py:data:`bits` isn't of the appropriate type. :raises ValueError: If the number of bits isn't an integer of the appropriate size. :return: ``None`` """ if not isinstance(type, int): raise TypeError("type must be an integer") if not isinstance(bits, int): raise TypeError("bits must be an integer") if type == TYPE_RSA: if bits <= 0: raise ValueError("Invalid number of bits") # TODO Check error return exponent = _lib.BN_new() exponent = _ffi.gc(exponent, _lib.BN_free) _lib.BN_set_word(exponent, _lib.RSA_F4) rsa = _lib.RSA_new() result = _lib.RSA_generate_key_ex(rsa, bits, exponent, _ffi.NULL) _openssl_assert(result == 1) result = _lib.EVP_PKEY_assign_RSA(self._pkey, rsa) _openssl_assert(result == 1) elif type == TYPE_DSA: dsa = _lib.DSA_new() _openssl_assert(dsa != _ffi.NULL) dsa = _ffi.gc(dsa, _lib.DSA_free) res = _lib.DSA_generate_parameters_ex( dsa, bits, _ffi.NULL, 0, _ffi.NULL, _ffi.NULL, _ffi.NULL ) _openssl_assert(res == 1) _openssl_assert(_lib.DSA_generate_key(dsa) == 1) _openssl_assert(_lib.EVP_PKEY_set1_DSA(self._pkey, dsa) == 1) else: raise Error("No such key type") self._initialized = True
[ "def", "generate_key", "(", "self", ",", "type", ",", "bits", ")", ":", "if", "not", "isinstance", "(", "type", ",", "int", ")", ":", "raise", "TypeError", "(", "\"type must be an integer\"", ")", "if", "not", "isinstance", "(", "bits", ",", "int", ")", ...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/OpenSSL/crypto.py#L271-L325
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/phylomedb/phylomeDB3.py
python
PhylomeDB3Connector.get_phylomes_for_seed_ids
(self, ids)
return phylomes
Given a list of phylomeDB IDs, return in which phylomes these IDs have been used as a seed
Given a list of phylomeDB IDs, return in which phylomes these IDs have been used as a seed
[ "Given", "a", "list", "of", "phylomeDB", "IDs", "return", "in", "which", "phylomes", "these", "IDs", "have", "been", "used", "as", "a", "seed" ]
def get_phylomes_for_seed_ids(self, ids): """ Given a list of phylomeDB IDs, return in which phylomes these IDs have been used as a seed """ ## Check if the input parameter is well-constructed if not self.__check_input_parameter__(list_id = ids): raise NameError("get_phylomes_for_seed_ids: Check your input data") ## Get all phylomes where the input phylome IDs have been used as a seed cmd = 'SELECT CONCAT("Phy", t.protid, "_", code) AS protid, t.phylome_id,' cmd += ' ph.name FROM %s AS t, %s AS ph, ' % (self._trees, self._phylomes) cmd += 'species AS s WHERE (t.protid IN (%s) ' % (self.__parser_ids__(ids)) cmd += 'AND t.phylome_id = ph.phylome_id AND ph.seed_taxid = s.taxid) ' cmd += 'GROUP BY t.protid, ph.phylome_id' phylomes = {} if self.__execute__(cmd): for r in self._SQL.fetchall(): phylomes.setdefault(r["protid"], []).append((r["phylome_id"],r["name"])) return phylomes
[ "def", "get_phylomes_for_seed_ids", "(", "self", ",", "ids", ")", ":", "## Check if the input parameter is well-constructed", "if", "not", "self", ".", "__check_input_parameter__", "(", "list_id", "=", "ids", ")", ":", "raise", "NameError", "(", "\"get_phylomes_for_seed...
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/phylomedb/phylomeDB3.py#L1390-L1410
NTMC-Community/MatchZoo-py
0e5c04e1e948aa9277abd5c85ff99d9950d8527f
matchzoo/modules/attention.py
python
BidirectionalAttention.__init__
(self)
Init.
Init.
[ "Init", "." ]
def __init__(self): """Init.""" super().__init__()
[ "def", "__init__", "(", "self", ")", ":", "super", "(", ")", ".", "__init__", "(", ")" ]
https://github.com/NTMC-Community/MatchZoo-py/blob/0e5c04e1e948aa9277abd5c85ff99d9950d8527f/matchzoo/modules/attention.py#L43-L45
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
examples/pytorch/gas/dataloader.py
python
GASDataset.__len__
(self)
return len(self.graph)
r"""Number of data examples Return ------- int
r"""Number of data examples Return ------- int
[ "r", "Number", "of", "data", "examples", "Return", "-------", "int" ]
def __len__(self): r"""Number of data examples Return ------- int """ return len(self.graph)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "graph", ")" ]
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/examples/pytorch/gas/dataloader.py#L99-L105
PaddlePaddle/PaddleDetection
635e3e0a80f3d05751cdcfca8af04ee17c601a92
ppdet/metrics/coco_utils.py
python
json_eval_results
(metric, json_directory, dataset)
cocoapi eval with already exists proposal.json, bbox.json or mask.json
cocoapi eval with already exists proposal.json, bbox.json or mask.json
[ "cocoapi", "eval", "with", "already", "exists", "proposal", ".", "json", "bbox", ".", "json", "or", "mask", ".", "json" ]
def json_eval_results(metric, json_directory, dataset): """ cocoapi eval with already exists proposal.json, bbox.json or mask.json """ assert metric == 'COCO' anno_file = dataset.get_anno() json_file_list = ['proposal.json', 'bbox.json', 'mask.json'] if json_directory: assert os.path.exists( json_directory), "The json directory:{} does not exist".format( json_directory) for k, v in enumerate(json_file_list): json_file_list[k] = os.path.join(str(json_directory), v) coco_eval_style = ['proposal', 'bbox', 'segm'] for i, v_json in enumerate(json_file_list): if os.path.exists(v_json): cocoapi_eval(v_json, coco_eval_style[i], anno_file=anno_file) else: logger.info("{} not exists!".format(v_json))
[ "def", "json_eval_results", "(", "metric", ",", "json_directory", ",", "dataset", ")", ":", "assert", "metric", "==", "'COCO'", "anno_file", "=", "dataset", ".", "get_anno", "(", ")", "json_file_list", "=", "[", "'proposal.json'", ",", "'bbox.json'", ",", "'ma...
https://github.com/PaddlePaddle/PaddleDetection/blob/635e3e0a80f3d05751cdcfca8af04ee17c601a92/ppdet/metrics/coco_utils.py#L165-L184
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/sched.py
python
scheduler.enter
(self, delay, priority, action, argument)
return self.enterabs(time, priority, action, argument)
A variant that specifies the time as a relative time. This is actually the more commonly used interface.
A variant that specifies the time as a relative time.
[ "A", "variant", "that", "specifies", "the", "time", "as", "a", "relative", "time", "." ]
def enter(self, delay, priority, action, argument): """A variant that specifies the time as a relative time. This is actually the more commonly used interface. """ time = self.timefunc() + delay return self.enterabs(time, priority, action, argument)
[ "def", "enter", "(", "self", ",", "delay", ",", "priority", ",", "action", ",", "argument", ")", ":", "time", "=", "self", ".", "timefunc", "(", ")", "+", "delay", "return", "self", ".", "enterabs", "(", "time", ",", "priority", ",", "action", ",", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/sched.py#L63-L70
jdf/processing.py
76e48ac855fd34169a7576a5cbc396bda698e781
mode/formatter/autopep8.py
python
detect_encoding
(filename)
return 'utf-8'
Return file encoding.
Return file encoding.
[ "Return", "file", "encoding", "." ]
def detect_encoding(filename): """Return file encoding.""" return 'utf-8'
[ "def", "detect_encoding", "(", "filename", ")", ":", "return", "'utf-8'" ]
https://github.com/jdf/processing.py/blob/76e48ac855fd34169a7576a5cbc396bda698e781/mode/formatter/autopep8.py#L127-L129
constverum/ProxyBroker
d21aae8575fc3a95493233ecfd2c7cf47b36b069
proxybroker/providers.py
python
Spys_ru._pipe
(self)
[]
async def _pipe(self): expSession = r"'([a-z0-9]{32})'" url = 'http://spys.one/proxies/' page = await self.get(url) sessionId = re.findall(expSession, page)[0] data = { 'xf0': sessionId, # session id 'xpp': 3, # 3 - 200 proxies on page 'xf1': None, } # 1 = ANM & HIA; 3 = ANM; 4 = HIA method = 'POST' urls = [ {'url': url, 'data': {**data, 'xf1': lvl}, 'method': method} for lvl in [3, 4] ] await self._find_on_pages(urls)
[ "async", "def", "_pipe", "(", "self", ")", ":", "expSession", "=", "r\"'([a-z0-9]{32})'\"", "url", "=", "'http://spys.one/proxies/'", "page", "=", "await", "self", ".", "get", "(", "url", ")", "sessionId", "=", "re", ".", "findall", "(", "expSession", ",", ...
https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/providers.py#L547-L562
pimutils/todoman
6460032da527cd6885621b882d9f37f653412feb
todoman/cli.py
python
list
(ctx, *args, **kwargs)
List tasks (default). Filters any completed or cancelled tasks by default. If no arguments are provided, all lists will be displayed, and only incomplete tasks are show. Otherwise, only todos for the specified list will be displayed. eg: \b - `todo list' shows all unfinished tasks from all lists. - `todo list work' shows all unfinished tasks from the list `work`. This is the default action when running `todo'. The following commands can further filter shown todos, or include those omited by default:
List tasks (default). Filters any completed or cancelled tasks by default.
[ "List", "tasks", "(", "default", ")", ".", "Filters", "any", "completed", "or", "cancelled", "tasks", "by", "default", "." ]
def list(ctx, *args, **kwargs): """ List tasks (default). Filters any completed or cancelled tasks by default. If no arguments are provided, all lists will be displayed, and only incomplete tasks are show. Otherwise, only todos for the specified list will be displayed. eg: \b - `todo list' shows all unfinished tasks from all lists. - `todo list work' shows all unfinished tasks from the list `work`. This is the default action when running `todo'. The following commands can further filter shown todos, or include those omited by default: """ hide_list = (len([_ for _ in ctx.db.lists()]) == 1) or ( # noqa: C416 len(kwargs["lists"]) == 1 ) todos = ctx.db.todos(**kwargs) click.echo(ctx.formatter.compact_multiple(todos, hide_list))
[ "def", "list", "(", "ctx", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "hide_list", "=", "(", "len", "(", "[", "_", "for", "_", "in", "ctx", ".", "db", ".", "lists", "(", ")", "]", ")", "==", "1", ")", "or", "(", "# noqa: C416", "l...
https://github.com/pimutils/todoman/blob/6460032da527cd6885621b882d9f37f653412feb/todoman/cli.py#L610-L633
tlsnotary/tlsnotary
be3346ca8e754c7f1d027c33b183f7e799d2b0b0
src/auditee/python/slowaes/slowaes.py
python
AES.rotate
(self, word)
return word[1:] + word[:1]
Rijndael's key schedule rotate operation. Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d Word is an char list of size 4 (32 bits overall).
Rijndael's key schedule rotate operation.
[ "Rijndael", "s", "key", "schedule", "rotate", "operation", "." ]
def rotate(self, word): """ Rijndael's key schedule rotate operation. Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d Word is an char list of size 4 (32 bits overall). """ return word[1:] + word[:1]
[ "def", "rotate", "(", "self", ",", "word", ")", ":", "return", "word", "[", "1", ":", "]", "+", "word", "[", ":", "1", "]" ]
https://github.com/tlsnotary/tlsnotary/blob/be3346ca8e754c7f1d027c33b183f7e799d2b0b0/src/auditee/python/slowaes/slowaes.py#L96-L102
scikit-fuzzy/scikit-fuzzy
92ad3c382ac19707086204ac6cdf6e81353345a7
docs/ext/plot2rst.py
python
Path.pjoin
(self, *args)
return self.__class__(os.path.join(self, *args))
Join paths. `p` prefix prevents confusion with string method.
Join paths. `p` prefix prevents confusion with string method.
[ "Join", "paths", ".", "p", "prefix", "prevents", "confusion", "with", "string", "method", "." ]
def pjoin(self, *args): """Join paths. `p` prefix prevents confusion with string method.""" return self.__class__(os.path.join(self, *args))
[ "def", "pjoin", "(", "self", ",", "*", "args", ")", ":", "return", "self", ".", "__class__", "(", "os", ".", "path", ".", "join", "(", "self", ",", "*", "args", ")", ")" ]
https://github.com/scikit-fuzzy/scikit-fuzzy/blob/92ad3c382ac19707086204ac6cdf6e81353345a7/docs/ext/plot2rst.py#L151-L153
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractYamtl.py
python
extractYamtl
(item)
return False
'yamtl'
'yamtl'
[ "yamtl" ]
def extractYamtl(item): """ 'yamtl' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None return False
[ "def", "extractYamtl", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", "or", "frag", ")", "or", "'preview'", "i...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractYamtl.py#L1-L8
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/tablib-0.12.1/tablib/packages/dbfpy3/dbf.py
python
Dbf.append
(self, record)
Append ``record`` to the database.
Append ``record`` to the database.
[ "Append", "record", "to", "the", "database", "." ]
def append(self, record): """Append ``record`` to the database.""" record.index = self.header.recordCount record._write() self.header.recordCount += 1 self._changed = True self._new = False
[ "def", "append", "(", "self", ",", "record", ")", ":", "record", ".", "index", "=", "self", ".", "header", ".", "recordCount", "record", ".", "_write", "(", ")", "self", ".", "header", ".", "recordCount", "+=", "1", "self", ".", "_changed", "=", "Tru...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/tablib-0.12.1/tablib/packages/dbfpy3/dbf.py#L214-L220
Trusted-AI/adversarial-robustness-toolbox
9fabffdbb92947efa1ecc5d825d634d30dfbaf29
art/defences/detector/poison/spectral_signature_defense.py
python
SpectralSignatureDefense.detect_poison
(self, **kwargs)
return report, is_clean_lst
Returns poison detected and a report. :return: (report, is_clean_lst): where a report is a dictionary containing the index as keys the outlier score of suspected poisons as values where is_clean is a list, where is_clean_lst[i]=1 means that x_train[i] there is clean and is_clean_lst[i]=0, means that x_train[i] was classified as poison.
Returns poison detected and a report.
[ "Returns", "poison", "detected", "and", "a", "report", "." ]
def detect_poison(self, **kwargs) -> Tuple[dict, List[int]]: """ Returns poison detected and a report. :return: (report, is_clean_lst): where a report is a dictionary containing the index as keys the outlier score of suspected poisons as values where is_clean is a list, where is_clean_lst[i]=1 means that x_train[i] there is clean and is_clean_lst[i]=0, means that x_train[i] was classified as poison. """ self.set_params(**kwargs) if self.classifier.layer_names is not None: nb_layers = len(self.classifier.layer_names) else: raise ValueError("No layer names identified.") features_x_poisoned = self.classifier.get_activations( self.x_train, layer=nb_layers - 1, batch_size=self.batch_size ) features_split = segment_by_class(features_x_poisoned, self.y_train, self.classifier.nb_classes) score_by_class = [] keep_by_class = [] for idx, feature in enumerate(features_split): # Check for empty list if len(feature): # pylint: disable=C1801 score = SpectralSignatureDefense.spectral_signature_scores(np.vstack(feature)) score_cutoff = np.quantile(score, max(1 - self.eps_multiplier * self.expected_pp_poison, 0.0)) score_by_class.append(score) keep_by_class.append(score < score_cutoff) else: score_by_class.append([0]) keep_by_class.append([True]) base_indices_by_class = segment_by_class( np.arange(self.y_train.shape[0]), self.y_train, self.classifier.nb_classes, ) is_clean_lst = [0] * self.y_train.shape[0] report = {} for keep_booleans, all_scores, indices in zip(keep_by_class, score_by_class, base_indices_by_class): for keep_boolean, all_score, idx in zip(keep_booleans, all_scores, indices): if keep_boolean: is_clean_lst[idx] = 1 else: report[idx] = all_score[0] return report, is_clean_lst
[ "def", "detect_poison", "(", "self", ",", "*", "*", "kwargs", ")", "->", "Tuple", "[", "dict", ",", "List", "[", "int", "]", "]", ":", "self", ".", "set_params", "(", "*", "*", "kwargs", ")", "if", "self", ".", "classifier", ".", "layer_names", "is...
https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/9fabffdbb92947efa1ecc5d825d634d30dfbaf29/art/defences/detector/poison/spectral_signature_defense.py#L102-L151
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/sysconfig.py
python
_init_posix
(vars)
Initialize the module as appropriate for POSIX systems.
Initialize the module as appropriate for POSIX systems.
[ "Initialize", "the", "module", "as", "appropriate", "for", "POSIX", "systems", "." ]
def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # load the installed Makefile: makefile = _get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError, e: msg = "invalid Python installation: unable to open %s" % makefile if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError, e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED']
[ "def", "_init_posix", "(", "vars", ")", ":", "# load the installed Makefile:", "makefile", "=", "_get_makefile_filename", "(", ")", "try", ":", "_parse_makefile", "(", "makefile", ",", "vars", ")", "except", "IOError", ",", "e", ":", "msg", "=", "\"invalid Pytho...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/sysconfig.py#L277-L304
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
struc_t.is_varstr
(self, *args)
return _idaapi.struc_t_is_varstr(self, *args)
is_varstr(self) -> bool
is_varstr(self) -> bool
[ "is_varstr", "(", "self", ")", "-", ">", "bool" ]
def is_varstr(self, *args): """ is_varstr(self) -> bool """ return _idaapi.struc_t_is_varstr(self, *args)
[ "def", "is_varstr", "(", "self", ",", "*", "args", ")", ":", "return", "_idaapi", ".", "struc_t_is_varstr", "(", "self", ",", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L48603-L48607
facebookresearch/pytorch3d
fddd6a700fa9685c1ce2d4b266c111d7db424ecc
pytorch3d/renderer/mesh/textures.py
python
TexturesAtlas.join_batch
(self, textures: List["TexturesAtlas"])
return new_tex
Join the list of textures given by `textures` to self to create a batch of textures. Return a new TexturesAtlas object with the combined textures. Args: textures: List of TexturesAtlas objects Returns: new_tex: TexturesAtlas object with the combined textures from self and the list `textures`.
Join the list of textures given by `textures` to self to create a batch of textures. Return a new TexturesAtlas object with the combined textures.
[ "Join", "the", "list", "of", "textures", "given", "by", "textures", "to", "self", "to", "create", "a", "batch", "of", "textures", ".", "Return", "a", "new", "TexturesAtlas", "object", "with", "the", "combined", "textures", "." ]
def join_batch(self, textures: List["TexturesAtlas"]) -> "TexturesAtlas": """ Join the list of textures given by `textures` to self to create a batch of textures. Return a new TexturesAtlas object with the combined textures. Args: textures: List of TexturesAtlas objects Returns: new_tex: TexturesAtlas object with the combined textures from self and the list `textures`. """ tex_types_same = all(isinstance(tex, TexturesAtlas) for tex in textures) if not tex_types_same: raise ValueError("All textures must be of type TexturesAtlas.") atlas_list = [] atlas_list += self.atlas_list() num_faces_per_mesh = self._num_faces_per_mesh for tex in textures: atlas_list += tex.atlas_list() num_faces_per_mesh += tex._num_faces_per_mesh new_tex = self.__class__(atlas=atlas_list) new_tex._num_faces_per_mesh = num_faces_per_mesh return new_tex
[ "def", "join_batch", "(", "self", ",", "textures", ":", "List", "[", "\"TexturesAtlas\"", "]", ")", "->", "\"TexturesAtlas\"", ":", "tex_types_same", "=", "all", "(", "isinstance", "(", "tex", ",", "TexturesAtlas", ")", "for", "tex", "in", "textures", ")", ...
https://github.com/facebookresearch/pytorch3d/blob/fddd6a700fa9685c1ce2d4b266c111d7db424ecc/pytorch3d/renderer/mesh/textures.py#L553-L578
rotki/rotki
aafa446815cdd5e9477436d1b02bee7d01b398c8
rotkehlchen/chain/ethereum/modules/makerdao/vaults.py
python
MakerdaoVaults.reset_last_query_ts
(self)
Reset the last query timestamps, effectively cleaning the caches
Reset the last query timestamps, effectively cleaning the caches
[ "Reset", "the", "last", "query", "timestamps", "effectively", "cleaning", "the", "caches" ]
def reset_last_query_ts(self) -> None: """Reset the last query timestamps, effectively cleaning the caches""" super().reset_last_query_ts() self.last_vault_mapping_query_ts = 0 self.last_vault_details_query_ts = 0
[ "def", "reset_last_query_ts", "(", "self", ")", "->", "None", ":", "super", "(", ")", ".", "reset_last_query_ts", "(", ")", "self", ".", "last_vault_mapping_query_ts", "=", "0", "self", ".", "last_vault_details_query_ts", "=", "0" ]
https://github.com/rotki/rotki/blob/aafa446815cdd5e9477436d1b02bee7d01b398c8/rotkehlchen/chain/ethereum/modules/makerdao/vaults.py#L284-L288
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/userreports/reports/specs.py
python
AggregateDateColumn.get_format_fn
(self)
return _format
[]
def get_format_fn(self): def _format(data): if not data.get('year', None) or not data.get('month', None): return _('Unknown Date') format_ = self.format or '%Y-%m' return date(year=int(data['year']), month=int(data['month']), day=1).strftime(format_) return _format
[ "def", "get_format_fn", "(", "self", ")", ":", "def", "_format", "(", "data", ")", ":", "if", "not", "data", ".", "get", "(", "'year'", ",", "None", ")", "or", "not", "data", ".", "get", "(", "'month'", ",", "None", ")", ":", "return", "_", "(", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/userreports/reports/specs.py#L289-L295
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_registry.py
python
OpenShiftCLI.openshift_cmd
(self, cmd, oadm=False, output=False, output_type='json', input_data=None)
return rval
Base command for oc
Base command for oc
[ "Base", "command", "for", "oc" ]
def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None): '''Base command for oc ''' cmds = [self.oc_binary] if oadm: cmds.append('adm') cmds.extend(cmd) if self.all_namespaces: cmds.extend(['--all-namespaces']) elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501 cmds.extend(['-n', self.namespace]) if self.verbose: print(' '.join(cmds)) try: returncode, stdout, stderr = self._run(cmds, input_data) except OSError as ex: returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex) rval = {"returncode": returncode, "cmd": ' '.join(cmds)} if output_type == 'json': rval['results'] = {} if output and stdout: try: rval['results'] = json.loads(stdout) except ValueError as verr: if "No JSON object could be decoded" in verr.args: rval['err'] = verr.args elif output_type == 'raw': rval['results'] = stdout if output else '' if self.verbose: print("STDOUT: {0}".format(stdout)) print("STDERR: {0}".format(stderr)) if 'err' in rval or returncode != 0: rval.update({"stderr": stderr, "stdout": stdout}) return rval
[ "def", "openshift_cmd", "(", "self", ",", "cmd", ",", "oadm", "=", "False", ",", "output", "=", "False", ",", "output_type", "=", "'json'", ",", "input_data", "=", "None", ")", ":", "cmds", "=", "[", "self", ".", "oc_binary", "]", "if", "oadm", ":", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_registry.py#L1229-L1273
metaodi/osmapi
1559827bc77889cc67ed3a2b45cb373cfaa293f5
osmapi/OsmApi.py
python
OsmApi.NoteCreate
(self, NoteData)
return self._NoteAction(uri)
Creates a note. Returns updated NoteData (without timestamp).
Creates a note.
[ "Creates", "a", "note", "." ]
def NoteCreate(self, NoteData): """ Creates a note. Returns updated NoteData (without timestamp). """ uri = "/api/0.6/notes" uri += "?" + urllib.parse.urlencode(NoteData) return self._NoteAction(uri)
[ "def", "NoteCreate", "(", "self", ",", "NoteData", ")", ":", "uri", "=", "\"/api/0.6/notes\"", "uri", "+=", "\"?\"", "+", "urllib", ".", "parse", ".", "urlencode", "(", "NoteData", ")", "return", "self", ".", "_NoteAction", "(", "uri", ")" ]
https://github.com/metaodi/osmapi/blob/1559827bc77889cc67ed3a2b45cb373cfaa293f5/osmapi/OsmApi.py#L1590-L1598
dagster-io/dagster
b27d569d5fcf1072543533a0c763815d96f90b8f
python_modules/libraries/dagster-aws/dagster_aws/ecs/tasks.py
python
default_ecs_task_metadata
(ec2, ecs)
return TaskMetadata( cluster=cluster, subnets=subnets, security_groups=security_groups, task_definition=task_definition, container_definition=container_definition, assign_public_ip="ENABLED" if public_ip else "DISABLED", )
ECS injects an environment variable into each Fargate task. The value of this environment variable is a url that can be queried to introspect information about the current processes's running task: https://docs.aws.amazon.com/AmazonECS/latest/userguide/task-metadata-endpoint-v4-fargate.html
ECS injects an environment variable into each Fargate task. The value of this environment variable is a url that can be queried to introspect information about the current processes's running task:
[ "ECS", "injects", "an", "environment", "variable", "into", "each", "Fargate", "task", ".", "The", "value", "of", "this", "environment", "variable", "is", "a", "url", "that", "can", "be", "queried", "to", "introspect", "information", "about", "the", "current", ...
def default_ecs_task_metadata(ec2, ecs): """ ECS injects an environment variable into each Fargate task. The value of this environment variable is a url that can be queried to introspect information about the current processes's running task: https://docs.aws.amazon.com/AmazonECS/latest/userguide/task-metadata-endpoint-v4-fargate.html """ container_metadata_uri = os.environ.get("ECS_CONTAINER_METADATA_URI_V4") name = requests.get(container_metadata_uri).json()["Name"] task_metadata_uri = container_metadata_uri + "/task" response = requests.get(task_metadata_uri).json() cluster = response.get("Cluster") task_arn = response.get("TaskARN") def describe_task_or_raise(task_arn, cluster): try: return ecs.describe_tasks(tasks=[task_arn], cluster=cluster)["tasks"][0] except IndexError: raise EcsNoTasksFound try: task = backoff( describe_task_or_raise, retry_on=(EcsNoTasksFound,), kwargs={"task_arn": task_arn, "cluster": cluster}, max_retries=BACKOFF_RETRIES, ) except EcsNoTasksFound: raise EcsEventualConsistencyTimeout enis = [] subnets = [] for attachment in task["attachments"]: if attachment["type"] == "ElasticNetworkInterface": for detail in attachment["details"]: if detail["name"] == "subnetId": subnets.append(detail["value"]) if detail["name"] == "networkInterfaceId": enis.append(ec2.NetworkInterface(detail["value"])) public_ip = False security_groups = [] for eni in enis: if (eni.association_attribute or {}).get("PublicIp"): public_ip = True for group in eni.groups: security_groups.append(group["GroupId"]) task_definition_arn = task["taskDefinitionArn"] task_definition = ecs.describe_task_definition(taskDefinition=task_definition_arn)[ "taskDefinition" ] container_definition = next( iter( [ container for container in task_definition["containerDefinitions"] if container["name"] == name ] ) ) return TaskMetadata( cluster=cluster, subnets=subnets, security_groups=security_groups, task_definition=task_definition, container_definition=container_definition, assign_public_ip="ENABLED" if public_ip else "DISABLED", )
[ "def", "default_ecs_task_metadata", "(", "ec2", ",", "ecs", ")", ":", "container_metadata_uri", "=", "os", ".", "environ", ".", "get", "(", "\"ECS_CONTAINER_METADATA_URI_V4\"", ")", "name", "=", "requests", ".", "get", "(", "container_metadata_uri", ")", ".", "j...
https://github.com/dagster-io/dagster/blob/b27d569d5fcf1072543533a0c763815d96f90b8f/python_modules/libraries/dagster-aws/dagster_aws/ecs/tasks.py#L107-L179
facebookresearch/ParlAI
e4d59c30eef44f1f67105961b82a83fd28d7d78b
parlai/agents/rag/indexers.py
python
indexer_factory
(opt: Opt)
return indexer
Build indexer. :param opt: Options :return indexer: return build indexer, according to options
Build indexer.
[ "Build", "indexer", "." ]
def indexer_factory(opt: Opt) -> BaseIndexer: """ Build indexer. :param opt: Options :return indexer: return build indexer, according to options """ if opt['indexer_type'] == 'compressed': if opt['path_to_index'] == WIKIPEDIA_EXACT_INDEX: logging.warning( f'Changing index path to compressed index: {WIKIPEDIA_COMPRESSED_INDEX}' ) opt['path_to_index'] = modelzoo_path( opt['datapath'], WIKIPEDIA_COMPRESSED_INDEX ) indexer = CompressedIndexer(opt) elif opt['indexer_type'] == 'exact': if opt['path_to_index'] == WIKIPEDIA_COMPRESSED_INDEX: logging.warning( f'Changing index path to exact index: {WIKIPEDIA_EXACT_INDEX}' ) opt['path_to_index'] = modelzoo_path(opt['datapath'], WIKIPEDIA_EXACT_INDEX) indexer = DenseHNSWFlatIndexer(opt) else: raise ValueError(f"Unsupported indexer type: {opt['indexer_type']}") return indexer
[ "def", "indexer_factory", "(", "opt", ":", "Opt", ")", "->", "BaseIndexer", ":", "if", "opt", "[", "'indexer_type'", "]", "==", "'compressed'", ":", "if", "opt", "[", "'path_to_index'", "]", "==", "WIKIPEDIA_EXACT_INDEX", ":", "logging", ".", "warning", "(",...
https://github.com/facebookresearch/ParlAI/blob/e4d59c30eef44f1f67105961b82a83fd28d7d78b/parlai/agents/rag/indexers.py#L414-L443
JetBrains/python-skeletons
95ad24b666e475998e5d1cc02ed53a2188036167
numpy/core/__init__.py
python
intc.__rlshift__
(self, *args, **kwargs)
Return value<<self.
Return value<<self.
[ "Return", "value<<self", "." ]
def __rlshift__(self, *args, **kwargs): # real signature unknown """ Return value<<self. """ pass
[ "def", "__rlshift__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# real signature unknown", "pass" ]
https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/numpy/core/__init__.py#L2959-L2961
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_geo_raster_resource/models.py
python
RasterResource.can_have_multiple_files
(cls)
return False
[]
def can_have_multiple_files(cls): # can have only 1 file return False
[ "def", "can_have_multiple_files", "(", "cls", ")", ":", "# can have only 1 file", "return", "False" ]
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_geo_raster_resource/models.py#L354-L356
l11x0m7/Question_Answering_Models
b53c33db08a51f8e5f8c774eb65ec29c75942c66
cQA/qacnn/models.py
python
QACNN.add_loss_op
(self, q_ap_cosine, q_am_cosine)
return total_loss, loss, accu
损失节点
损失节点
[ "损失节点" ]
def add_loss_op(self, q_ap_cosine, q_am_cosine): """ 损失节点 """ original_loss = self.config.m - q_ap_cosine + q_am_cosine l = tf.maximum(tf.zeros_like(original_loss), original_loss) loss = tf.reduce_sum(l) tf.add_to_collection('total_loss', loss) total_loss = tf.add_n(tf.get_collection('total_loss')) accu = tf.reduce_mean(tf.cast(tf.equal(0., l), tf.float32)) return total_loss, loss, accu
[ "def", "add_loss_op", "(", "self", ",", "q_ap_cosine", ",", "q_am_cosine", ")", ":", "original_loss", "=", "self", ".", "config", ".", "m", "-", "q_ap_cosine", "+", "q_am_cosine", "l", "=", "tf", ".", "maximum", "(", "tf", ".", "zeros_like", "(", "origin...
https://github.com/l11x0m7/Question_Answering_Models/blob/b53c33db08a51f8e5f8c774eb65ec29c75942c66/cQA/qacnn/models.py#L136-L146
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_volume_attachment_status.py
python
V1VolumeAttachmentStatus.attach_error
(self)
return self._attach_error
Gets the attach_error of this V1VolumeAttachmentStatus. # noqa: E501 :return: The attach_error of this V1VolumeAttachmentStatus. # noqa: E501 :rtype: V1VolumeError
Gets the attach_error of this V1VolumeAttachmentStatus. # noqa: E501
[ "Gets", "the", "attach_error", "of", "this", "V1VolumeAttachmentStatus", ".", "#", "noqa", ":", "E501" ]
def attach_error(self): """Gets the attach_error of this V1VolumeAttachmentStatus. # noqa: E501 :return: The attach_error of this V1VolumeAttachmentStatus. # noqa: E501 :rtype: V1VolumeError """ return self._attach_error
[ "def", "attach_error", "(", "self", ")", ":", "return", "self", ".", "_attach_error" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_volume_attachment_status.py#L70-L77
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/PIL/ImageOps.py
python
deform
(image, deformer, resample=Image.BILINEAR)
return image.transform( image.size, Image.MESH, deformer.getmesh(image), resample )
Deform image using the given deformer
Deform image using the given deformer
[ "Deform", "image", "using", "the", "given", "deformer" ]
def deform(image, deformer, resample=Image.BILINEAR): "Deform image using the given deformer" return image.transform( image.size, Image.MESH, deformer.getmesh(image), resample )
[ "def", "deform", "(", "image", ",", "deformer", ",", "resample", "=", "Image", ".", "BILINEAR", ")", ":", "return", "image", ".", "transform", "(", "image", ".", "size", ",", "Image", ".", "MESH", ",", "deformer", ".", "getmesh", "(", "image", ")", "...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/PIL/ImageOps.py#L189-L193
LinOTP/LinOTP
bb3940bbaccea99550e6c063ff824f258dd6d6d7
linotp/lib/user.py
python
getUserDetail
(user)
return userinfo
Returns userinfo of an user :param user: the user :returns: the userinfo dict
Returns userinfo of an user
[ "Returns", "userinfo", "of", "an", "user" ]
def getUserDetail(user): """ Returns userinfo of an user :param user: the user :returns: the userinfo dict """ (uid, resId, resClass) = getUserId(user) log.debug("got uid %r, ResId %r, Class %r", uid, resId, resClass) userinfo = getUserInfo(uid, resId, resClass) return userinfo
[ "def", "getUserDetail", "(", "user", ")", ":", "(", "uid", ",", "resId", ",", "resClass", ")", "=", "getUserId", "(", "user", ")", "log", ".", "debug", "(", "\"got uid %r, ResId %r, Class %r\"", ",", "uid", ",", "resId", ",", "resClass", ")", "userinfo", ...
https://github.com/LinOTP/LinOTP/blob/bb3940bbaccea99550e6c063ff824f258dd6d6d7/linotp/lib/user.py#L1665-L1675
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/cbook/__init__.py
python
_string_to_bool
(s)
Parses the string argument as a boolean
Parses the string argument as a boolean
[ "Parses", "the", "string", "argument", "as", "a", "boolean" ]
def _string_to_bool(s): """Parses the string argument as a boolean""" if not isinstance(s, str): return bool(s) warn_deprecated("2.2", "Passing one of 'on', 'true', 'off', 'false' as a " "boolean is deprecated; use an actual boolean " "(True/False) instead.") if s.lower() in ['on', 'true']: return True if s.lower() in ['off', 'false']: return False raise ValueError('String "%s" must be one of: ' '"on", "off", "true", or "false"' % s)
[ "def", "_string_to_bool", "(", "s", ")", ":", "if", "not", "isinstance", "(", "s", ",", "str", ")", ":", "return", "bool", "(", "s", ")", "warn_deprecated", "(", "\"2.2\"", ",", "\"Passing one of 'on', 'true', 'off', 'false' as a \"", "\"boolean is deprecated; use a...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/cbook/__init__.py#L420-L432
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/PIL/Image.py
python
Image.paste
(self, im, box=None, mask=None)
Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image.
Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region.
[ "Pastes", "another", "image", "into", "this", "image", ".", "The", "box", "argument", "is", "either", "a", "2", "-", "tuple", "giving", "the", "upper", "left", "corner", "a", "4", "-", "tuple", "defining", "the", "left", "upper", "right", "and", "lower",...
def paste(self, im, box=None, mask=None): """ Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the size of the pasted image must match the size of the region. If the modes don't match, the pasted image is converted to the mode of this image (see the :py:meth:`~PIL.Image.Image.convert` method for details). Instead of an image, the source can be a integer or tuple containing pixel values. The method then fills the region with the given color. When creating RGB images, you can also use color strings as supported by the ImageColor module. If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L" or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them. See :py:meth:`~PIL.Image.Image.alpha_composite` if you want to combine images with respect to their alpha channels. :param im: Source image or pixel value (integer or tuple). :param box: An optional 4-tuple giving the region to paste into. If a 2-tuple is used instead, it's treated as the upper left corner. If omitted or None, the source is pasted into the upper left corner. If an image is given as the second argument and there is no third, the box defaults to (0, 0), and the second argument is interpreted as a mask image. :param mask: An optional mask image. """ if isImageType(box) and mask is None: # abbreviated paste(im, mask) syntax mask = box box = None if box is None: box = (0, 0) if len(box) == 2: # upper left corner given; get size from image or mask if isImageType(im): size = im.size elif isImageType(mask): size = mask.size else: # FIXME: use self.size here? raise ValueError("cannot determine region size; use 4-item box") box += (box[0] + size[0], box[1] + size[1]) if isinstance(im, str): from . import ImageColor im = ImageColor.getcolor(im, self.mode) elif isImageType(im): im.load() if self.mode != im.mode: if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"): # should use an adapter for this! im = im.convert(self.mode) im = im.im self._ensure_mutable() if mask: mask.load() self.im.paste(im, box, mask.im) else: self.im.paste(im, box)
[ "def", "paste", "(", "self", ",", "im", ",", "box", "=", "None", ",", "mask", "=", "None", ")", ":", "if", "isImageType", "(", "box", ")", "and", "mask", "is", "None", ":", "# abbreviated paste(im, mask) syntax", "mask", "=", "box", "box", "=", "None",...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/PIL/Image.py#L1418-L1496
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/db/migrations/operations/models.py
python
AlterUniqueTogether.__init__
(self, name, unique_together)
[]
def __init__(self, name, unique_together): unique_together = normalize_together(unique_together) self.unique_together = set(tuple(cons) for cons in unique_together) super(AlterUniqueTogether, self).__init__(name)
[ "def", "__init__", "(", "self", ",", "name", ",", "unique_together", ")", ":", "unique_together", "=", "normalize_together", "(", "unique_together", ")", "self", ".", "unique_together", "=", "set", "(", "tuple", "(", "cons", ")", "for", "cons", "in", "unique...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/db/migrations/operations/models.py#L508-L511
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/sklearn/mixture/base.py
python
_check_X
(X, n_components=None, n_features=None)
return X
Check the input data X. Parameters ---------- X : array-like, shape (n_samples, n_features) n_components : int Returns ------- X : array, shape (n_samples, n_features)
Check the input data X.
[ "Check", "the", "input", "data", "X", "." ]
def _check_X(X, n_components=None, n_features=None): """Check the input data X. Parameters ---------- X : array-like, shape (n_samples, n_features) n_components : int Returns ------- X : array, shape (n_samples, n_features) """ X = check_array(X, dtype=[np.float64, np.float32]) if n_components is not None and X.shape[0] < n_components: raise ValueError('Expected n_samples >= n_components ' 'but got n_components = %d, n_samples = %d' % (n_components, X.shape[0])) if n_features is not None and X.shape[1] != n_features: raise ValueError("Expected the input data X have %d features, " "but got %d features" % (n_features, X.shape[1])) return X
[ "def", "_check_X", "(", "X", ",", "n_components", "=", "None", ",", "n_features", "=", "None", ")", ":", "X", "=", "check_array", "(", "X", ",", "dtype", "=", "[", "np", ".", "float64", ",", "np", ".", "float32", "]", ")", "if", "n_components", "is...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/sklearn/mixture/base.py#L41-L63
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/lib2to3/fixer_util.py
python
in_special_context
(node)
return False
Returns true if node is in an environment where all that is required of it is being itterable (ie, it doesn't matter if it returns a list or an itterator). See test_map_nochange in test_fixers.py for some examples and tests.
Returns true if node is in an environment where all that is required of it is being itterable (ie, it doesn't matter if it returns a list or an itterator). See test_map_nochange in test_fixers.py for some examples and tests.
[ "Returns", "true", "if", "node", "is", "in", "an", "environment", "where", "all", "that", "is", "required", "of", "it", "is", "being", "itterable", "(", "ie", "it", "doesn", "t", "matter", "if", "it", "returns", "a", "list", "or", "an", "itterator", ")...
def in_special_context(node): """ Returns true if node is in an environment where all that is required of it is being itterable (ie, it doesn't matter if it returns a list or an itterator). See test_map_nochange in test_fixers.py for some examples and tests. """ global p0, p1, p2, pats_built if not pats_built: p1 = patcomp.compile_pattern(p1) p0 = patcomp.compile_pattern(p0) p2 = patcomp.compile_pattern(p2) pats_built = True patterns = [p0, p1, p2] for pattern, parent in zip(patterns, attr_chain(node, "parent")): results = {} if pattern.match(parent, results) and results["node"] is node: return True return False
[ "def", "in_special_context", "(", "node", ")", ":", "global", "p0", ",", "p1", ",", "p2", ",", "pats_built", "if", "not", "pats_built", ":", "p1", "=", "patcomp", ".", "compile_pattern", "(", "p1", ")", "p0", "=", "patcomp", ".", "compile_pattern", "(", ...
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/lib2to3/fixer_util.py#L208-L225
NeuromorphicProcessorProject/snn_toolbox
a85ada7b5d060500703285ef8a68f06ea1ffda65
snntoolbox/parsing/utils.py
python
AbstractModelParser.evaluate
(self, batch_size, num_to_test, x_test=None, y_test=None, dataflow=None)
return score
Evaluate parsed Keras model. Can use either numpy arrays ``x_test, y_test`` containing the test samples, or generate them with a dataflow (``keras.ImageDataGenerator.flow_from_directory`` object). Parameters ---------- batch_size: int Batch size num_to_test: int Number of samples to test x_test: Optional[np.ndarray] y_test: Optional[np.ndarray] dataflow: keras.ImageDataGenerator.flow_from_directory
Evaluate parsed Keras model.
[ "Evaluate", "parsed", "Keras", "model", "." ]
def evaluate(self, batch_size, num_to_test, x_test=None, y_test=None, dataflow=None): """Evaluate parsed Keras model. Can use either numpy arrays ``x_test, y_test`` containing the test samples, or generate them with a dataflow (``keras.ImageDataGenerator.flow_from_directory`` object). Parameters ---------- batch_size: int Batch size num_to_test: int Number of samples to test x_test: Optional[np.ndarray] y_test: Optional[np.ndarray] dataflow: keras.ImageDataGenerator.flow_from_directory """ assert (x_test is not None and y_test is not None or dataflow is not None), "No testsamples provided." if x_test is not None: score = self.parsed_model.evaluate(x_test, y_test, batch_size, verbose=0) else: steps = int(num_to_test / batch_size) score = self.parsed_model.evaluate(dataflow, steps=steps) print("Top-1 accuracy: {:.2%}".format(score[1])) print("Top-5 accuracy: {:.2%}\n".format(score[2])) return score
[ "def", "evaluate", "(", "self", ",", "batch_size", ",", "num_to_test", ",", "x_test", "=", "None", ",", "y_test", "=", "None", ",", "dataflow", "=", "None", ")", ":", "assert", "(", "x_test", "is", "not", "None", "and", "y_test", "is", "not", "None", ...
https://github.com/NeuromorphicProcessorProject/snn_toolbox/blob/a85ada7b5d060500703285ef8a68f06ea1ffda65/snntoolbox/parsing/utils.py#L831-L867
googleapis/python-ndb
e780c81cde1016651afbfcad8180d9912722cf1b
google/cloud/ndb/_cache.py
python
_handle_transient_errors
(read=False)
return wrap
Decorator for global_XXX functions for handling transient errors. Will log as warning or reraise transient errors according to `strict_read` and `strict_write` attributes of the global cache and whether the operation is a read or a write. If in strict mode, will retry the wrapped function up to 5 times before reraising the transient error.
Decorator for global_XXX functions for handling transient errors.
[ "Decorator", "for", "global_XXX", "functions", "for", "handling", "transient", "errors", "." ]
def _handle_transient_errors(read=False): """Decorator for global_XXX functions for handling transient errors. Will log as warning or reraise transient errors according to `strict_read` and `strict_write` attributes of the global cache and whether the operation is a read or a write. If in strict mode, will retry the wrapped function up to 5 times before reraising the transient error. """ def wrap(wrapped): def retry(wrapped, transient_errors): @functools.wraps(wrapped) @tasklets.tasklet def retry_wrapper(key, *args, **kwargs): sleep_generator = core_retry.exponential_sleep_generator(0.1, 1) attempts = 5 for sleep_time in sleep_generator: # pragma: NO BRANCH # pragma is required because loop never exits normally, it only gets # raised out of. attempts -= 1 try: result = yield wrapped(key, *args, **kwargs) raise tasklets.Return(result) except transient_errors: if not attempts: raise yield tasklets.sleep(sleep_time) return retry_wrapper @functools.wraps(wrapped) @tasklets.tasklet def wrapper(key, *args, **kwargs): cache = _global_cache() is_read = read if not is_read: is_read = kwargs.get("read", False) strict = cache.strict_read if is_read else cache.strict_write if strict: function = retry(wrapped, cache.transient_errors) else: function = wrapped try: result = yield function(key, *args, **kwargs) raise tasklets.Return(result) except cache.transient_errors as error: if strict: raise if not getattr(error, "_ndb_warning_logged", False): # Same exception will be sent to every future in the batch. Only # need to log one warning, though. warnings.warn( "Error connecting to global cache: {}".format(error), RuntimeWarning, ) error._ndb_warning_logged = True raise tasklets.Return(None) return wrapper return wrap
[ "def", "_handle_transient_errors", "(", "read", "=", "False", ")", ":", "def", "wrap", "(", "wrapped", ")", ":", "def", "retry", "(", "wrapped", ",", "transient_errors", ")", ":", "@", "functools", ".", "wraps", "(", "wrapped", ")", "@", "tasklets", ".",...
https://github.com/googleapis/python-ndb/blob/e780c81cde1016651afbfcad8180d9912722cf1b/google/cloud/ndb/_cache.py#L136-L205
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/zipfile.py
python
ZipFile.printdir
(self)
Print a table of contents for the zip file.
Print a table of contents for the zip file.
[ "Print", "a", "table", "of", "contents", "for", "the", "zip", "file", "." ]
def printdir(self): """Print a table of contents for the zip file.""" print "%-46s %19s %12s" % ("File Name", "Modified ", "Size") for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6] print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)
[ "def", "printdir", "(", "self", ")", ":", "print", "\"%-46s %19s %12s\"", "%", "(", "\"File Name\"", ",", "\"Modified \"", ",", "\"Size\"", ")", "for", "zinfo", "in", "self", ".", "filelist", ":", "date", "=", "\"%d-%02d-%02d %02d:%02d:%02d\"", "%", "zinfo", ...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/zipfile.py#L884-L889
faucamp/python-gsmmodem
834c68b1387ca2c91e2210faa8f75526b39723b5
gsmmodem/pdu.py
python
_decodeTimestamp
(byteIter)
return datetime.strptime(dateStr[:-2], '%y%m%d%H%M%S').replace(tzinfo=SmsPduTzInfo(timeZoneStr))
Decodes a 7-octet timestamp
Decodes a 7-octet timestamp
[ "Decodes", "a", "7", "-", "octet", "timestamp" ]
def _decodeTimestamp(byteIter): """ Decodes a 7-octet timestamp """ dateStr = decodeSemiOctets(byteIter, 7) timeZoneStr = dateStr[-2:] return datetime.strptime(dateStr[:-2], '%y%m%d%H%M%S').replace(tzinfo=SmsPduTzInfo(timeZoneStr))
[ "def", "_decodeTimestamp", "(", "byteIter", ")", ":", "dateStr", "=", "decodeSemiOctets", "(", "byteIter", ",", "7", ")", "timeZoneStr", "=", "dateStr", "[", "-", "2", ":", "]", "return", "datetime", ".", "strptime", "(", "dateStr", "[", ":", "-", "2", ...
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/pdu.py#L494-L498
galaxyproject/galaxy
4c03520f05062e0f4a1b3655dc0b7452fda69943
lib/galaxy/webapps/util.py
python
wrap_if_allowed_or_fail
(app, stack, wrap, name=None, args=None, kwargs=None)
return wrap(app, *args, **kwargs)
Wrap the application with the given method if the application stack allows for it. Arguments are the same as for :func:`wrap_if_allowed`. Raises py:class:`MiddlewareWrapUnsupported` if the stack does not allow the middleware.
Wrap the application with the given method if the application stack allows for it.
[ "Wrap", "the", "application", "with", "the", "given", "method", "if", "the", "application", "stack", "allows", "for", "it", "." ]
def wrap_if_allowed_or_fail(app, stack, wrap, name=None, args=None, kwargs=None): """ Wrap the application with the given method if the application stack allows for it. Arguments are the same as for :func:`wrap_if_allowed`. Raises py:class:`MiddlewareWrapUnsupported` if the stack does not allow the middleware. """ name = name or wrap.__name__ if not stack.allowed_middleware(wrap): raise MiddlewareWrapUnsupported( "'%s' is enabled in your configuration but the %s application stack does not support it, this " "middleware has been disabled" % (name, stack.name)) args = args or [] kwargs = kwargs or {} log.debug("Enabling '%s' middleware", name) return wrap(app, *args, **kwargs)
[ "def", "wrap_if_allowed_or_fail", "(", "app", ",", "stack", ",", "wrap", ",", "name", "=", "None", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "name", "=", "name", "or", "wrap", ".", "__name__", "if", "not", "stack", ".", "allowed...
https://github.com/galaxyproject/galaxy/blob/4c03520f05062e0f4a1b3655dc0b7452fda69943/lib/galaxy/webapps/util.py#L33-L49
xonsh/xonsh
b76d6f994f22a4078f602f8b386f4ec280c8461f
xonsh/imphooks.py
python
XonshImportHook.find_spec
(self, fullname, path, target=None)
return spec
Finds the spec for a xonsh module if it exists.
Finds the spec for a xonsh module if it exists.
[ "Finds", "the", "spec", "for", "a", "xonsh", "module", "if", "it", "exists", "." ]
def find_spec(self, fullname, path, target=None): """Finds the spec for a xonsh module if it exists.""" dot = "." spec = None path = sys.path if path is None else path if dot not in fullname and dot not in path: path = [dot] + path name = fullname.rsplit(dot, 1)[-1] fname = name + ".xsh" for p in path: if not isinstance(p, str): continue if not os.path.isdir(p) or not os.access(p, os.R_OK): continue if fname not in {x.name for x in os.scandir(p)}: continue spec = ModuleSpec(fullname, self) self._filenames[fullname] = os.path.abspath(os.path.join(p, fname)) break return spec
[ "def", "find_spec", "(", "self", ",", "fullname", ",", "path", ",", "target", "=", "None", ")", ":", "dot", "=", "\".\"", "spec", "=", "None", "path", "=", "sys", ".", "path", "if", "path", "is", "None", "else", "path", "if", "dot", "not", "in", ...
https://github.com/xonsh/xonsh/blob/b76d6f994f22a4078f602f8b386f4ec280c8461f/xonsh/imphooks.py#L61-L80
Qidian213/deep_sort_yolov3
df913275777ecaee19b4a99ea1889ac6063c0a4b
deep_sort/nn_matching.py
python
NearestNeighborDistanceMetric.distance
(self, features, targets)
return cost_matrix
Compute distance between features and targets. Parameters ---------- features : ndarray An NxM matrix of N features of dimensionality M. targets : List[int] A list of targets to match the given `features` against. Returns ------- ndarray Returns a cost matrix of shape len(targets), len(features), where element (i, j) contains the closest squared distance between `targets[i]` and `features[j]`.
Compute distance between features and targets.
[ "Compute", "distance", "between", "features", "and", "targets", "." ]
def distance(self, features, targets): """Compute distance between features and targets. Parameters ---------- features : ndarray An NxM matrix of N features of dimensionality M. targets : List[int] A list of targets to match the given `features` against. Returns ------- ndarray Returns a cost matrix of shape len(targets), len(features), where element (i, j) contains the closest squared distance between `targets[i]` and `features[j]`. """ cost_matrix = np.zeros((len(targets), len(features))) for i, target in enumerate(targets): cost_matrix[i, :] = self._metric(self.samples[target], features) return cost_matrix
[ "def", "distance", "(", "self", ",", "features", ",", "targets", ")", ":", "cost_matrix", "=", "np", ".", "zeros", "(", "(", "len", "(", "targets", ")", ",", "len", "(", "features", ")", ")", ")", "for", "i", ",", "target", "in", "enumerate", "(", ...
https://github.com/Qidian213/deep_sort_yolov3/blob/df913275777ecaee19b4a99ea1889ac6063c0a4b/deep_sort/nn_matching.py#L156-L177
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/pandas/core/dtypes/common.py
python
is_categorical_dtype
(arr_or_dtype)
return CategoricalDtype.is_dtype(arr_or_dtype)
Check whether an array-like or dtype is of the Categorical dtype. Parameters ---------- arr_or_dtype : array-like The array-like or dtype to check. Returns ------- boolean : Whether or not the array-like or dtype is of the Categorical dtype. Examples -------- >>> is_categorical_dtype(object) False >>> is_categorical_dtype(CategoricalDtype()) True >>> is_categorical_dtype([1, 2, 3]) False >>> is_categorical_dtype(pd.Categorical([1, 2, 3])) True >>> is_categorical_dtype(pd.CategoricalIndex([1, 2, 3])) True
Check whether an array-like or dtype is of the Categorical dtype.
[ "Check", "whether", "an", "array", "-", "like", "or", "dtype", "is", "of", "the", "Categorical", "dtype", "." ]
def is_categorical_dtype(arr_or_dtype): """ Check whether an array-like or dtype is of the Categorical dtype. Parameters ---------- arr_or_dtype : array-like The array-like or dtype to check. Returns ------- boolean : Whether or not the array-like or dtype is of the Categorical dtype. Examples -------- >>> is_categorical_dtype(object) False >>> is_categorical_dtype(CategoricalDtype()) True >>> is_categorical_dtype([1, 2, 3]) False >>> is_categorical_dtype(pd.Categorical([1, 2, 3])) True >>> is_categorical_dtype(pd.CategoricalIndex([1, 2, 3])) True """ if arr_or_dtype is None: return False return CategoricalDtype.is_dtype(arr_or_dtype)
[ "def", "is_categorical_dtype", "(", "arr_or_dtype", ")", ":", "if", "arr_or_dtype", "is", "None", ":", "return", "False", "return", "CategoricalDtype", ".", "is_dtype", "(", "arr_or_dtype", ")" ]
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/core/dtypes/common.py#L472-L502
PytLab/VASPy
3650b3e07bcd722f9443ae1213ff4b8734c42ffa
vaspy/matstudio.py
python
XsdFile.get_name_info
(self)
获取文件中能量,力等数据.
获取文件中能量,力等数据.
[ "获取文件中能量,力等数据", "." ]
def get_name_info(self): """ 获取文件中能量,力等数据. """ # Get info string. info = None for elem in self.tree.iter("SymmetrySystem"): info = elem.attrib.get('Name') break if info is None: return # Get thermo data. fieldnames = ["energy", "force", "magnetism", "path"] try: for key, value in zip(fieldnames, info.split()): if key != "path": data = float(value.split(':')[-1].strip()) else: data = value.split(":")[-1].strip() setattr(self, key, data) except: # Set default values. self.force, self.energy, self.magnetism = 0.0, 0.0, 0.0 msg = "No data info in Name property '{}'".format(info) self.__logger.warning(msg) finally: self.path = getcwd()
[ "def", "get_name_info", "(", "self", ")", ":", "# Get info string.", "info", "=", "None", "for", "elem", "in", "self", ".", "tree", ".", "iter", "(", "\"SymmetrySystem\"", ")", ":", "info", "=", "elem", ".", "attrib", ".", "get", "(", "'Name'", ")", "b...
https://github.com/PytLab/VASPy/blob/3650b3e07bcd722f9443ae1213ff4b8734c42ffa/vaspy/matstudio.py#L206-L234
git-cola/git-cola
b48b8028e0c3baf47faf7b074b9773737358163d
cola/models/prefs.py
python
SetConfig.__init__
(self, model, source, config, value)
[]
def __init__(self, model, source, config, value): self.source = source self.config = config self.value = value self.old_value = None self.model = model
[ "def", "__init__", "(", "self", ",", "model", ",", "source", ",", "config", ",", "value", ")", ":", "self", ".", "source", "=", "source", "self", ".", "config", "=", "config", "self", ".", "value", "=", "value", "self", ".", "old_value", "=", "None",...
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/models/prefs.py#L245-L250
mtianyan/FlaskMovie
75158aa7bab6104cfb22ff4953fb5306dfe9cec9
app/admin/views.py
python
user_del
(id=None)
return redirect(url_for('admin.user_list', page=from_page))
删除会员
删除会员
[ "删除会员" ]
def user_del(id=None): """ 删除会员 """ # 因为删除当前页。假如是最后一页,这一页已经不见了。回不到。 from_page = int(request.args.get('fp')) - 1 # 此处考虑全删完了,没法前挪的情况,0被视为false if not from_page: from_page = 1 user = User.query.get_or_404(int(id)) db.session.delete(user) db.session.commit() flash("删除会员成功!", "ok") return redirect(url_for('admin.user_list', page=from_page))
[ "def", "user_del", "(", "id", "=", "None", ")", ":", "# 因为删除当前页。假如是最后一页,这一页已经不见了。回不到。", "from_page", "=", "int", "(", "request", ".", "args", ".", "get", "(", "'fp'", ")", ")", "-", "1", "# 此处考虑全删完了,没法前挪的情况,0被视为false", "if", "not", "from_page", ":", "from_pa...
https://github.com/mtianyan/FlaskMovie/blob/75158aa7bab6104cfb22ff4953fb5306dfe9cec9/app/admin/views.py#L483-L496
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twill/twill/other_packages/pyparsing.py
python
downcaseTokens
(s,l,t)
return map( str.lower, t )
Helper parse action to convert tokens to lower case.
Helper parse action to convert tokens to lower case.
[ "Helper", "parse", "action", "to", "convert", "tokens", "to", "lower", "case", "." ]
def downcaseTokens(s,l,t): """Helper parse action to convert tokens to lower case.""" return map( str.lower, t )
[ "def", "downcaseTokens", "(", "s", ",", "l", ",", "t", ")", ":", "return", "map", "(", "str", ".", "lower", ",", "t", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twill/twill/other_packages/pyparsing.py#L2421-L2423
r0x0r/pywebview
7641414db75542958d1d1158b903576aafebd47c
webview/wsgi.py
python
StaticContentsApp.no_permissions
(self, environ, start_response)
return do_403(environ, start_response)
Handle if we can't open the file
Handle if we can't open the file
[ "Handle", "if", "we", "can", "t", "open", "the", "file" ]
def no_permissions(self, environ, start_response): """ Handle if we can't open the file """ return do_403(environ, start_response)
[ "def", "no_permissions", "(", "self", ",", "environ", ",", "start_response", ")", ":", "return", "do_403", "(", "environ", ",", "start_response", ")" ]
https://github.com/r0x0r/pywebview/blob/7641414db75542958d1d1158b903576aafebd47c/webview/wsgi.py#L193-L197
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
21-async/mojifinder/bottle.py
python
BaseRequest.method
(self)
return self.environ.get('REQUEST_METHOD', 'GET').upper()
The ``REQUEST_METHOD`` value as an uppercase string.
The ``REQUEST_METHOD`` value as an uppercase string.
[ "The", "REQUEST_METHOD", "value", "as", "an", "uppercase", "string", "." ]
def method(self): ''' The ``REQUEST_METHOD`` value as an uppercase string. ''' return self.environ.get('REQUEST_METHOD', 'GET').upper()
[ "def", "method", "(", "self", ")", ":", "return", "self", ".", "environ", ".", "get", "(", "'REQUEST_METHOD'", ",", "'GET'", ")", ".", "upper", "(", ")" ]
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/21-async/mojifinder/bottle.py#L1039-L1041
facebookresearch/pytext
1a4e184b233856fcfb9997d74f167cbf5bbbfb8d
pytext/data/data_structures/annotation.py
python
Node.list_nonTerminals
(self)
return non_terminals
Returns all Intent and Slot nodes subordinate to this node
Returns all Intent and Slot nodes subordinate to this node
[ "Returns", "all", "Intent", "and", "Slot", "nodes", "subordinate", "to", "this", "node" ]
def list_nonTerminals(self): """ Returns all Intent and Slot nodes subordinate to this node """ non_terminals = [] for child in self.children: if type(child) != Root and type(child) != Token: non_terminals.append(child) non_terminals += child.list_nonTerminals() return non_terminals
[ "def", "list_nonTerminals", "(", "self", ")", ":", "non_terminals", "=", "[", "]", "for", "child", "in", "self", ".", "children", ":", "if", "type", "(", "child", ")", "!=", "Root", "and", "type", "(", "child", ")", "!=", "Token", ":", "non_terminals",...
https://github.com/facebookresearch/pytext/blob/1a4e184b233856fcfb9997d74f167cbf5bbbfb8d/pytext/data/data_structures/annotation.py#L256-L265
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/metadata.py
python
LegacyMetadata.__init__
(self, path=None, fileobj=None, mapping=None, scheme='default')
[]
def __init__(self, path=None, fileobj=None, mapping=None, scheme='default'): if [path, fileobj, mapping].count(None) < 2: raise TypeError('path, fileobj and mapping are exclusive') self._fields = {} self.requires_files = [] self._dependencies = None self.scheme = scheme if path is not None: self.read(path) elif fileobj is not None: self.read_file(fileobj) elif mapping is not None: self.update(mapping) self.set_metadata_version()
[ "def", "__init__", "(", "self", ",", "path", "=", "None", ",", "fileobj", "=", "None", ",", "mapping", "=", "None", ",", "scheme", "=", "'default'", ")", ":", "if", "[", "path", ",", "fileobj", ",", "mapping", "]", ".", "count", "(", "None", ")", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/distlib/metadata.py#L248-L262
dropbox/nautilus-dropbox
e5dd94738b096c1d7c131365e99b19c9daf0de29
rst2man.py
python
Table.append_cell
(self, cell_lines)
cell_lines is an array of lines
cell_lines is an array of lines
[ "cell_lines", "is", "an", "array", "of", "lines" ]
def append_cell(self, cell_lines): """cell_lines is an array of lines""" self._rows[-1].append(cell_lines) if len(self._coldefs) < len(self._rows[-1]): self._coldefs.append('l')
[ "def", "append_cell", "(", "self", ",", "cell_lines", ")", ":", "self", ".", "_rows", "[", "-", "1", "]", ".", "append", "(", "cell_lines", ")", "if", "len", "(", "self", ".", "_coldefs", ")", "<", "len", "(", "self", ".", "_rows", "[", "-", "1",...
https://github.com/dropbox/nautilus-dropbox/blob/e5dd94738b096c1d7c131365e99b19c9daf0de29/rst2man.py#L141-L145
amphibian-dev/toad
3d932169112e8474525262af15440af7f2cf8029
toad/selection.py
python
drop_empty
(frame, threshold = 0.9, nan = None, return_drop = False, exclude = None)
return unpack_tuple(res)
drop columns by empty Args: frame (DataFrame): dataframe that will be used threshold (number): drop the features whose empty num is greater than threshold. if threshold is float, it will be use as percentage nan (any): values will be look like empty return_drop (bool): if need to return features' name who has been dropped exclude (array-like): list of feature names that will not be dropped Returns: DataFrame: selected dataframe array: list of feature names that has been dropped
drop columns by empty
[ "drop", "columns", "by", "empty" ]
def drop_empty(frame, threshold = 0.9, nan = None, return_drop = False, exclude = None): """drop columns by empty Args: frame (DataFrame): dataframe that will be used threshold (number): drop the features whose empty num is greater than threshold. if threshold is float, it will be use as percentage nan (any): values will be look like empty return_drop (bool): if need to return features' name who has been dropped exclude (array-like): list of feature names that will not be dropped Returns: DataFrame: selected dataframe array: list of feature names that has been dropped """ cols = frame.columns.copy() if exclude is not None: cols = cols.drop(exclude) if threshold < 1: threshold = len(frame) * threshold drop_list = [] for col in cols: series = frame[col] if nan is not None: series = series.replace(nan, np.nan) n = series.isnull().sum() if n > threshold: drop_list.append(col) r = frame.drop(columns = drop_list) res = (r,) if return_drop: res += (np.array(drop_list),) return unpack_tuple(res)
[ "def", "drop_empty", "(", "frame", ",", "threshold", "=", "0.9", ",", "nan", "=", "None", ",", "return_drop", "=", "False", ",", "exclude", "=", "None", ")", ":", "cols", "=", "frame", ".", "columns", ".", "copy", "(", ")", "if", "exclude", "is", "...
https://github.com/amphibian-dev/toad/blob/3d932169112e8474525262af15440af7f2cf8029/toad/selection.py#L225-L265
aws-samples/aws-glue-samples
13c21776350ca7996c086fb8a5bf6dfaf386054c
utilities/Hive_metastore_migration/src/hive_metastore_migration.py
python
append
(l, elem)
return l
Append list with element and return the list modified
Append list with element and return the list modified
[ "Append", "list", "with", "element", "and", "return", "the", "list", "modified" ]
def append(l, elem): """Append list with element and return the list modified""" if elem is not None: l.append(elem) return l
[ "def", "append", "(", "l", ",", "elem", ")", ":", "if", "elem", "is", "not", "None", ":", "l", ".", "append", "(", "elem", ")", "return", "l" ]
https://github.com/aws-samples/aws-glue-samples/blob/13c21776350ca7996c086fb8a5bf6dfaf386054c/utilities/Hive_metastore_migration/src/hive_metastore_migration.py#L141-L145
linuxscout/mishkal
4f4ae0ebc2d6acbeb3de3f0303151ec7b54d2f76
interfaces/web/lib/paste/wsgilib.py
python
catch_errors
(application, environ, start_response, error_callback, ok_callback=None)
Runs the application, and returns the application iterator (which should be passed upstream). If an error occurs then error_callback will be called with exc_info as its sole argument. If no errors occur and ok_callback is given, then it will be called with no arguments.
Runs the application, and returns the application iterator (which should be passed upstream). If an error occurs then error_callback will be called with exc_info as its sole argument. If no errors occur and ok_callback is given, then it will be called with no arguments.
[ "Runs", "the", "application", "and", "returns", "the", "application", "iterator", "(", "which", "should", "be", "passed", "upstream", ")", ".", "If", "an", "error", "occurs", "then", "error_callback", "will", "be", "called", "with", "exc_info", "as", "its", ...
def catch_errors(application, environ, start_response, error_callback, ok_callback=None): """ Runs the application, and returns the application iterator (which should be passed upstream). If an error occurs then error_callback will be called with exc_info as its sole argument. If no errors occur and ok_callback is given, then it will be called with no arguments. """ try: app_iter = application(environ, start_response) except: error_callback(sys.exc_info()) raise if type(app_iter) in (list, tuple): # These won't produce exceptions if ok_callback: ok_callback() return app_iter else: return _wrap_app_iter(app_iter, error_callback, ok_callback)
[ "def", "catch_errors", "(", "application", ",", "environ", ",", "start_response", ",", "error_callback", ",", "ok_callback", "=", "None", ")", ":", "try", ":", "app_iter", "=", "application", "(", "environ", ",", "start_response", ")", "except", ":", "error_ca...
https://github.com/linuxscout/mishkal/blob/4f4ae0ebc2d6acbeb3de3f0303151ec7b54d2f76/interfaces/web/lib/paste/wsgilib.py#L170-L189
lbryio/torba
190304344c0ff68f8a24cf50272307a11bf7f62b
torba/server/coins.py
python
Monoeci.header_hash
(cls, header)
return x11_hash.getPoWHash(header)
Given a header return the hash.
Given a header return the hash.
[ "Given", "a", "header", "return", "the", "hash", "." ]
def header_hash(cls, header): """Given a header return the hash.""" import x11_hash return x11_hash.getPoWHash(header)
[ "def", "header_hash", "(", "cls", ",", "header", ")", ":", "import", "x11_hash", "return", "x11_hash", ".", "getPoWHash", "(", "header", ")" ]
https://github.com/lbryio/torba/blob/190304344c0ff68f8a24cf50272307a11bf7f62b/torba/server/coins.py#L2049-L2052
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
ST_DM/KDD2021-MSTPAC/code/ST-PAC/datasets/datasets_factory.py
python
DatasetsFactory.get_dataset
(cls, name)
return cls.datasets.get(name, None)
get class type with class name
get class type with class name
[ "get", "class", "type", "with", "class", "name" ]
def get_dataset(cls, name): """ get class type with class name """ return cls.datasets.get(name, None)
[ "def", "get_dataset", "(", "cls", ",", "name", ")", ":", "return", "cls", ".", "datasets", ".", "get", "(", "name", ",", "None", ")" ]
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/ST_DM/KDD2021-MSTPAC/code/ST-PAC/datasets/datasets_factory.py#L53-L57
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/core/typeconv/castgraph.py
python
TypeGraph.safe
(self, a, b)
[]
def safe(self, a, b): self.insert_rule(a, b, Conversion.safe)
[ "def", "safe", "(", "self", ",", "a", ",", "b", ")", ":", "self", ".", "insert_rule", "(", "a", ",", "b", ",", "Conversion", ".", "safe", ")" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/core/typeconv/castgraph.py#L128-L129
kozec/sc-controller
ce92c773b8b26f6404882e9209aff212c4053170
scc/lib/enum.py
python
EnumMeta.__bool__
(cls)
return True
classes/types should always be True.
classes/types should always be True.
[ "classes", "/", "types", "should", "always", "be", "True", "." ]
def __bool__(cls): """ classes/types should always be True. """ return True
[ "def", "__bool__", "(", "cls", ")", ":", "return", "True" ]
https://github.com/kozec/sc-controller/blob/ce92c773b8b26f6404882e9209aff212c4053170/scc/lib/enum.py#L356-L360
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/xml/dom/expatbuilder.py
python
ExpatBuilder.parseString
(self, string)
return doc
Parse a document from a string, returning the document node.
Parse a document from a string, returning the document node.
[ "Parse", "a", "document", "from", "a", "string", "returning", "the", "document", "node", "." ]
def parseString(self, string): """Parse a document from a string, returning the document node.""" parser = self.getParser() try: parser.Parse(string, True) self._setup_subset(string) except ParseEscape: pass doc = self.document self.reset() self._parser = None return doc
[ "def", "parseString", "(", "self", ",", "string", ")", ":", "parser", "=", "self", ".", "getParser", "(", ")", "try", ":", "parser", ".", "Parse", "(", "string", ",", "True", ")", "self", ".", "_setup_subset", "(", "string", ")", "except", "ParseEscape...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/xml/dom/expatbuilder.py#L219-L230
joe42/CloudFusion
c4b94124e74a81e0634578c7754d62160081f7a1
cloudfusion/third_party/requests_1_2_3/requests/cookies.py
python
RequestsCookieJar.update
(self, other)
Updates this jar with cookies from another CookieJar or dict-like
Updates this jar with cookies from another CookieJar or dict-like
[ "Updates", "this", "jar", "with", "cookies", "from", "another", "CookieJar", "or", "dict", "-", "like" ]
def update(self, other): """Updates this jar with cookies from another CookieJar or dict-like""" if isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(cookie) else: super(RequestsCookieJar, self).update(other)
[ "def", "update", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "cookielib", ".", "CookieJar", ")", ":", "for", "cookie", "in", "other", ":", "self", ".", "set_cookie", "(", "cookie", ")", "else", ":", "super", "(", "Requ...
https://github.com/joe42/CloudFusion/blob/c4b94124e74a81e0634578c7754d62160081f7a1/cloudfusion/third_party/requests_1_2_3/requests/cookies.py#L261-L267
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/hqcase/views.py
python
case_api
(request, domain, case_id=None)
return JsonResponse({'error': "Request method not allowed"}, status=405)
[]
def case_api(request, domain, case_id=None): if request.method == 'GET' and case_id: return _handle_individual_get(request, case_id) if request.method == 'GET' and not case_id: return _handle_list_view(request) if request.method == 'POST' and not case_id: return _handle_case_update(request) if request.method == 'PUT' and case_id: return _handle_case_update(request, case_id) return JsonResponse({'error': "Request method not allowed"}, status=405)
[ "def", "case_api", "(", "request", ",", "domain", ",", "case_id", "=", "None", ")", ":", "if", "request", ".", "method", "==", "'GET'", "and", "case_id", ":", "return", "_handle_individual_get", "(", "request", ",", "case_id", ")", "if", "request", ".", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/hqcase/views.py#L87-L96
HypothesisWorks/hypothesis
d1bfc4acc86899caa7a40f892322e1a69fbf36f4
hypothesis-python/src/hypothesis/internal/charmap.py
python
as_general_categories
(cats, name="cats")
return tuple(c for c in cs if c in out)
Return a tuple of Unicode categories in a normalised order. This function expands one-letter designations of a major class to include all subclasses: >>> as_general_categories(['N']) ('Nd', 'Nl', 'No') See section 4.5 of the Unicode standard for more on classes: https://www.unicode.org/versions/Unicode10.0.0/ch04.pdf If the collection ``cats`` includes any elements that do not represent a major class or a class with subclass, a deprecation warning is raised.
Return a tuple of Unicode categories in a normalised order.
[ "Return", "a", "tuple", "of", "Unicode", "categories", "in", "a", "normalised", "order", "." ]
def as_general_categories(cats, name="cats"): """Return a tuple of Unicode categories in a normalised order. This function expands one-letter designations of a major class to include all subclasses: >>> as_general_categories(['N']) ('Nd', 'Nl', 'No') See section 4.5 of the Unicode standard for more on classes: https://www.unicode.org/versions/Unicode10.0.0/ch04.pdf If the collection ``cats`` includes any elements that do not represent a major class or a class with subclass, a deprecation warning is raised. """ if cats is None: return None major_classes = ("L", "M", "N", "P", "S", "Z", "C") cs = categories() out = set(cats) for c in cats: if c in major_classes: out.discard(c) out.update(x for x in cs if x.startswith(c)) elif c not in cs: raise InvalidArgument( f"In {name}={cats!r}, {c!r} is not a valid Unicode category." ) return tuple(c for c in cs if c in out)
[ "def", "as_general_categories", "(", "cats", ",", "name", "=", "\"cats\"", ")", ":", "if", "cats", "is", "None", ":", "return", "None", "major_classes", "=", "(", "\"L\"", ",", "\"M\"", ",", "\"N\"", ",", "\"P\"", ",", "\"S\"", ",", "\"Z\"", ",", "\"C\...
https://github.com/HypothesisWorks/hypothesis/blob/d1bfc4acc86899caa7a40f892322e1a69fbf36f4/hypothesis-python/src/hypothesis/internal/charmap.py#L118-L146
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
sensorClientTemplate/lib/globalData/baseObjects.py
python
LocalObject.deepcopy
(obj)
This function copies all attributes of the given object to a new object. :param obj: :return: object of this class
This function copies all attributes of the given object to a new object. :param obj: :return: object of this class
[ "This", "function", "copies", "all", "attributes", "of", "the", "given", "object", "to", "a", "new", "object", ".", ":", "param", "obj", ":", ":", "return", ":", "object", "of", "this", "class" ]
def deepcopy(obj): """ This function copies all attributes of the given object to a new object. :param obj: :return: object of this class """ raise NotImplementedError("Abstract class.")
[ "def", "deepcopy", "(", "obj", ")", ":", "raise", "NotImplementedError", "(", "\"Abstract class.\"", ")" ]
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/sensorClientTemplate/lib/globalData/baseObjects.py#L31-L37
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/locations/forms.py
python
LocationForm.get_allowed_types
(domain, parent)
return list(LocationType.objects .filter(domain=domain, parent_type=parent_type) .all())
[]
def get_allowed_types(domain, parent): parent_type = parent.location_type if parent else None return list(LocationType.objects .filter(domain=domain, parent_type=parent_type) .all())
[ "def", "get_allowed_types", "(", "domain", ",", "parent", ")", ":", "parent_type", "=", "parent", ".", "location_type", "if", "parent", "else", "None", "return", "list", "(", "LocationType", ".", "objects", ".", "filter", "(", "domain", "=", "domain", ",", ...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/locations/forms.py#L269-L274
INK-USC/KagNet
b386661ac5841774b9d17cc132e991a7bef3c5ef
baselines/pytorch-pretrained-BERT/pytorch_pretrained_bert/modeling_gpt2.py
python
GPT2PreTrainedModel.__init__
(self, config, *inputs, **kwargs)
[]
def __init__(self, config, *inputs, **kwargs): super(GPT2PreTrainedModel, self).__init__() if not isinstance(config, GPT2Config): raise ValueError( "Parameter config in `{}(config)` should be an instance of class `GPT2Config`. " "To create a model from a pretrained model use " "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format( self.__class__.__name__, self.__class__.__name__ ) ) self.config = config
[ "def", "__init__", "(", "self", ",", "config", ",", "*", "inputs", ",", "*", "*", "kwargs", ")", ":", "super", "(", "GPT2PreTrainedModel", ",", "self", ")", ".", "__init__", "(", ")", "if", "not", "isinstance", "(", "config", ",", "GPT2Config", ")", ...
https://github.com/INK-USC/KagNet/blob/b386661ac5841774b9d17cc132e991a7bef3c5ef/baselines/pytorch-pretrained-BERT/pytorch_pretrained_bert/modeling_gpt2.py#L332-L342
edgewall/trac
beb3e4eaf1e0a456d801a50a8614ecab06de29fc
trac/web/chrome.py
python
accesskey
(req, key)
return key if req.session.as_int('accesskeys') else None
Helper function for creating accesskey HTML attribute according to preference values
Helper function for creating accesskey HTML attribute according to preference values
[ "Helper", "function", "for", "creating", "accesskey", "HTML", "attribute", "according", "to", "preference", "values" ]
def accesskey(req, key): """Helper function for creating accesskey HTML attribute according to preference values""" return key if req.session.as_int('accesskeys') else None
[ "def", "accesskey", "(", "req", ",", "key", ")", ":", "return", "key", "if", "req", ".", "session", ".", "as_int", "(", "'accesskeys'", ")", "else", "None" ]
https://github.com/edgewall/trac/blob/beb3e4eaf1e0a456d801a50a8614ecab06de29fc/trac/web/chrome.py#L118-L121
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/phases/ceos.py
python
CEOSGas.fugacities_lowest_Gibbs
(self)
return [P*zs[i]*trunc_exp(lnphis[i]) for i in range(len(zs))]
[]
def fugacities_lowest_Gibbs(self): eos_mix = self.eos_mix P = self.P zs = self.zs try: if eos_mix.G_dep_g < eos_mix.G_dep_l: lnphis = eos_mix.fugacity_coefficients(eos_mix.Z_g) else: lnphis = eos_mix.fugacity_coefficients(eos_mix.Z_l) except: try: lnphis = eos_mix.fugacity_coefficients(eos_mix.Z_g) except: lnphis = eos_mix.fugacity_coefficients(eos_mix.Z_l) return [P*zs[i]*trunc_exp(lnphis[i]) for i in range(len(zs))]
[ "def", "fugacities_lowest_Gibbs", "(", "self", ")", ":", "eos_mix", "=", "self", ".", "eos_mix", "P", "=", "self", ".", "P", "zs", "=", "self", ".", "zs", "try", ":", "if", "eos_mix", ".", "G_dep_g", "<", "eos_mix", ".", "G_dep_l", ":", "lnphis", "="...
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/phases/ceos.py#L435-L449
JPStrydom/Crypto-Trading-Bot
94b5aab261a35d99bc044267baf4735f0ee3f89a
src/app.py
python
get_settings
()
return settings_content
[]
def get_settings(): settings_file_directory = "../database/settings.json" settings_template = { "sound": False, "tradeParameters": { "tickerInterval": "TICKER_INTERVAL", "buy": { "btcAmount": 0, "rsiThreshold": 0, "24HourVolumeThreshold": 0, "minimumUnitPrice": 0, "maxOpenTrades": 0 }, "sell": { "lossMarginThreshold": 0, "rsiThreshold": 0, "minProfitMarginThreshold": 0, "profitMarginThreshold": 0 } }, "pauseParameters": { "buy": { "rsiThreshold": 0, "pauseTime": 0 }, "sell": { "profitMarginThreshold": 0, "pauseTime": 0 }, "balance": { "pauseTime": 0 } } } settings_content = get_json_from_file(settings_file_directory, settings_template) if settings_content == settings_template: print("Please completed the `settings.json` file in your `database` directory") exit() return settings_content
[ "def", "get_settings", "(", ")", ":", "settings_file_directory", "=", "\"../database/settings.json\"", "settings_template", "=", "{", "\"sound\"", ":", "False", ",", "\"tradeParameters\"", ":", "{", "\"tickerInterval\"", ":", "\"TICKER_INTERVAL\"", ",", "\"buy\"", ":", ...
https://github.com/JPStrydom/Crypto-Trading-Bot/blob/94b5aab261a35d99bc044267baf4735f0ee3f89a/src/app.py#L41-L80
MaurizioFD/RecSys2019_DeepLearning_Evaluation
0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b
CNN_on_embeddings/IJCAI/CFM_github/LoadData.py
python
LoadData.construct_dataset
(self, X_user, X_item)
return Data_Dic
Construct dataset :param X_user: user structured data :param X_item: item structured data :return:
Construct dataset :param X_user: user structured data :param X_item: item structured data :return:
[ "Construct", "dataset", ":", "param", "X_user", ":", "user", "structured", "data", ":", "param", "X_item", ":", "item", "structured", "data", ":", "return", ":" ]
def construct_dataset(self, X_user, X_item): ''' Construct dataset :param X_user: user structured data :param X_item: item structured data :return: ''' Data_Dic = {} indexs = range(len(X_user)) Data_Dic['X_user'] = [X_user[i] for i in indexs] Data_Dic['X_item'] = [X_item[i] for i in indexs] return Data_Dic
[ "def", "construct_dataset", "(", "self", ",", "X_user", ",", "X_item", ")", ":", "Data_Dic", "=", "{", "}", "indexs", "=", "range", "(", "len", "(", "X_user", ")", ")", "Data_Dic", "[", "'X_user'", "]", "=", "[", "X_user", "[", "i", "]", "for", "i"...
https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation/blob/0fb6b7f5c396f8525316ed66cf9c9fdb03a5fa9b/CNN_on_embeddings/IJCAI/CFM_github/LoadData.py#L177-L188
snakeztc/NeuralDialog-ZSDG
1d1548457a16a2e07567dc8532ea8b2fba178540
zsdg/main.py
python
LossManager.add_loss
(self, loss)
[]
def add_loss(self, loss): for key, val in loss.items(): if val is not None and type(val) is not bool: self.losses[key].append(val.data[0])
[ "def", "add_loss", "(", "self", ",", "loss", ")", ":", "for", "key", ",", "val", "in", "loss", ".", "items", "(", ")", ":", "if", "val", "is", "not", "None", "and", "type", "(", "val", ")", "is", "not", "bool", ":", "self", ".", "losses", "[", ...
https://github.com/snakeztc/NeuralDialog-ZSDG/blob/1d1548457a16a2e07567dc8532ea8b2fba178540/zsdg/main.py#L51-L54
bashtage/linearmodels
9256269f01ff8c5f85e65342d66149a5636661b6
linearmodels/panel/model.py
python
PanelOLS.other_effects
(self)
return self._other_effects
Flag indicating whether other (generic) effects are included
Flag indicating whether other (generic) effects are included
[ "Flag", "indicating", "whether", "other", "(", "generic", ")", "effects", "are", "included" ]
def other_effects(self) -> bool: """Flag indicating whether other (generic) effects are included""" return self._other_effects
[ "def", "other_effects", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_other_effects" ]
https://github.com/bashtage/linearmodels/blob/9256269f01ff8c5f85e65342d66149a5636661b6/linearmodels/panel/model.py#L1313-L1315
slinderman/pyhawkes
0df433a40c5e6d8c1dcdb98ffc88fe3a403ac223
pyhawkes/standard_models.py
python
_NonlinearHawkesNodeBase.fit_with_bfgs
(self)
Fit the model with BFGS
Fit the model with BFGS
[ "Fit", "the", "model", "with", "BFGS" ]
def fit_with_bfgs(self): """ Fit the model with BFGS """ # If W_max is specified, set this as a bound # if self.W_max is not None: bnds = self.bias_bnds + self.weight_bnds * (self.K * self.B) \ if self.constrained else None # else: # bnds = [(None, None)] * (1 + self.K * self.B) itr = [0] def callback(w): if itr[0] % 10 == 0: print("Iteration: %03d\t LP: %.5f" % (itr[0], self.objective(w))) itr[0] = itr[0] + 1 itr[0] = 0 x0 = self.w res = minimize(self.objective, # Objective function x0, # Initial value jac=grad(self.objective), # Gradient of the objective bounds=bnds, # Bounds on x callback=callback) self.w = res.x
[ "def", "fit_with_bfgs", "(", "self", ")", ":", "# If W_max is specified, set this as a bound", "# if self.W_max is not None:", "bnds", "=", "self", ".", "bias_bnds", "+", "self", ".", "weight_bnds", "*", "(", "self", ".", "K", "*", "self", ".", "B", ")", "if", ...
https://github.com/slinderman/pyhawkes/blob/0df433a40c5e6d8c1dcdb98ffc88fe3a403ac223/pyhawkes/standard_models.py#L101-L126
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/ui/console/menu.py
python
menu._cmd_print
(self, params)
[]
def _cmd_print(self, params): if not len(params): raise BaseFrameworkException('Variable is expected') small_locals = {'kb': kb, 'w3af_core': self._w3af} small_globals = {} eval_variable = ' '.join(params) try: res = eval(eval_variable, small_globals, small_locals) except: om.out.console('Unknown variable.') else: pp = pprint.PrettyPrinter(indent=4) output = pp.pformat(res) om.out.console(output)
[ "def", "_cmd_print", "(", "self", ",", "params", ")", ":", "if", "not", "len", "(", "params", ")", ":", "raise", "BaseFrameworkException", "(", "'Variable is expected'", ")", "small_locals", "=", "{", "'kb'", ":", "kb", ",", "'w3af_core'", ":", "self", "."...
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/ui/console/menu.py#L210-L225
broadinstitute/viral-ngs
e144969e4c57060d53f38a4c3a270e8227feace1
file_utils.py
python
merge_tarballs
(out_tarball, in_tarballs, threads=None, extract_to_disk_path=None, pipe_hint_in=None, pipe_hint_out=None)
return 0
Merges separate tarballs into one tarball data can be piped in and/or out
Merges separate tarballs into one tarball data can be piped in and/or out
[ "Merges", "separate", "tarballs", "into", "one", "tarball", "data", "can", "be", "piped", "in", "and", "/", "or", "out" ]
def merge_tarballs(out_tarball, in_tarballs, threads=None, extract_to_disk_path=None, pipe_hint_in=None, pipe_hint_out=None): ''' Merges separate tarballs into one tarball data can be piped in and/or out ''' util.file.repack_tarballs(out_tarball, in_tarballs, threads=threads, extract_to_disk_path=extract_to_disk_path, pipe_hint_in=pipe_hint_in, pipe_hint_out=pipe_hint_out) return 0
[ "def", "merge_tarballs", "(", "out_tarball", ",", "in_tarballs", ",", "threads", "=", "None", ",", "extract_to_disk_path", "=", "None", ",", "pipe_hint_in", "=", "None", ",", "pipe_hint_out", "=", "None", ")", ":", "util", ".", "file", ".", "repack_tarballs", ...
https://github.com/broadinstitute/viral-ngs/blob/e144969e4c57060d53f38a4c3a270e8227feace1/file_utils.py#L22-L27
SymbiFlow/symbiflow-arch-defs
f38793112ff78a06de9f1e3269bd22543e29729f
utils/lib/parse_pcf.py
python
parse_simple_pcf
(f)
Parse a simple PCF file object and yield PcfIoConstraint objects.
Parse a simple PCF file object and yield PcfIoConstraint objects.
[ "Parse", "a", "simple", "PCF", "file", "object", "and", "yield", "PcfIoConstraint", "objects", "." ]
def parse_simple_pcf(f): """ Parse a simple PCF file object and yield PcfIoConstraint objects. """ for line_number, line in enumerate(f): line_number += 1 # Remove comments. args = re.sub(r"#.*", "", line.strip()).split() if not args: continue # Ignore arguments. args = [arg for arg in args if arg[0] != '-'] assert len(args) == 3, args if args[0] == 'set_io': yield PcfIoConstraint( net=args[1], pad=args[2], line_str=line.strip(), line_num=line_number, ) if args[0] == 'set_clk': yield PcfClkConstraint( pin=args[1], net=args[2], )
[ "def", "parse_simple_pcf", "(", "f", ")", ":", "for", "line_number", ",", "line", "in", "enumerate", "(", "f", ")", ":", "line_number", "+=", "1", "# Remove comments.", "args", "=", "re", ".", "sub", "(", "r\"#.*\"", ",", "\"\"", ",", "line", ".", "str...
https://github.com/SymbiFlow/symbiflow-arch-defs/blob/f38793112ff78a06de9f1e3269bd22543e29729f/utils/lib/parse_pcf.py#L15-L44
tenpy/tenpy
bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff
tenpy/models/model.py
python
NearestNeighborModel.bond_energies
(self, psi)
return psi.expectation_value(self.H_bond[1:], axes=(['p0', 'p1'], ['p0*', 'p1*']))
Calculate bond energies <psi|H_bond|psi>. Parameters ---------- psi : :class:`~tenpy.networks.mps.MPS` The MPS for which the bond energies should be calculated. Returns ------- E_bond : 1D ndarray List of bond energies: for finite bc, ``E_Bond[i]`` is the energy of bond ``i, i+1``. (i.e. we omit bond 0 between sites L-1 and 0); for infinite bc ``E_bond[i]`` is the energy of bond ``i-1, i``.
Calculate bond energies <psi|H_bond|psi>.
[ "Calculate", "bond", "energies", "<psi|H_bond|psi", ">", "." ]
def bond_energies(self, psi): """Calculate bond energies <psi|H_bond|psi>. Parameters ---------- psi : :class:`~tenpy.networks.mps.MPS` The MPS for which the bond energies should be calculated. Returns ------- E_bond : 1D ndarray List of bond energies: for finite bc, ``E_Bond[i]`` is the energy of bond ``i, i+1``. (i.e. we omit bond 0 between sites L-1 and 0); for infinite bc ``E_bond[i]`` is the energy of bond ``i-1, i``. """ if self.lat.bc_MPS == 'infinite': return psi.expectation_value(self.H_bond, axes=(['p0', 'p1'], ['p0*', 'p1*'])) # else return psi.expectation_value(self.H_bond[1:], axes=(['p0', 'p1'], ['p0*', 'p1*']))
[ "def", "bond_energies", "(", "self", ",", "psi", ")", ":", "if", "self", ".", "lat", ".", "bc_MPS", "==", "'infinite'", ":", "return", "psi", ".", "expectation_value", "(", "self", ".", "H_bond", ",", "axes", "=", "(", "[", "'p0'", ",", "'p1'", "]", ...
https://github.com/tenpy/tenpy/blob/bbdd3dbbdb511948eb0e6ba7ff619ac6ca657fff/tenpy/models/model.py#L266-L284
BigBrotherBot/big-brother-bot
848823c71413c86e7f1ff9584f43e08d40a7f2c0
b3/plugins/netblocker/__init__.py
python
NetblockerPlugin.onPlayerConnect
(self, event)
Examine players ip address and allow/deny connection.
Examine players ip address and allow/deny connection.
[ "Examine", "players", "ip", "address", "and", "allow", "/", "deny", "connection", "." ]
def onPlayerConnect(self, event): """ Examine players ip address and allow/deny connection. """ client = event.client self.debug('checking client: %s, name: %s, ip: %s, level: %s', client.cid, client.name, client.ip, client.maxLevel) # check the level of the connecting client before applying the filters if client.maxLevel > self._maxLevel: self.debug('%s is a higher level user, and allowed to connect', client.name) else: # transform ip address ip = netblock.convert(client.ip) # cycle through our blocks for block in self._blocks: # convert each block b = netblock.convert(block) # check if clients ip is in the disallowed range if b[0] <= ip[0] <= b[1]: # client not allowed to connect self.debug('client refused: %s (%s)', client.ip, client.name) client.kick("Netblocker: Client %s refused!" % client.name)
[ "def", "onPlayerConnect", "(", "self", ",", "event", ")", ":", "client", "=", "event", ".", "client", "self", ".", "debug", "(", "'checking client: %s, name: %s, ip: %s, level: %s'", ",", "client", ".", "cid", ",", "client", ".", "name", ",", "client", ".", ...
https://github.com/BigBrotherBot/big-brother-bot/blob/848823c71413c86e7f1ff9584f43e08d40a7f2c0/b3/plugins/netblocker/__init__.py#L77-L98
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/ma/core.py
python
MaskedArray.__ne__
(self, other)
return check
Check whether other doesn't equal self elementwise
Check whether other doesn't equal self elementwise
[ "Check", "whether", "other", "doesn", "t", "equal", "self", "elementwise" ]
def __ne__(self, other): "Check whether other doesn't equal self elementwise" if self is masked: return masked omask = getattr(other, '_mask', nomask) if omask is nomask: check = ndarray.__ne__(self.filled(0), other) try: check = check.view(type(self)) check._mask = self._mask except AttributeError: # In case check is a boolean (or a numpy.bool) return check else: odata = filled(other, 0) check = ndarray.__ne__(self.filled(0), odata).view(type(self)) if self._mask is nomask: check._mask = omask else: mask = mask_or(self._mask, omask) if mask.dtype.names: if mask.size > 1: axis = 1 else: axis = None try: mask = mask.view((bool_, len(self.dtype))).all(axis) except ValueError: mask = np.all([[f[n].all() for n in mask.dtype.names] for f in mask], axis=axis) check._mask = mask return check
[ "def", "__ne__", "(", "self", ",", "other", ")", ":", "if", "self", "is", "masked", ":", "return", "masked", "omask", "=", "getattr", "(", "other", ",", "'_mask'", ",", "nomask", ")", "if", "omask", "is", "nomask", ":", "check", "=", "ndarray", ".", ...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/numpy-1.10.0.dev0_046311a-py3.3-win-amd64.egg/numpy/ma/core.py#L3715-L3746
joelibaceta/video-to-ascii
906abad87083afbd2b13a44a31e614566446bbb9
video_to_ascii/render_strategy/image_processor.py
python
colorize_char
(char, ansi_color)
return str_colorized
Get an appropriate char of brightness from a rgb color
Get an appropriate char of brightness from a rgb color
[ "Get", "an", "appropriate", "char", "of", "brightness", "from", "a", "rgb", "color" ]
def colorize_char(char, ansi_color): """ Get an appropriate char of brightness from a rgb color """ str_colorized = colorize(char, ansi=ansi_color) return str_colorized
[ "def", "colorize_char", "(", "char", ",", "ansi_color", ")", ":", "str_colorized", "=", "colorize", "(", "char", ",", "ansi", "=", "ansi_color", ")", "return", "str_colorized" ]
https://github.com/joelibaceta/video-to-ascii/blob/906abad87083afbd2b13a44a31e614566446bbb9/video_to_ascii/render_strategy/image_processor.py#L21-L26
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/qt_frame.py
python
LeoQtBody.hideCanvas
(self, event=None)
Hide canvas pane.
Hide canvas pane.
[ "Hide", "canvas", "pane", "." ]
def hideCanvas(self, event=None): """Hide canvas pane.""" c, d = self.c, self.editorWrappers wrapper = c.frame.body.wrapper w = wrapper.widget name = w.leo_name assert name assert wrapper == d.get(name), 'wrong wrapper' assert g.isTextWrapper(wrapper), wrapper assert g.isTextWidget(w), w if len(list(d.keys())) <= 1: return # At present, can not delete the first column. if name == '1': g.warning('can not delete leftmost editor') return # # Actually delete the widget. del d[name] f = c.frame.top.leo_body_inner_frame layout = f.layout() for z in (w, w.leo_label): if z: self.unpackWidget(layout, z) # # Select another editor. w.leo_label = None new_wrapper = list(d.values())[0] self.numberOfEditors -= 1 if self.numberOfEditors == 1: w = new_wrapper.widget if w.leo_label: self.unpackWidget(layout, w.leo_label) w.leo_label = None self.selectEditor(new_wrapper)
[ "def", "hideCanvas", "(", "self", ",", "event", "=", "None", ")", ":", "c", ",", "d", "=", "self", ".", "c", ",", "self", ".", "editorWrappers", "wrapper", "=", "c", ".", "frame", ".", "body", ".", "wrapper", "w", "=", "wrapper", ".", "widget", "...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/qt_frame.py#L2017-L2051
bytedance/byteps
d0bcf1a87ee87539ceb29bcc976d4da063ffc47b
launcher/dist_launcher.py
python
start_ssh
(prog, node, port, username, fname)
return thread
[]
def start_ssh(prog, node, port, username, fname): def run(prog): subprocess.check_call(prog, shell=True) dirname = 'sshlog' if not os.path.exists(dirname): os.mkdir(dirname) pname = dirname + '/' + fname if username is not None: prog = 'ssh -o StrictHostKeyChecking=no ' + ' -l ' + username \ + ' ' + node + ' -p ' + port + ' \'' + prog + '\'' \ + ' > ' + pname + '.stdout' + ' 2>' + pname + '.stderr&' else: prog = 'ssh -o StrictHostKeyChecking=no ' + node + ' -p ' + port + ' \'' + prog + '\'' \ + ' > ' + pname + '.stdout' + ' 2>' + pname + '.stderr&' thread = Thread(target=run, args=(prog,)) thread.setDaemon(True) thread.start() return thread
[ "def", "start_ssh", "(", "prog", ",", "node", ",", "port", ",", "username", ",", "fname", ")", ":", "def", "run", "(", "prog", ")", ":", "subprocess", ".", "check_call", "(", "prog", ",", "shell", "=", "True", ")", "dirname", "=", "'sshlog'", "if", ...
https://github.com/bytedance/byteps/blob/d0bcf1a87ee87539ceb29bcc976d4da063ffc47b/launcher/dist_launcher.py#L55-L75
SamSchott/maestral
a32653bac7b5a76cb326d4fd5a4fb2c11f19a2fc
src/maestral/client.py
python
DropboxClient.remove
(self, dbx_path: str, **kwargs)
Removes a file / folder from Dropbox. :param dbx_path: Path to file on Dropbox. :param kwargs: Keyword arguments for the Dropbox API files_delete_v2 endpoint. :returns: Metadata of deleted item.
Removes a file / folder from Dropbox.
[ "Removes", "a", "file", "/", "folder", "from", "Dropbox", "." ]
def remove(self, dbx_path: str, **kwargs) -> files.Metadata: """ Removes a file / folder from Dropbox. :param dbx_path: Path to file on Dropbox. :param kwargs: Keyword arguments for the Dropbox API files_delete_v2 endpoint. :returns: Metadata of deleted item. """ with convert_api_errors(dbx_path=dbx_path): res = self.dbx.files_delete_v2(dbx_path, **kwargs) return res.metadata
[ "def", "remove", "(", "self", ",", "dbx_path", ":", "str", ",", "*", "*", "kwargs", ")", "->", "files", ".", "Metadata", ":", "with", "convert_api_errors", "(", "dbx_path", "=", "dbx_path", ")", ":", "res", "=", "self", ".", "dbx", ".", "files_delete_v...
https://github.com/SamSchott/maestral/blob/a32653bac7b5a76cb326d4fd5a4fb2c11f19a2fc/src/maestral/client.py#L744-L755
beancount/fava
69614956d3c01074403af0a07ddbaa986cf602a0
src/fava/ext/portfolio_list/__init__.py
python
PortfolioList._account_metadata_pattern
(self, tree, metadata_key, pattern)
return title, portfolio_data
Returns portfolio info based on matching account open metadata. Args: tree: Ledger root tree node. metadata_key: Metadata key to match for in account open. pattern: Metadata value's regex pattern to match for. Return: Data structured for use with a querytable - (types, rows).
Returns portfolio info based on matching account open metadata.
[ "Returns", "portfolio", "info", "based", "on", "matching", "account", "open", "metadata", "." ]
def _account_metadata_pattern(self, tree, metadata_key, pattern): """ Returns portfolio info based on matching account open metadata. Args: tree: Ledger root tree node. metadata_key: Metadata key to match for in account open. pattern: Metadata value's regex pattern to match for. Return: Data structured for use with a querytable - (types, rows). """ title = ( "Accounts with '" + metadata_key + "' metadata matching: '" + pattern + "'" ) selected_accounts = [] regexer = re.compile(pattern) for entry in self.ledger.all_entries_by_type.Open: if (metadata_key in entry.meta) and ( regexer.match(entry.meta[metadata_key]) is not None ): selected_accounts.append(entry.account) selected_nodes = [tree[x] for x in selected_accounts] portfolio_data = self._portfolio_data(selected_nodes) return title, portfolio_data
[ "def", "_account_metadata_pattern", "(", "self", ",", "tree", ",", "metadata_key", ",", "pattern", ")", ":", "title", "=", "(", "\"Accounts with '\"", "+", "metadata_key", "+", "\"' metadata matching: '\"", "+", "pattern", "+", "\"'\"", ")", "selected_accounts", "...
https://github.com/beancount/fava/blob/69614956d3c01074403af0a07ddbaa986cf602a0/src/fava/ext/portfolio_list/__init__.py#L63-L91
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
pypy/objspace/std/unicodeobject.py
python
UnicodeDocstrings.upper
()
S.upper() -> unicode Return a copy of S converted to uppercase.
S.upper() -> unicode
[ "S", ".", "upper", "()", "-", ">", "unicode" ]
def upper(): """S.upper() -> unicode Return a copy of S converted to uppercase. """
[ "def", "upper", "(", ")", ":" ]
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/objspace/std/unicodeobject.py#L960-L964
emmetio/livestyle-sublime-old
c42833c046e9b2f53ebce3df3aa926528f5a33b5
lsutils/websockets.py
python
off
(name, callback=None)
[]
def off(name, callback=None): _dispatcher.off(name, callback)
[ "def", "off", "(", "name", ",", "callback", "=", "None", ")", ":", "_dispatcher", ".", "off", "(", "name", ",", "callback", ")" ]
https://github.com/emmetio/livestyle-sublime-old/blob/c42833c046e9b2f53ebce3df3aa926528f5a33b5/lsutils/websockets.py#L77-L78
PRBonn/bonnet
7bf03b06e48faec46d39ea6b4b4706a73ff6ce48
train_py/arch/abstract_net.py
python
AbstractNetwork.loss_f
(self, lbls_pl, logits_train, gamma_focal=2, w_t="log", w_d=1e-4)
Calculates the loss from the logits and the labels.
Calculates the loss from the logits and the labels.
[ "Calculates", "the", "loss", "from", "the", "logits", "and", "the", "labels", "." ]
def loss_f(self, lbls_pl, logits_train, gamma_focal=2, w_t="log", w_d=1e-4): """Calculates the loss from the logits and the labels. """ print("Defining loss function") with tf.variable_scope("loss"): lbls_resized = self.resize_label(lbls_pl) # Apply median freq balancing (median frec / freq(class)) w = np.empty(len(self.dataset.train.content)) if w_t == "log": # get the frequencies and weights for key in self.dataset.train.content: e = 1.02 # max weight = 50 f_c = self.dataset.train.content[key] w[self.DATA["label_remap"][key]] = 1 / np.log(f_c + e) print("\nWeights for loss function (1/log(frec(c)+e)):\n", w) elif w_t == "median_freq": # get the frequencies f = np.empty(len(self.dataset.train.content)) for key in self.dataset.train.content: e = 0.001 f_c = self.dataset.train.content[key] f[self.DATA["label_remap"][key]] = f_c w[self.DATA["label_remap"][key]] = 1 / (f_c + e) # calculate the median frequencies and normalize median_freq = np.median(f) print("\nFrequencies of classes:\n", f) print("\nMedian freq:\n", median_freq) print("\nWeights for loss function (1/frec(c)):\n", w) w = median_freq * w print("\nWeights for loss function (median frec/frec(c)):\n", w) else: print("Using natural weights, since no valid loss option was given.") w.fill(1.0) for key in self.dataset.train.content: if self.dataset.train.content[key] == float("inf"): w[self.DATA["label_remap"][key]] = 0 print("weights: ", w) # use class weights as tf constant w_tf = tf.constant(w, dtype=tf.float32, name='class_weights') w_mask = w.astype(np.bool).astype(np.float32) w_mask_tf = tf.constant(w_mask, dtype=tf.float32, name='class_weights_mask') # make logits softmax matrixes for loss loss_epsilon = tf.constant(value=1e-10) softmax = tf.nn.softmax(logits_train) softmax_mat = tf.reshape(softmax, (-1, self.num_classes)) zerohot_softmax_mat = 1 - softmax_mat # make the labels one-hot for the cross-entropy onehot_mat = tf.reshape(tf.one_hot(lbls_resized, self.num_classes), (-1, self.num_classes)) # make the zero hot to punish the false negatives, but ignore the # zero-weight classes masked_sum = tf.reduce_sum(onehot_mat * w_mask_tf, axis=1) zeros = onehot_mat * 0.0 zerohot_mat = tf.where(tf.less(masked_sum, 1e-5), x=zeros, y=1 - onehot_mat) # focal loss p and gamma gamma = np.full(onehot_mat.get_shape().as_list(), fill_value=gamma_focal) gamma_tf = tf.constant(gamma, dtype=tf.float32) focal_softmax = tf.pow(1 - softmax_mat, gamma_tf) * \ tf.log(softmax_mat + loss_epsilon) zerohot_focal_softmax = tf.pow(1 - zerohot_softmax_mat, gamma_tf) * \ tf.log(zerohot_softmax_mat + loss_epsilon) # calculate xentropy cross_entropy = - tf.reduce_sum(tf.multiply(focal_softmax * onehot_mat + zerohot_focal_softmax * zerohot_mat, w_tf), axis=[1]) loss = tf.reduce_mean(cross_entropy, name='xentropy_mean') # weight decay print("Weight decay: ", w_d) w_d_tf = tf.constant(w_d, dtype=tf.float32, name='weight_decay') variables = tf.trainable_variables(scope="model") for var in variables: if "weights" in var.name: loss += w_d_tf * tf.nn.l2_loss(var) return loss
[ "def", "loss_f", "(", "self", ",", "lbls_pl", ",", "logits_train", ",", "gamma_focal", "=", "2", ",", "w_t", "=", "\"log\"", ",", "w_d", "=", "1e-4", ")", ":", "print", "(", "\"Defining loss function\"", ")", "with", "tf", ".", "variable_scope", "(", "\"...
https://github.com/PRBonn/bonnet/blob/7bf03b06e48faec46d39ea6b4b4706a73ff6ce48/train_py/arch/abstract_net.py#L76-L164
NTMC-Community/MatchZoo
8a487ee5a574356fc91e4f48e219253dc11bcff2
matchzoo/preprocessors/diin_preprocessor.py
python
DIINPreprocessor.fit
(self, data_pack: DataPack, verbose: int = 1)
return self
Fit pre-processing context for transformation. :param data_pack: data_pack to be preprocessed. :param verbose: Verbosity. :return: class:'DIINPreprocessor' instance.
Fit pre-processing context for transformation.
[ "Fit", "pre", "-", "processing", "context", "for", "transformation", "." ]
def fit(self, data_pack: DataPack, verbose: int = 1): """ Fit pre-processing context for transformation. :param data_pack: data_pack to be preprocessed. :param verbose: Verbosity. :return: class:'DIINPreprocessor' instance. """ func = chain_transform(self._units) data_pack = data_pack.apply_on_text(func, mode='both', verbose=verbose) vocab_unit = build_vocab_unit(data_pack, verbose=verbose) vocab_size = len(vocab_unit.state['term_index']) self._context['vocab_unit'] = vocab_unit self._context['vocab_size'] = vocab_size self._context['embedding_input_dim'] = vocab_size data_pack = data_pack.apply_on_text( units.NgramLetter(ngram=1, reduce_dim=True).transform, mode='both', verbose=verbose) char_unit = build_vocab_unit(data_pack, verbose=verbose) self._context['char_unit'] = char_unit self._context['input_shapes'] = [ (self._fixed_length_left,), (self._fixed_length_right,), (self._fixed_length_left, self._fixed_length_word,), (self._fixed_length_right, self._fixed_length_word,), (self._fixed_length_left,), (self._fixed_length_right,) ] return self
[ "def", "fit", "(", "self", ",", "data_pack", ":", "DataPack", ",", "verbose", ":", "int", "=", "1", ")", ":", "func", "=", "chain_transform", "(", "self", ".", "_units", ")", "data_pack", "=", "data_pack", ".", "apply_on_text", "(", "func", ",", "mode"...
https://github.com/NTMC-Community/MatchZoo/blob/8a487ee5a574356fc91e4f48e219253dc11bcff2/matchzoo/preprocessors/diin_preprocessor.py#L72-L103
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1_limit_range_list.py
python
V1LimitRangeList.__eq__
(self, other)
return self.__dict__ == other.__dict__
Returns true if both objects are equal
Returns true if both objects are equal
[ "Returns", "true", "if", "both", "objects", "are", "equal" ]
def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, V1LimitRangeList): return False return self.__dict__ == other.__dict__
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "V1LimitRangeList", ")", ":", "return", "False", "return", "self", ".", "__dict__", "==", "other", ".", "__dict__" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1_limit_range_list.py#L184-L191
xjsender/haoide
717dd706db1169bfc41e818ac6fc6cd9a0aef12d
requests/packages/urllib3/response.py
python
HTTPResponse._flush_decoder
(self)
return b''
Flushes the decoder. Should only be called if the decoder is actually being used.
Flushes the decoder. Should only be called if the decoder is actually being used.
[ "Flushes", "the", "decoder", ".", "Should", "only", "be", "called", "if", "the", "decoder", "is", "actually", "being", "used", "." ]
def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b'') return buf + self._decoder.flush() return b''
[ "def", "_flush_decoder", "(", "self", ")", ":", "if", "self", ".", "_decoder", ":", "buf", "=", "self", ".", "_decoder", ".", "decompress", "(", "b''", ")", "return", "buf", "+", "self", ".", "_decoder", ".", "flush", "(", ")", "return", "b''" ]
https://github.com/xjsender/haoide/blob/717dd706db1169bfc41e818ac6fc6cd9a0aef12d/requests/packages/urllib3/response.py#L204-L213
GitGuardian/ggshield
94a1fa0f6402cd1df2dd3dbc5b932862e85f99e5
ggshield/git_shell.py
python
shell_split
(command: List[str], **kwargs: Any)
return shell(command, **kwargs).split("\n")
[]
def shell_split(command: List[str], **kwargs: Any) -> List[str]: return shell(command, **kwargs).split("\n")
[ "def", "shell_split", "(", "command", ":", "List", "[", "str", "]", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "List", "[", "str", "]", ":", "return", "shell", "(", "command", ",", "*", "*", "kwargs", ")", ".", "split", "(", "\"\\n\"", ")" ]
https://github.com/GitGuardian/ggshield/blob/94a1fa0f6402cd1df2dd3dbc5b932862e85f99e5/ggshield/git_shell.py#L106-L107
frescobaldi/frescobaldi
301cc977fc4ba7caa3df9e4bf905212ad5d06912
frescobaldi_app/gadgets/drag.py
python
Dragger.startDrag
(self, widget)
Reimplement to start a drag.
Reimplement to start a drag.
[ "Reimplement", "to", "start", "a", "drag", "." ]
def startDrag(self, widget): """Reimplement to start a drag."""
[ "def", "startDrag", "(", "self", ",", "widget", ")", ":" ]
https://github.com/frescobaldi/frescobaldi/blob/301cc977fc4ba7caa3df9e4bf905212ad5d06912/frescobaldi_app/gadgets/drag.py#L101-L102
cuthbertLab/music21
bd30d4663e52955ed922c10fdf541419d8c67671
music21/analysis/transposition.py
python
TranspositionChecker.getPitchesOfDistinctTranspositions
(self)
return allNormalOrderPitchTuples
Outputs pitch tuples for each distinct transposition (normal order). >>> pList = [pitch.Pitch('C4'), pitch.Pitch('E4'), pitch.Pitch('G#4')] >>> tc = analysis.transposition.TranspositionChecker(pList) >>> tc.getPitchesOfDistinctTranspositions() [(<music21.pitch.Pitch C>, <music21.pitch.Pitch E>, <music21.pitch.Pitch G#>), (<music21.pitch.Pitch C#>, <music21.pitch.Pitch F>, <music21.pitch.Pitch A>), (<music21.pitch.Pitch D>, <music21.pitch.Pitch F#>, <music21.pitch.Pitch A#>), (<music21.pitch.Pitch E->, <music21.pitch.Pitch G>, <music21.pitch.Pitch B>)]
Outputs pitch tuples for each distinct transposition (normal order).
[ "Outputs", "pitch", "tuples", "for", "each", "distinct", "transposition", "(", "normal", "order", ")", "." ]
def getPitchesOfDistinctTranspositions(self): ''' Outputs pitch tuples for each distinct transposition (normal order). >>> pList = [pitch.Pitch('C4'), pitch.Pitch('E4'), pitch.Pitch('G#4')] >>> tc = analysis.transposition.TranspositionChecker(pList) >>> tc.getPitchesOfDistinctTranspositions() [(<music21.pitch.Pitch C>, <music21.pitch.Pitch E>, <music21.pitch.Pitch G#>), (<music21.pitch.Pitch C#>, <music21.pitch.Pitch F>, <music21.pitch.Pitch A>), (<music21.pitch.Pitch D>, <music21.pitch.Pitch F#>, <music21.pitch.Pitch A#>), (<music21.pitch.Pitch E->, <music21.pitch.Pitch G>, <music21.pitch.Pitch B>)] ''' chords = self.getChordsOfDistinctTranspositions() allNormalOrderPitchTuples = [c.pitches for c in chords] return allNormalOrderPitchTuples
[ "def", "getPitchesOfDistinctTranspositions", "(", "self", ")", ":", "chords", "=", "self", ".", "getChordsOfDistinctTranspositions", "(", ")", "allNormalOrderPitchTuples", "=", "[", "c", ".", "pitches", "for", "c", "in", "chords", "]", "return", "allNormalOrderPitch...
https://github.com/cuthbertLab/music21/blob/bd30d4663e52955ed922c10fdf541419d8c67671/music21/analysis/transposition.py#L176-L190
HenriWahl/Nagstamon
16549c6860b51a93141d84881c6ad28c35d8581e
Nagstamon/Servers/Livestatus.py
python
LivestatusServer._update_object
(self, obj, data)
return result
populate the generic fields of obj (GenericHost or GenericService) from data.
populate the generic fields of obj (GenericHost or GenericService) from data.
[ "populate", "the", "generic", "fields", "of", "obj", "(", "GenericHost", "or", "GenericService", ")", "from", "data", "." ]
def _update_object(self, obj, data): """populate the generic fields of obj (GenericHost or GenericService) from data.""" result = obj result.server = self.name result.last_check = format_timestamp(data['last_check']) result.duration = duration(data['last_state_change']) result.attempt = data['current_attempt'] result.status_information = data['plugin_output'] result.passiveonly = False result.notifications_disabled = data['notifications_enabled'] != 1 result.flapping = data['is_flapping'] == 1 result.acknowledged = data['acknowledged'] == 1 result.scheduled_downtime = data['scheduled_downtime_depth'] == 1 if data['state'] == data['last_hard_state']: result.status_type = 'hard' else: result.status_type = 'soft' return result
[ "def", "_update_object", "(", "self", ",", "obj", ",", "data", ")", ":", "result", "=", "obj", "result", ".", "server", "=", "self", ".", "name", "result", ".", "last_check", "=", "format_timestamp", "(", "data", "[", "'last_check'", "]", ")", "result", ...
https://github.com/HenriWahl/Nagstamon/blob/16549c6860b51a93141d84881c6ad28c35d8581e/Nagstamon/Servers/Livestatus.py#L184-L202
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cbs/v20170312/models.py
python
AttachDetail.__init__
(self)
r""" :param InstanceId: 实例ID。 :type InstanceId: str :param AttachedDiskCount: 实例已挂载数据盘的数量。 :type AttachedDiskCount: int :param MaxAttachCount: 实例最大可挂载数据盘的数量。 :type MaxAttachCount: int
r""" :param InstanceId: 实例ID。 :type InstanceId: str :param AttachedDiskCount: 实例已挂载数据盘的数量。 :type AttachedDiskCount: int :param MaxAttachCount: 实例最大可挂载数据盘的数量。 :type MaxAttachCount: int
[ "r", ":", "param", "InstanceId", ":", "实例ID。", ":", "type", "InstanceId", ":", "str", ":", "param", "AttachedDiskCount", ":", "实例已挂载数据盘的数量。", ":", "type", "AttachedDiskCount", ":", "int", ":", "param", "MaxAttachCount", ":", "实例最大可挂载数据盘的数量。", ":", "type", "Max...
def __init__(self): r""" :param InstanceId: 实例ID。 :type InstanceId: str :param AttachedDiskCount: 实例已挂载数据盘的数量。 :type AttachedDiskCount: int :param MaxAttachCount: 实例最大可挂载数据盘的数量。 :type MaxAttachCount: int """ self.InstanceId = None self.AttachedDiskCount = None self.MaxAttachCount = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "InstanceId", "=", "None", "self", ".", "AttachedDiskCount", "=", "None", "self", ".", "MaxAttachCount", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cbs/v20170312/models.py#L79-L90
youfou/wxpy
ab63e12da822dc85615fa203e5be9fa28ae0b59f
wxpy/api/chats/chat.py
python
Chat.get_avatar
(self, save_path=None)
return self.bot.core.get_head_img(**kwargs)
获取头像 :param save_path: 保存路径(后缀通常为.jpg),若为 `None` 则返回字节数据
获取头像
[ "获取头像" ]
def get_avatar(self, save_path=None): """ 获取头像 :param save_path: 保存路径(后缀通常为.jpg),若为 `None` 则返回字节数据 """ logger.info('getting avatar of {}'.format(self)) from .group import Group from .member import Member from .friend import User if isinstance(self, Group): kwargs = dict(userName=None, chatroomUserName=self.user_name) elif isinstance(self, Member): kwargs = dict(userName=self.user_name, chatroomUserName=self.group.user_name) elif isinstance(self, User): kwargs = dict(userName=self.user_name, chatroomUserName=None) else: raise TypeError('expected `Chat`, got`{}`'.format(type(self))) kwargs.update(dict(picDir=save_path)) return self.bot.core.get_head_img(**kwargs)
[ "def", "get_avatar", "(", "self", ",", "save_path", "=", "None", ")", ":", "logger", ".", "info", "(", "'getting avatar of {}'", ".", "format", "(", "self", ")", ")", "from", ".", "group", "import", "Group", "from", ".", "member", "import", "Member", "fr...
https://github.com/youfou/wxpy/blob/ab63e12da822dc85615fa203e5be9fa28ae0b59f/wxpy/api/chats/chat.py#L310-L334