repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
ejeschke/ginga
ginga/rv/Control.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/rv/Control.py#L1464-L1501
def delete_channel(self, chname): """Delete a given channel from viewer.""" name = chname.lower() if len(self.channel_names) < 1: self.logger.error('Delete channel={0} failed. ' 'No channels left.'.format(chname)) return with self.lock: channel = self.channel[name] # Close local plugins open on this channel self.close_plugins(channel) try: idx = self.channel_names.index(chname) except ValueError: idx = 0 # Update the channels control self.channel_names.remove(channel.name) self.channel_names.sort() self.ds.remove_tab(chname) del self.channel[name] self.prefs.remove_settings('channel_' + chname) # pick new channel num_channels = len(self.channel_names) if num_channels > 0: if idx >= num_channels: idx = num_channels - 1 self.change_channel(self.channel_names[idx]) else: self.cur_channel = None self.make_gui_callback('delete-channel', channel)
[ "def", "delete_channel", "(", "self", ",", "chname", ")", ":", "name", "=", "chname", ".", "lower", "(", ")", "if", "len", "(", "self", ".", "channel_names", ")", "<", "1", ":", "self", ".", "logger", ".", "error", "(", "'Delete channel={0} failed. '", ...
Delete a given channel from viewer.
[ "Delete", "a", "given", "channel", "from", "viewer", "." ]
python
train
lpantano/seqcluster
seqcluster/libs/thinkbayes.py
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L538-L554
def Var(self, mu=None): """Computes the variance of a PMF. Args: mu: the point around which the variance is computed; if omitted, computes the mean Returns: float variance """ if mu is None: mu = self.Mean() var = 0.0 for x, p in self.d.iteritems(): var += p * (x - mu) ** 2 return var
[ "def", "Var", "(", "self", ",", "mu", "=", "None", ")", ":", "if", "mu", "is", "None", ":", "mu", "=", "self", ".", "Mean", "(", ")", "var", "=", "0.0", "for", "x", ",", "p", "in", "self", ".", "d", ".", "iteritems", "(", ")", ":", "var", ...
Computes the variance of a PMF. Args: mu: the point around which the variance is computed; if omitted, computes the mean Returns: float variance
[ "Computes", "the", "variance", "of", "a", "PMF", "." ]
python
train
collectiveacuity/labPack
labpack/platforms/docker.py
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/platforms/docker.py#L118-L156
def _validate_virtualbox(self): ''' a method to validate that virtualbox is running on Win 7/8 machines :return: boolean indicating whether virtualbox is running ''' # validate operating system if self.localhost.os.sysname != 'Windows': return False win_release = float(self.localhost.os.release) if win_release >= 10.0: return False # validate docker-machine installation from os import devnull from subprocess import call, check_output, STDOUT sys_command = 'docker-machine --help' try: check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8') except Exception as err: raise Exception('Docker requires docker-machine to run on Win7/8. GoTo: https://www.docker.com') # validate virtualbox is running sys_command = 'docker-machine status %s' % self.vbox try: vbox_status = check_output(sys_command, shell=True, stderr=open(devnull, 'wb')).decode('utf-8').replace('\n', '') except Exception as err: if not self.vbox: raise Exception('Docker requires VirtualBox to run on Win7/8. GoTo: https://www.virtualbox.org') elif self.vbox == "default": raise Exception('Virtualbox "default" not found. Container will not start without a valid virtualbox.') else: raise Exception('Virtualbox "%s" not found. Try using "default" instead.' % self.vbox) if 'Stopped' in vbox_status: raise Exception('Virtualbox "%s" is stopped. Try first running: docker-machine start %s' % (self.vbox, self.vbox)) return True
[ "def", "_validate_virtualbox", "(", "self", ")", ":", "# validate operating system\r", "if", "self", ".", "localhost", ".", "os", ".", "sysname", "!=", "'Windows'", ":", "return", "False", "win_release", "=", "float", "(", "self", ".", "localhost", ".", "os", ...
a method to validate that virtualbox is running on Win 7/8 machines :return: boolean indicating whether virtualbox is running
[ "a", "method", "to", "validate", "that", "virtualbox", "is", "running", "on", "Win", "7", "/", "8", "machines", ":", "return", ":", "boolean", "indicating", "whether", "virtualbox", "is", "running" ]
python
train
dmlc/gluon-nlp
scripts/bert/staticbert/static_bert.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/bert/staticbert/static_bert.py#L481-L512
def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model. """ outputs = [] seq_out, attention_out = self._encode_sequence(F, inputs, token_types, valid_length) outputs.append(seq_out) if self.encoder._output_all_encodings: assert isinstance(seq_out, list) output = seq_out[-1] else: output = seq_out if attention_out: outputs.append(attention_out) if self._use_pooler: pooled_out = self._apply_pooling(output) outputs.append(pooled_out) if self._use_classifier: next_sentence_classifier_out = self.classifier(pooled_out) outputs.append(next_sentence_classifier_out) if self._use_decoder: assert masked_positions is not None, \ 'masked_positions tensor is required for decoding masked language model' decoder_out = self._decode(output, masked_positions) outputs.append(decoder_out) return tuple(outputs) if len(outputs) > 1 else outputs[0]
[ "def", "hybrid_forward", "(", "self", ",", "F", ",", "inputs", ",", "token_types", ",", "valid_length", "=", "None", ",", "masked_positions", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "# pylint: disable=unused-argument", "outputs", "=", "[", "]", ...
Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model.
[ "Generate", "the", "representation", "given", "the", "inputs", "." ]
python
train
nugget/python-insteonplm
insteonplm/states/onOff.py
https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/states/onOff.py#L792-L828
def _create_set_property_msg(self, prop, cmd, val): """Create an extended message to set a property. Create an extended message with: cmd1: 0x2e cmd2: 0x00 flags: Direct Extended d1: group d2: cmd d3: val d4 - d14: 0x00 Parameters: prop: Property name to update cmd: Command value 0x02: on mask 0x03: off mask 0x04: x10 house code 0x05: ramp rate 0x06: on level 0x07: LED brightness 0x08: Non-Toggle mask 0x09: LED bit mask (Do not use in this class. Use LED class) 0x0a: X10 All bit mask 0x0c: Trigger group bit mask val: New property value """ user_data = Userdata({'d1': self.group, 'd2': cmd, 'd3': val}) msg = ExtendedSend(self._address, COMMAND_EXTENDED_GET_SET_0X2E_0X00, user_data) msg.set_checksum() self._set_sent_property(prop, val) return msg
[ "def", "_create_set_property_msg", "(", "self", ",", "prop", ",", "cmd", ",", "val", ")", ":", "user_data", "=", "Userdata", "(", "{", "'d1'", ":", "self", ".", "group", ",", "'d2'", ":", "cmd", ",", "'d3'", ":", "val", "}", ")", "msg", "=", "Exten...
Create an extended message to set a property. Create an extended message with: cmd1: 0x2e cmd2: 0x00 flags: Direct Extended d1: group d2: cmd d3: val d4 - d14: 0x00 Parameters: prop: Property name to update cmd: Command value 0x02: on mask 0x03: off mask 0x04: x10 house code 0x05: ramp rate 0x06: on level 0x07: LED brightness 0x08: Non-Toggle mask 0x09: LED bit mask (Do not use in this class. Use LED class) 0x0a: X10 All bit mask 0x0c: Trigger group bit mask val: New property value
[ "Create", "an", "extended", "message", "to", "set", "a", "property", "." ]
python
train
peepall/FancyLogger
FancyLogger/__init__.py
https://github.com/peepall/FancyLogger/blob/7f13f1397e76ed768fb6b6358194118831fafc6d/FancyLogger/__init__.py#L365-L374
def info(self, text): """ Posts an info message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time. Logger will redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw immediately (may produce flickering) then call 'flush' method. :param text: The text to log into file and console. """ self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.INFO)))
[ "def", "info", "(", "self", ",", "text", ")", ":", "self", ".", "queue", ".", "put", "(", "dill", ".", "dumps", "(", "LogMessageCommand", "(", "text", "=", "text", ",", "level", "=", "logging", ".", "INFO", ")", ")", ")" ]
Posts an info message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time. Logger will redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw immediately (may produce flickering) then call 'flush' method. :param text: The text to log into file and console.
[ "Posts", "an", "info", "message", "adding", "a", "timestamp", "and", "logging", "level", "to", "it", "for", "both", "file", "and", "console", "handlers", ".", "Logger", "uses", "a", "redraw", "rate", "because", "of", "console", "flickering", ".", "That", "...
python
train
dhermes/bezier
docs/make_images.py
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L677-L709
def curve_specialize(curve, new_curve): """Image for :meth`.Curve.specialize` docstring.""" if NO_IMAGES: return ax = curve.plot(256) interval = r"$\left[0, 1\right]$" line = ax.lines[-1] line.set_label(interval) color1 = line.get_color() new_curve.plot(256, ax=ax) interval = r"$\left[-\frac{1}{4}, \frac{3}{4}\right]$" line = ax.lines[-1] line.set_label(interval) ax.plot( curve._nodes[0, (0, -1)], curve._nodes[1, (0, -1)], color=color1, linestyle="None", marker="o", ) ax.plot( new_curve._nodes[0, (0, -1)], new_curve._nodes[1, (0, -1)], color=line.get_color(), linestyle="None", marker="o", ) ax.legend(loc="lower right", fontsize=12) ax.axis("scaled") ax.set_xlim(-0.375, 1.125) ax.set_ylim(-0.75, 0.625) save_image(ax.figure, "curve_specialize.png")
[ "def", "curve_specialize", "(", "curve", ",", "new_curve", ")", ":", "if", "NO_IMAGES", ":", "return", "ax", "=", "curve", ".", "plot", "(", "256", ")", "interval", "=", "r\"$\\left[0, 1\\right]$\"", "line", "=", "ax", ".", "lines", "[", "-", "1", "]", ...
Image for :meth`.Curve.specialize` docstring.
[ "Image", "for", ":", "meth", ".", "Curve", ".", "specialize", "docstring", "." ]
python
train
linkhub-sdk/popbill.py
popbill/taxinvoiceService.py
https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/taxinvoiceService.py#L287-L310
def cancelSend(self, CorpNum, MgtKeyType, MgtKey, Memo=None, UserID=None): """ 승인요청 취소 args CorpNum : 회원 사업자 번호 MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE'] MgtKey : 파트너 관리번호 Memo : 처리 메모 UserID : 팝빌 회원아이디 return 처리결과. consist of code and message raise PopbillException """ if MgtKeyType not in self.__MgtKeyTypes: raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.") if MgtKey == None or MgtKey == "": raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.") if Memo != None and Memo != '': postData = self._stringtify({"memo": Memo}) else: postData = '' return self._httppost('/Taxinvoice/' + MgtKeyType + "/" + MgtKey, postData, CorpNum, UserID, "CANCELSEND")
[ "def", "cancelSend", "(", "self", ",", "CorpNum", ",", "MgtKeyType", ",", "MgtKey", ",", "Memo", "=", "None", ",", "UserID", "=", "None", ")", ":", "if", "MgtKeyType", "not", "in", "self", ".", "__MgtKeyTypes", ":", "raise", "PopbillException", "(", "-",...
승인요청 취소 args CorpNum : 회원 사업자 번호 MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE'] MgtKey : 파트너 관리번호 Memo : 처리 메모 UserID : 팝빌 회원아이디 return 처리결과. consist of code and message raise PopbillException
[ "승인요청", "취소", "args", "CorpNum", ":", "회원", "사업자", "번호", "MgtKeyType", ":", "관리번호", "유형", "one", "of", "[", "SELL", "BUY", "TRUSTEE", "]", "MgtKey", ":", "파트너", "관리번호", "Memo", ":", "처리", "메모", "UserID", ":", "팝빌", "회원아이디", "return", "처리결과", ".", "...
python
train
zendesk/connect_python_sdk
outbound/__init__.py
https://github.com/zendesk/connect_python_sdk/blob/6d7c1a539dcf23c1b1942e9bf6c9084c929df7e6/outbound/__init__.py#L280-L372
def track(user_id, event, first_name=None, last_name=None, email=None, phone_number=None, apns_tokens=None, gcm_tokens=None, user_attributes=None, properties=None, on_error=None, on_success=None, timestamp=None): """ For any event you want to track, when a user triggers that event you would call this function. You can do an identify and track call simultaneously by including all the identifiable user information in the track call. :param str | number user_id: the id you user who triggered the event. :param str first_name: OPTIONAL the user's first name. :param str last_name: OPTIONAL the user's last name. :param str email: OPTIONAL the user's email address. :param str phone_number: OPTIONAL the user's phone number. :param str | list apns_tokens: OPTIONAL the device tokens for the user's iOS devices. If a single string is given it is put into a list. :param str | list gcm_tokens: OPTIONAL the device tokens for the user's Android devices. If a single string is given it is put into a list. :param dict user_attributes: An optional dictionary with any additional freeform attributes describing the user. :param dict properties: An optional dictionary with any properties that describe the event being track. Example: if the event were "added item to cart", you might include a properties named "item" that is the name of the item added to the cart. :param func on_error: An optional function to call in the event of an error. on_error callback should take 1 parameter which will be the error message. :param func on_success: An optional function to call if/when the API call succeeds. on_success callback takes no parameters. """ on_error = on_error or __on_error on_success = on_success or __on_success if not __is_init(): on_error(ERROR_INIT, __error_message(ERROR_INIT)) return if not isinstance(user_id, six.string_types + (Number,)): on_error(ERROR_USER_ID, __error_message(ERROR_USER_ID)) return if not isinstance(event, six.string_types): on_error(ERROR_EVENT_NAME, __error_message(ERROR_EVENT_NAME)) return data = dict(user_id=user_id, event=event) user = __user( first_name, last_name, email, phone_number, apns_tokens, gcm_tokens, user_attributes, None, None, None) if user: data['user'] = user if properties: if isinstance(properties, dict): if len(properties) > 0: data['properties'] = properties else: sys.stderr.write('Invalid event properties given. Expected dictionary. ' + 'Got %s' % type(properties).__name__) if timestamp: data['timestamp'] = timestamp else: data['timestamp'] = int(time.time()) try: resp = requests.post( "%s/track" % __BASE_URL, data=json.dumps(data), headers=__HEADERS, ) if resp.status_code >= 200 and resp.status_code < 400: on_success() else: on_error(ERROR_UNKNOWN, resp.text) except requests.exceptions.ConnectionError: on_error(ERROR_CONNECTION, __error_message(ERROR_CONNECTION))
[ "def", "track", "(", "user_id", ",", "event", ",", "first_name", "=", "None", ",", "last_name", "=", "None", ",", "email", "=", "None", ",", "phone_number", "=", "None", ",", "apns_tokens", "=", "None", ",", "gcm_tokens", "=", "None", ",", "user_attribut...
For any event you want to track, when a user triggers that event you would call this function. You can do an identify and track call simultaneously by including all the identifiable user information in the track call. :param str | number user_id: the id you user who triggered the event. :param str first_name: OPTIONAL the user's first name. :param str last_name: OPTIONAL the user's last name. :param str email: OPTIONAL the user's email address. :param str phone_number: OPTIONAL the user's phone number. :param str | list apns_tokens: OPTIONAL the device tokens for the user's iOS devices. If a single string is given it is put into a list. :param str | list gcm_tokens: OPTIONAL the device tokens for the user's Android devices. If a single string is given it is put into a list. :param dict user_attributes: An optional dictionary with any additional freeform attributes describing the user. :param dict properties: An optional dictionary with any properties that describe the event being track. Example: if the event were "added item to cart", you might include a properties named "item" that is the name of the item added to the cart. :param func on_error: An optional function to call in the event of an error. on_error callback should take 1 parameter which will be the error message. :param func on_success: An optional function to call if/when the API call succeeds. on_success callback takes no parameters.
[ "For", "any", "event", "you", "want", "to", "track", "when", "a", "user", "triggers", "that", "event", "you", "would", "call", "this", "function", "." ]
python
train
Nukesor/pueue
pueue/client/displaying.py
https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/client/displaying.py#L19-L105
def execute_status(args, root_dir=None): """Print the status of the daemon. This function displays the current status of the daemon as well as the whole queue and all available information about every entry in the queue. `terminaltables` is used to format and display the queue contents. `colorclass` is used to color format the various items in the queue. Args: root_dir (string): The path to the root directory the daemon is running in. """ status = command_factory('status')({}, root_dir=root_dir) # First rows, showing daemon status if status['status'] == 'running': status['status'] = Color('{autogreen}' + '{}'.format(status['status']) + '{/autogreen}') elif status['status'] in ['paused']: status['status'] = Color('{autoyellow}' + '{}'.format(status['status']) + '{/autoyellow}') print('Daemon: {}\n'.format(status['status'])) # Handle queue data data = status['data'] if isinstance(data, str): print(data) elif isinstance(data, dict): # Format incomming data to be compatible with Terminaltables formatted_data = [] formatted_data.append(['Index', 'Status', 'Code', 'Command', 'Path', 'Start', 'End']) for key, entry in sorted(data.items(), key=operator.itemgetter(0)): formatted_data.append( [ '#{}'.format(key), entry['status'], '{}'.format(entry['returncode']), entry['command'], entry['path'], entry['start'], entry['end'] ] ) # Create AsciiTable instance and define style table = AsciiTable(formatted_data) table.outer_border = False table.inner_column_border = False terminal_width = terminal_size() customWidth = table.column_widths # If the text is wider than the actual terminal size, we # compute a new size for the Command and Path column. if (reduce(lambda a, b: a+b, table.column_widths) + 10) > terminal_width[0]: # We have to subtract 14 because of table paddings left_space = math.floor((terminal_width[0] - customWidth[0] - customWidth[1] - customWidth[2] - customWidth[5] - customWidth[6] - 14)/2) if customWidth[3] < left_space: customWidth[4] = 2*left_space - customWidth[3] elif customWidth[4] < left_space: customWidth[3] = 2*left_space - customWidth[4] else: customWidth[3] = left_space customWidth[4] = left_space # Format long strings to match the console width for i, entry in enumerate(table.table_data): for j, string in enumerate(entry): max_width = customWidth[j] wrapped_string = '\n'.join(wrap(string, max_width)) if j == 1: if wrapped_string == 'done' or wrapped_string == 'running' or wrapped_string == 'paused': wrapped_string = Color('{autogreen}' + '{}'.format(wrapped_string) + '{/autogreen}') elif wrapped_string in ['queued', 'stashed']: wrapped_string = Color('{autoyellow}' + '{}'.format(wrapped_string) + '{/autoyellow}') elif wrapped_string in ['failed', 'stopping', 'killing']: wrapped_string = Color('{autored}' + '{}'.format(wrapped_string) + '{/autored}') elif j == 2: if wrapped_string == '0' and wrapped_string != 'Code': wrapped_string = Color('{autogreen}' + '{}'.format(wrapped_string) + '{/autogreen}') elif wrapped_string != '0' and wrapped_string != 'Code': wrapped_string = Color('{autored}' + '{}'.format(wrapped_string) + '{/autored}') table.table_data[i][j] = wrapped_string print(table.table) print('')
[ "def", "execute_status", "(", "args", ",", "root_dir", "=", "None", ")", ":", "status", "=", "command_factory", "(", "'status'", ")", "(", "{", "}", ",", "root_dir", "=", "root_dir", ")", "# First rows, showing daemon status", "if", "status", "[", "'status'", ...
Print the status of the daemon. This function displays the current status of the daemon as well as the whole queue and all available information about every entry in the queue. `terminaltables` is used to format and display the queue contents. `colorclass` is used to color format the various items in the queue. Args: root_dir (string): The path to the root directory the daemon is running in.
[ "Print", "the", "status", "of", "the", "daemon", "." ]
python
train
mardix/Juice
juice/plugins/maintenance_page/__init__.py
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/plugins/maintenance_page/__init__.py#L6-L33
def view(template=None): """ Create the Maintenance view Must be instantiated import maintenance_view MaintenanceView = maintenance_view() :param template_: The directory containing the view pages :return: """ if not template: template = "Juice/Plugin/MaintenancePage/index.html" class Maintenance(View): @classmethod def register(cls, app, **kwargs): super(cls, cls).register(app, **kwargs) if cls.get_config("APPLICATION_MAINTENANCE_ON"): app.logger.info("APPLICATION MAINTENANCE PAGE IS ON") @app.before_request def on_maintenance(): return cls.render_(layout_=template), 503 return Maintenance
[ "def", "view", "(", "template", "=", "None", ")", ":", "if", "not", "template", ":", "template", "=", "\"Juice/Plugin/MaintenancePage/index.html\"", "class", "Maintenance", "(", "View", ")", ":", "@", "classmethod", "def", "register", "(", "cls", ",", "app", ...
Create the Maintenance view Must be instantiated import maintenance_view MaintenanceView = maintenance_view() :param template_: The directory containing the view pages :return:
[ "Create", "the", "Maintenance", "view", "Must", "be", "instantiated" ]
python
train
flo-compbio/genometools
genometools/expression/matrix.py
https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/matrix.py#L426-L466
def read_tsv(cls, file_path: str, gene_table: ExpGeneTable = None, encoding: str = 'UTF-8', sep: str = '\t'): """Read expression matrix from a tab-delimited text file. Parameters ---------- file_path: str The path of the text file. gene_table: `ExpGeneTable` object, optional The set of valid genes. If given, the genes in the text file will be filtered against this set of genes. (None) encoding: str, optional The file encoding. ("UTF-8") sep: str, optional The separator. ("\t") Returns ------- `ExpMatrix` The expression matrix. """ # use pd.read_csv to parse the tsv file into a DataFrame matrix = cls(pd.read_csv(file_path, sep=sep, index_col=0, header=0, encoding=encoding)) # parse index column separately # (this seems to be the only way we can prevent pandas from converting # "nan" or "NaN" to floats in the index)['1_cell_306.120', '1_cell_086.024', '1_cell_168.103'] #ind = pd.read_csv(file_path, sep=sep, usecols=[0, ], header=0, # encoding=encoding, na_filter=False) ind = pd.read_csv(file_path, sep=sep, usecols=[0, ], header=None, skiprows=1, encoding=encoding, na_filter=False) matrix.index = ind.iloc[:, 0] matrix.index.name = 'Genes' if gene_table is not None: # filter genes matrix = matrix.filter_genes(gene_table.gene_names) return matrix
[ "def", "read_tsv", "(", "cls", ",", "file_path", ":", "str", ",", "gene_table", ":", "ExpGeneTable", "=", "None", ",", "encoding", ":", "str", "=", "'UTF-8'", ",", "sep", ":", "str", "=", "'\\t'", ")", ":", "# use pd.read_csv to parse the tsv file into a DataF...
Read expression matrix from a tab-delimited text file. Parameters ---------- file_path: str The path of the text file. gene_table: `ExpGeneTable` object, optional The set of valid genes. If given, the genes in the text file will be filtered against this set of genes. (None) encoding: str, optional The file encoding. ("UTF-8") sep: str, optional The separator. ("\t") Returns ------- `ExpMatrix` The expression matrix.
[ "Read", "expression", "matrix", "from", "a", "tab", "-", "delimited", "text", "file", "." ]
python
train
gbiggs/rtsprofile
rtsprofile/targets.py
https://github.com/gbiggs/rtsprofile/blob/fded6eddcb0b25fe9808b1b12336a4413ea00905/rtsprofile/targets.py#L303-L313
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a target execution context into this object. ''' super(TargetExecutionContext, self).parse_xml_node(node) if node.hasAttributeNS(RTS_NS, 'id'): self.id = node.getAttributeNS(RTS_NS, 'id') else: self.id = '' return self
[ "def", "parse_xml_node", "(", "self", ",", "node", ")", ":", "super", "(", "TargetExecutionContext", ",", "self", ")", ".", "parse_xml_node", "(", "node", ")", "if", "node", ".", "hasAttributeNS", "(", "RTS_NS", ",", "'id'", ")", ":", "self", ".", "id", ...
Parse an xml.dom Node object representing a target execution context into this object.
[ "Parse", "an", "xml", ".", "dom", "Node", "object", "representing", "a", "target", "execution", "context", "into", "this", "object", "." ]
python
train
rigetti/quantumflow
quantumflow/channels.py
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/channels.py#L170-L175
def join_channels(*channels: Channel) -> Channel: """Join two channels acting on different qubits into a single channel acting on all qubits""" vectors = [chan.vec for chan in channels] vec = reduce(outer_product, vectors) return Channel(vec.tensor, vec.qubits)
[ "def", "join_channels", "(", "*", "channels", ":", "Channel", ")", "->", "Channel", ":", "vectors", "=", "[", "chan", ".", "vec", "for", "chan", "in", "channels", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "return", "Channel", ...
Join two channels acting on different qubits into a single channel acting on all qubits
[ "Join", "two", "channels", "acting", "on", "different", "qubits", "into", "a", "single", "channel", "acting", "on", "all", "qubits" ]
python
train
Zimbra-Community/python-zimbra
pythonzimbra/communication.py
https://github.com/Zimbra-Community/python-zimbra/blob/8b839143c64b0507a30a9908ff39066ae4ef5d03/pythonzimbra/communication.py#L54-L84
def gen_request(self, request_type="json", token=None, set_batch=False, batch_onerror=None): """ Convenience method to quickly generate a token :param request_type: Type of request (defaults to json) :param token: Authentication token :param set_batch: Also set this request to batch mode? :param batch_onerror: Onerror-parameter for batch mode :return: The request """ if request_type == "json": local_request = RequestJson() elif request_type == "xml": local_request = RequestXml() else: raise UnknownRequestType() if token is not None: local_request.set_auth_token(token) if set_batch: local_request.enable_batch(batch_onerror) return local_request
[ "def", "gen_request", "(", "self", ",", "request_type", "=", "\"json\"", ",", "token", "=", "None", ",", "set_batch", "=", "False", ",", "batch_onerror", "=", "None", ")", ":", "if", "request_type", "==", "\"json\"", ":", "local_request", "=", "RequestJson",...
Convenience method to quickly generate a token :param request_type: Type of request (defaults to json) :param token: Authentication token :param set_batch: Also set this request to batch mode? :param batch_onerror: Onerror-parameter for batch mode :return: The request
[ "Convenience", "method", "to", "quickly", "generate", "a", "token" ]
python
train
lanpa/tensorboardX
examples/demo_caffe2.py
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L130-L133
def AddAccuracy(model, softmax, label): """Adds an accuracy op to the model""" accuracy = brew.accuracy(model, [softmax, label], "accuracy") return accuracy
[ "def", "AddAccuracy", "(", "model", ",", "softmax", ",", "label", ")", ":", "accuracy", "=", "brew", ".", "accuracy", "(", "model", ",", "[", "softmax", ",", "label", "]", ",", "\"accuracy\"", ")", "return", "accuracy" ]
Adds an accuracy op to the model
[ "Adds", "an", "accuracy", "op", "to", "the", "model" ]
python
train
sdss/sdss_access
python/sdss_access/sync/rsync.py
https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/sync/rsync.py#L28-L34
def remote(self, username=None, password=None, inquire=None): """ Configures remote access """ self.set_netloc(sdss=True) # simplifies things to have a single sdss machine in .netrc self.set_auth(username=username, password=password, inquire=inquire) self.set_netloc(dtn=not self.public) self.set_remote_base(scheme="rsync")
[ "def", "remote", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ",", "inquire", "=", "None", ")", ":", "self", ".", "set_netloc", "(", "sdss", "=", "True", ")", "# simplifies things to have a single sdss machine in .netrc", "self", "....
Configures remote access
[ "Configures", "remote", "access" ]
python
train
googledatalab/pydatalab
datalab/bigquery/_sampling.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_sampling.py#L74-L88
def sampling_query(sql, fields=None, count=5, sampling=None): """Returns a sampling query for the SQL object. Args: sql: the SQL object to sample fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to apply to the table. Returns: A SQL query string for sampling the input sql. """ if sampling is None: sampling = Sampling.default(count=count, fields=fields) return sampling(sql)
[ "def", "sampling_query", "(", "sql", ",", "fields", "=", "None", ",", "count", "=", "5", ",", "sampling", "=", "None", ")", ":", "if", "sampling", "is", "None", ":", "sampling", "=", "Sampling", ".", "default", "(", "count", "=", "count", ",", "field...
Returns a sampling query for the SQL object. Args: sql: the SQL object to sample fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to apply to the table. Returns: A SQL query string for sampling the input sql.
[ "Returns", "a", "sampling", "query", "for", "the", "SQL", "object", "." ]
python
train
adrn/gala
gala/potential/potential/util.py
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/potential/util.py#L18-L162
def from_equation(expr, vars, pars, name=None, hessian=False): r""" Create a potential class from an expression for the potential. .. note:: This utility requires having `Sympy <http://www.sympy.org/>`_ installed. .. warning:: These potentials are *not* pickle-able and cannot be written out to YAML files (using `~gala.potential.PotentialBase.save()`) Parameters ---------- expr : :class:`sympy.core.expr.Expr`, str Either a ``Sympy`` expression, or a string that can be converted to a ``Sympy`` expression. vars : iterable An iterable of variable names in the expression. pars : iterable An iterable of parameter names in the expression. name : str (optional) The name of the potential class returned. hessian : bool (optional) Generate a function to compute the Hessian. Returns ------- CustomPotential : `~gala.potential.PotentialBase` A potential class that represents the input equation. To instantiate the potential, use just like a normal class with parameters. Examples -------- Here we'll create a potential class for the harmonic oscillator potential, :math:`\Phi(x) = \frac{1}{2}\,k\,x^2`:: >>> Potential = from_equation("1/2*k*x**2", vars="x", pars="k", ... name='HarmonicOscillator') >>> p1 = Potential(k=1.) >>> p1 <HarmonicOscillatorPotential: k=1.00 (dimensionless)> The potential class (and object) is a fully-fledged subclass of `~gala.potential.PotentialBase` and therefore has many useful methods. For example, to integrate an orbit:: >>> orbit = p1.integrate_orbit([1.,0], dt=0.01, n_steps=1000) """ try: import sympy from sympy.utilities.lambdify import lambdify except ImportError: raise ImportError("sympy is required to use 'from_equation()' " "potential class creation.") # convert all input to Sympy objects expr = sympy.sympify(expr) vars = [sympy.sympify(v) for v in vars] var_names = [v.name for v in vars] pars = [sympy.sympify(p) for p in pars] par_names = [p.name for p in pars] ndim = len(vars) # Energy / value energyfunc = lambdify(vars + pars, expr, dummify=False, modules='numpy') # Gradient gradfuncs = [] for var in vars: gradfuncs.append(lambdify(vars + pars, sympy.diff(expr,var), dummify=False, modules='numpy')) class CustomPotential(PotentialBase): def __init__(self, units=None, **kwargs): for par in par_names: if par not in kwargs: raise ValueError("You must specify a value for " "parameter '{}'.".format(par)) super(CustomPotential,self).__init__(units=units, parameters=kwargs, ndim=ndim) def _energy(self, w, t=0.): kw = self.parameters.copy() for k,v in kw.items(): kw[k] = v.value for i,name in enumerate(var_names): kw[name] = w[:,i] return np.array(energyfunc(**kw)) def _gradient(self, w, t=0.): kw = self.parameters.copy() for k,v in kw.items(): kw[k] = v.value for i,name in enumerate(var_names): kw[name] = w[:,i] grad = np.vstack([f(**kw)[np.newaxis] for f in gradfuncs]) return grad.T if name is not None: # name = _classnamify(name) if "potential" not in name.lower(): name = name + "Potential" CustomPotential.__name__ = str(name) # Hessian if hessian: hessfuncs = [] for var1 in vars: for var2 in vars: hessfuncs.append(lambdify(vars + pars, sympy.diff(expr,var1,var2), dummify=False, modules='numpy')) def _hessian(self, w, t): kw = self.parameters.copy() for k,v in kw.items(): kw[k] = v.value for i,name in enumerate(var_names): kw[name] = w[:,i] # expand = [np.newaxis] * w[i].ndim # This ain't pretty, bub arrs = [] for f in hessfuncs: hess_arr = np.array(f(**kw)) if hess_arr.shape != w[:,i].shape: hess_arr = np.tile(hess_arr, reps=w[:,i].shape) arrs.append(hess_arr) hess = np.vstack(arrs) return hess.reshape((ndim,ndim,len(w[:,i]))) CustomPotential._hessian = _hessian CustomPotential.save = None return CustomPotential
[ "def", "from_equation", "(", "expr", ",", "vars", ",", "pars", ",", "name", "=", "None", ",", "hessian", "=", "False", ")", ":", "try", ":", "import", "sympy", "from", "sympy", ".", "utilities", ".", "lambdify", "import", "lambdify", "except", "ImportErr...
r""" Create a potential class from an expression for the potential. .. note:: This utility requires having `Sympy <http://www.sympy.org/>`_ installed. .. warning:: These potentials are *not* pickle-able and cannot be written out to YAML files (using `~gala.potential.PotentialBase.save()`) Parameters ---------- expr : :class:`sympy.core.expr.Expr`, str Either a ``Sympy`` expression, or a string that can be converted to a ``Sympy`` expression. vars : iterable An iterable of variable names in the expression. pars : iterable An iterable of parameter names in the expression. name : str (optional) The name of the potential class returned. hessian : bool (optional) Generate a function to compute the Hessian. Returns ------- CustomPotential : `~gala.potential.PotentialBase` A potential class that represents the input equation. To instantiate the potential, use just like a normal class with parameters. Examples -------- Here we'll create a potential class for the harmonic oscillator potential, :math:`\Phi(x) = \frac{1}{2}\,k\,x^2`:: >>> Potential = from_equation("1/2*k*x**2", vars="x", pars="k", ... name='HarmonicOscillator') >>> p1 = Potential(k=1.) >>> p1 <HarmonicOscillatorPotential: k=1.00 (dimensionless)> The potential class (and object) is a fully-fledged subclass of `~gala.potential.PotentialBase` and therefore has many useful methods. For example, to integrate an orbit:: >>> orbit = p1.integrate_orbit([1.,0], dt=0.01, n_steps=1000)
[ "r", "Create", "a", "potential", "class", "from", "an", "expression", "for", "the", "potential", "." ]
python
train
PyPSA/PyPSA
examples/scigrid-de/add_load_gen_trafos_to_scigrid.py
https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/examples/scigrid-de/add_load_gen_trafos_to_scigrid.py#L392-L406
def generate_dummy_graph(network): """Generate a dummy graph to feed to the FIAS libraries. It adds the "pos" attribute and removes the 380 kV duplicate buses when the buses have been split, so that all load and generation is attached to the 220kV bus.""" graph = pypsa.descriptors.OrderedGraph() graph.add_nodes_from([bus for bus in network.buses.index if bus not in buses_to_split]) #add positions to graph for voronoi cell computation for node in graph.nodes(): graph.node[node]["pos"] = np.array(network.buses.loc[node,["x","y"]],dtype=float) return graph
[ "def", "generate_dummy_graph", "(", "network", ")", ":", "graph", "=", "pypsa", ".", "descriptors", ".", "OrderedGraph", "(", ")", "graph", ".", "add_nodes_from", "(", "[", "bus", "for", "bus", "in", "network", ".", "buses", ".", "index", "if", "bus", "n...
Generate a dummy graph to feed to the FIAS libraries. It adds the "pos" attribute and removes the 380 kV duplicate buses when the buses have been split, so that all load and generation is attached to the 220kV bus.
[ "Generate", "a", "dummy", "graph", "to", "feed", "to", "the", "FIAS", "libraries", ".", "It", "adds", "the", "pos", "attribute", "and", "removes", "the", "380", "kV", "duplicate", "buses", "when", "the", "buses", "have", "been", "split", "so", "that", "a...
python
train
miquelo/resort
packages/resort/component/glassfish.py
https://github.com/miquelo/resort/blob/097a25d3257c91a75c194fd44c2797ab356f85dd/packages/resort/component/glassfish.py#L315-L334
def connector_connection_pool(self, name, res_adapter_name, conn_def_name, props): """ Domain connector connection pool. :param str name: Resource name. :param str res_adapter_name: Resource adapter name. :param str conn_def_name: Resource connection definition name. :param dict props: Connection pool properties. :rtype: ConnectorConnectionPool """ return ConnectorConnectionPool(self.__endpoint, name, res_adapter_name, conn_def_name, props)
[ "def", "connector_connection_pool", "(", "self", ",", "name", ",", "res_adapter_name", ",", "conn_def_name", ",", "props", ")", ":", "return", "ConnectorConnectionPool", "(", "self", ".", "__endpoint", ",", "name", ",", "res_adapter_name", ",", "conn_def_name", ",...
Domain connector connection pool. :param str name: Resource name. :param str res_adapter_name: Resource adapter name. :param str conn_def_name: Resource connection definition name. :param dict props: Connection pool properties. :rtype: ConnectorConnectionPool
[ "Domain", "connector", "connection", "pool", ".", ":", "param", "str", "name", ":", "Resource", "name", ".", ":", "param", "str", "res_adapter_name", ":", "Resource", "adapter", "name", ".", ":", "param", "str", "conn_def_name", ":", "Resource", "connection", ...
python
train
ajyoon/blur
blur/soft.py
https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/soft.py#L102-L117
def with_random_weights(cls, options): """ Initialize from a list of options with random weights. The weights assigned to each object are uniformally random integers between ``1`` and ``len(options)`` Args: options (list): The list of options of any type this object can return with the ``get()`` method. Returns: SoftOptions: A newly constructed instance """ return cls([(value, random.randint(1, len(options))) for value in options])
[ "def", "with_random_weights", "(", "cls", ",", "options", ")", ":", "return", "cls", "(", "[", "(", "value", ",", "random", ".", "randint", "(", "1", ",", "len", "(", "options", ")", ")", ")", "for", "value", "in", "options", "]", ")" ]
Initialize from a list of options with random weights. The weights assigned to each object are uniformally random integers between ``1`` and ``len(options)`` Args: options (list): The list of options of any type this object can return with the ``get()`` method. Returns: SoftOptions: A newly constructed instance
[ "Initialize", "from", "a", "list", "of", "options", "with", "random", "weights", "." ]
python
train
zero-os/0-core
client/py-client/zeroos/core0/client/client.py
https://github.com/zero-os/0-core/blob/69f6ce845ab8b8ad805a79a415227e7ac566c218/client/py-client/zeroos/core0/client/client.py#L1810-L1826
def umount(self, source): """ Unmount partion :param source: Full partition path like /dev/sda1 """ args = { 'source': source, } self._umount_chk.check(args) response = self._client.raw('disk.umount', args) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to umount partition: %s' % result.stderr)
[ "def", "umount", "(", "self", ",", "source", ")", ":", "args", "=", "{", "'source'", ":", "source", ",", "}", "self", ".", "_umount_chk", ".", "check", "(", "args", ")", "response", "=", "self", ".", "_client", ".", "raw", "(", "'disk.umount'", ",", ...
Unmount partion :param source: Full partition path like /dev/sda1
[ "Unmount", "partion", ":", "param", "source", ":", "Full", "partition", "path", "like", "/", "dev", "/", "sda1" ]
python
train
apache/incubator-mxnet
example/rnn/large_word_lm/model.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rnn/large_word_lm/model.py#L130-L147
def generate_samples(label, num_splits, sampler): """ Split labels into `num_splits` and generate candidates based on log-uniform distribution. """ def listify(x): return x if isinstance(x, list) else [x] label_splits = listify(label.split(num_splits, axis=0)) prob_samples = [] prob_targets = [] samples = [] for label_split in label_splits: label_split_2d = label_split.reshape((-1,1)) sampled_value = sampler.draw(label_split_2d) sampled_classes, exp_cnt_true, exp_cnt_sampled = sampled_value samples.append(sampled_classes.astype(np.float32)) prob_targets.append(exp_cnt_true.astype(np.float32).reshape((-1,1))) prob_samples.append(exp_cnt_sampled.astype(np.float32)) return samples, prob_samples, prob_targets
[ "def", "generate_samples", "(", "label", ",", "num_splits", ",", "sampler", ")", ":", "def", "listify", "(", "x", ")", ":", "return", "x", "if", "isinstance", "(", "x", ",", "list", ")", "else", "[", "x", "]", "label_splits", "=", "listify", "(", "la...
Split labels into `num_splits` and generate candidates based on log-uniform distribution.
[ "Split", "labels", "into", "num_splits", "and", "generate", "candidates", "based", "on", "log", "-", "uniform", "distribution", "." ]
python
train
linuxsoftware/ls.joyous
ls/joyous/models/calendar.py
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L438-L441
def _getEventsOnDay(self, request, day): """Return all the events in this site for a given day.""" home = request.site.root_page return getAllEventsByDay(request, day, day, home=home)[0]
[ "def", "_getEventsOnDay", "(", "self", ",", "request", ",", "day", ")", ":", "home", "=", "request", ".", "site", ".", "root_page", "return", "getAllEventsByDay", "(", "request", ",", "day", ",", "day", ",", "home", "=", "home", ")", "[", "0", "]" ]
Return all the events in this site for a given day.
[ "Return", "all", "the", "events", "in", "this", "site", "for", "a", "given", "day", "." ]
python
train
rocky/python-xdis
xdis/util.py
https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/util.py#L69-L83
def pretty_flags(flags): """Return pretty representation of code flags.""" names = [] result = "0x%08x" % flags for i in range(32): flag = 1 << i if flags & flag: names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag))) flags ^= flag if not flags: break else: names.append(hex(flags)) names.reverse() return "%s (%s)" % (result, " | ".join(names))
[ "def", "pretty_flags", "(", "flags", ")", ":", "names", "=", "[", "]", "result", "=", "\"0x%08x\"", "%", "flags", "for", "i", "in", "range", "(", "32", ")", ":", "flag", "=", "1", "<<", "i", "if", "flags", "&", "flag", ":", "names", ".", "append"...
Return pretty representation of code flags.
[ "Return", "pretty", "representation", "of", "code", "flags", "." ]
python
train
radjkarl/imgProcessor
imgProcessor/camera/LensDistortion.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/LensDistortion.py#L258-L275
def writeToFile(self, filename, saveOpts=False): ''' write the distortion coeffs to file saveOpts --> Whether so save calibration options (and not just results) ''' try: if not filename.endswith('.%s' % self.ftype): filename += '.%s' % self.ftype s = {'coeffs': self.coeffs} if saveOpts: s['opts'] = self.opts # else: # s['opts':{}] np.savez(filename, **s) return filename except AttributeError: raise Exception( 'need to calibrate camera before calibration can be saved to file')
[ "def", "writeToFile", "(", "self", ",", "filename", ",", "saveOpts", "=", "False", ")", ":", "try", ":", "if", "not", "filename", ".", "endswith", "(", "'.%s'", "%", "self", ".", "ftype", ")", ":", "filename", "+=", "'.%s'", "%", "self", ".", "ftype"...
write the distortion coeffs to file saveOpts --> Whether so save calibration options (and not just results)
[ "write", "the", "distortion", "coeffs", "to", "file", "saveOpts", "--", ">", "Whether", "so", "save", "calibration", "options", "(", "and", "not", "just", "results", ")" ]
python
train
zeromake/aiko
aiko/application.py
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/application.py#L253-L285
def _handle(self, request: Request, response: Response) -> TypeGenerator[Any, None, None]: """ request 解析后的回调,调用中间件,并处理 headers, body 发送。 """ # request.start_time = datetime.now().timestamp() # 创建一个新的会话上下文 ctx = self._context( cast(asyncio.AbstractEventLoop, self._loop), request, response, self, ) request.app = self response.app = self request.ctx = ctx response.ctx = ctx request.response = response response.request = request # 把当前注册的中间件转为迭代器 middleware_iter = iter(self._middleware) # 通过迭代器的模式生成一个执行下一个中间的调用方法 next_call = self._next_middleware(middleware_iter, ctx) # 顺序执行中间件 yield from self._middleware_call(middleware_iter, ctx, next_call) # 设置 cookies cookies_headers = ctx.cookies.headers() if cookies_headers is not None: ctx.response.set("Set-Cookie", cookies_headers) # 写出 headers ctx.response.flush_headers() # 写出 body ctx.response.flush_body()
[ "def", "_handle", "(", "self", ",", "request", ":", "Request", ",", "response", ":", "Response", ")", "->", "TypeGenerator", "[", "Any", ",", "None", ",", "None", "]", ":", "# request.start_time = datetime.now().timestamp()", "# 创建一个新的会话上下文", "ctx", "=", "self",...
request 解析后的回调,调用中间件,并处理 headers, body 发送。
[ "request", "解析后的回调,调用中间件,并处理", "headers", "body", "发送。" ]
python
train
saltstack/salt
salt/proxy/bluecoat_sslv.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/bluecoat_sslv.py#L201-L213
def logout(session, cookies, csrf_token): ''' Closes the session with the device. ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "logout", "params": [] } session.post(DETAILS['url'], data=json.dumps(payload), cookies=cookies, headers={'X-CSRF-Token': csrf_token})
[ "def", "logout", "(", "session", ",", "cookies", ",", "csrf_token", ")", ":", "payload", "=", "{", "\"jsonrpc\"", ":", "\"2.0\"", ",", "\"id\"", ":", "\"ID0\"", ",", "\"method\"", ":", "\"logout\"", ",", "\"params\"", ":", "[", "]", "}", "session", ".", ...
Closes the session with the device.
[ "Closes", "the", "session", "with", "the", "device", "." ]
python
train
jim-easterbrook/pywws
src/pywws/weatherstation.py
https://github.com/jim-easterbrook/pywws/blob/4e4d74cee5a3ac5bf42286feaa251cd2ffcaf02c/src/pywws/weatherstation.py#L665-L670
def dec_ptr(self, ptr): """Get previous circular buffer data pointer.""" result = ptr - self.reading_len[self.ws_type] if result < self.data_start: result = 0x10000 - self.reading_len[self.ws_type] return result
[ "def", "dec_ptr", "(", "self", ",", "ptr", ")", ":", "result", "=", "ptr", "-", "self", ".", "reading_len", "[", "self", ".", "ws_type", "]", "if", "result", "<", "self", ".", "data_start", ":", "result", "=", "0x10000", "-", "self", ".", "reading_le...
Get previous circular buffer data pointer.
[ "Get", "previous", "circular", "buffer", "data", "pointer", "." ]
python
train
ilgarm/pyzimbra
pyzimbra/z/admin.py
https://github.com/ilgarm/pyzimbra/blob/c397bc7497554d260ec6fd1a80405aed872a70cc/pyzimbra/z/admin.py#L66-L77
def get_info(self, account, params={}): """ Gets account info. @param account: account to get info for @param params: parameters to retrieve @return: AccountInfo """ res = self.invoke(zconstant.NS_ZIMBRA_ADMIN_URL, sconstant.GetInfoRequest, params) return res
[ "def", "get_info", "(", "self", ",", "account", ",", "params", "=", "{", "}", ")", ":", "res", "=", "self", ".", "invoke", "(", "zconstant", ".", "NS_ZIMBRA_ADMIN_URL", ",", "sconstant", ".", "GetInfoRequest", ",", "params", ")", "return", "res" ]
Gets account info. @param account: account to get info for @param params: parameters to retrieve @return: AccountInfo
[ "Gets", "account", "info", "." ]
python
train
ungarj/mapchete
mapchete/formats/default/tile_directory.py
https://github.com/ungarj/mapchete/blob/d482918d0e66a5b414dff6aa7cc854e01fc60ee4/mapchete/formats/default/tile_directory.py#L288-L330
def read( self, validity_check=False, indexes=None, resampling=None, dst_nodata=None, gdal_opts=None, **kwargs ): """ Read reprojected & resampled input data. Parameters ---------- validity_check : bool vector file: also run checks if reprojected geometry is valid, otherwise throw RuntimeError (default: True) indexes : list or int raster file: a list of band numbers; None will read all. dst_nodata : int or float, optional raster file: if not set, the nodata value from the source dataset will be used gdal_opts : dict raster file: GDAL options passed on to rasterio.Env() Returns ------- data : list for vector files or numpy array for raster files """ return self._read_as_tiledir( data_type=self._file_type, out_tile=self.tile, td_crs=self._td_crs, tiles_paths=self._tiles_paths, profile=self._profile, validity_check=validity_check, indexes=indexes, resampling=resampling if resampling else self._resampling, dst_nodata=dst_nodata, gdal_opts=gdal_opts, **{k: v for k, v in kwargs.items() if k != "data_type"} )
[ "def", "read", "(", "self", ",", "validity_check", "=", "False", ",", "indexes", "=", "None", ",", "resampling", "=", "None", ",", "dst_nodata", "=", "None", ",", "gdal_opts", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_r...
Read reprojected & resampled input data. Parameters ---------- validity_check : bool vector file: also run checks if reprojected geometry is valid, otherwise throw RuntimeError (default: True) indexes : list or int raster file: a list of band numbers; None will read all. dst_nodata : int or float, optional raster file: if not set, the nodata value from the source dataset will be used gdal_opts : dict raster file: GDAL options passed on to rasterio.Env() Returns ------- data : list for vector files or numpy array for raster files
[ "Read", "reprojected", "&", "resampled", "input", "data", "." ]
python
valid
buzzfeed/caliendo
caliendo/patch.py
https://github.com/buzzfeed/caliendo/blob/1628a10f7782ad67c0422b5cbc9bf4979ac40abc/caliendo/patch.py#L231-L282
def patch(import_path, rvalue=UNDEFINED, side_effect=UNDEFINED, ignore=UNDEFINED, callback=UNDEFINED, ctxt=UNDEFINED, subsequent_rvalue=UNDEFINED): """ Patches an attribute of a module referenced on import_path with a decorated version that will use the caliendo cache if rvalue is None. Otherwise it will patch the attribute of the module to return rvalue when called. This class provides a context in which to use the patched module. After the decorated method is called patch_in_place unpatches the patched module with the original method. :param str import_path: The import path of the method to patch. :param mixed rvalue: The return value of the patched method. :param mixed side_effect: The side effect to execute. Either a callable with the same parameters as the target, or an exception. :param caliendo.Ignore ignore: Arguments to ignore. The first element should be a list of positional arguments. The second should be a list of keys for keyword arguments. :param function callback: A pickleable callback to execute when the patched method is called and the cache is hit. (has to have been cached the first time). :param caliendo.hooks.Context ctxt: The context this patch should be executed under. Generally reserved for internal use. The vast majority of use cases should leave this parameter alone. :param mixed subsequent_rvalue: If passed; this will be the return value each time this method is run regardless of what is returned when it is initially cached. Caching for this method will be skipped. This is useful when the method returns something unpickleable but we still need to stub it out. """ def patch_test(unpatched_test): """ Patches a callable dependency of an unpatched test with a callable corresponding to patch_with. :param unpatched_test: The unpatched test for which we're patching dependencies :type unpatched_test: instance method of a test suite :param patch_with: A callable to patch the callable dependency with. Should match the function signature of the callable we're patching. :type patch_with: callable :returns: The patched test :rtype: instance method """ if ctxt == UNDEFINED: context = get_context(unpatched_test) else: context = ctxt context.enter() patched_test = get_patched_test(import_path=import_path, unpatched_test=unpatched_test, rvalue=rvalue, side_effect=side_effect, context=context, ignore=ignore, callback=callback, subsequent_rvalue=subsequent_rvalue) patched_test.__context = context patched_test.__name__ = context.name return patched_test return patch_test
[ "def", "patch", "(", "import_path", ",", "rvalue", "=", "UNDEFINED", ",", "side_effect", "=", "UNDEFINED", ",", "ignore", "=", "UNDEFINED", ",", "callback", "=", "UNDEFINED", ",", "ctxt", "=", "UNDEFINED", ",", "subsequent_rvalue", "=", "UNDEFINED", ")", ":"...
Patches an attribute of a module referenced on import_path with a decorated version that will use the caliendo cache if rvalue is None. Otherwise it will patch the attribute of the module to return rvalue when called. This class provides a context in which to use the patched module. After the decorated method is called patch_in_place unpatches the patched module with the original method. :param str import_path: The import path of the method to patch. :param mixed rvalue: The return value of the patched method. :param mixed side_effect: The side effect to execute. Either a callable with the same parameters as the target, or an exception. :param caliendo.Ignore ignore: Arguments to ignore. The first element should be a list of positional arguments. The second should be a list of keys for keyword arguments. :param function callback: A pickleable callback to execute when the patched method is called and the cache is hit. (has to have been cached the first time). :param caliendo.hooks.Context ctxt: The context this patch should be executed under. Generally reserved for internal use. The vast majority of use cases should leave this parameter alone. :param mixed subsequent_rvalue: If passed; this will be the return value each time this method is run regardless of what is returned when it is initially cached. Caching for this method will be skipped. This is useful when the method returns something unpickleable but we still need to stub it out.
[ "Patches", "an", "attribute", "of", "a", "module", "referenced", "on", "import_path", "with", "a", "decorated", "version", "that", "will", "use", "the", "caliendo", "cache", "if", "rvalue", "is", "None", ".", "Otherwise", "it", "will", "patch", "the", "attri...
python
train
alphagov/gapy
gapy/client.py
https://github.com/alphagov/gapy/blob/5e8cc058c54d6034fa0f5177d5a6d3d2e71fa5ea/gapy/client.py#L62-L89
def from_secrets_file(client_secrets, storage=None, flags=None, storage_path=None, api_version="v3", readonly=False, http_client=None, ga_hook=None): """Create a client for a web or installed application. Create a client with a client secrets file. Args: client_secrets: str, path to the client secrets file (downloadable from Google API Console) storage: oauth2client.client.Storage, a Storage implementation to store credentials. storage_path: str, path to a file storage. readonly: bool, default False, if True only readonly access is requested from GA. http_client: httplib2.Http, Override the default http client used. ga_hook: function, a hook that is called every time a query is made against GA. """ scope = GOOGLE_API_SCOPE_READONLY if readonly else GOOGLE_API_SCOPE flow = flow_from_clientsecrets(client_secrets, scope=scope) storage = _get_storage(storage, storage_path) credentials = storage.get() if credentials is None or credentials.invalid: credentials = run_flow(flow, storage, flags) return Client(_build(credentials, api_version, http_client), ga_hook)
[ "def", "from_secrets_file", "(", "client_secrets", ",", "storage", "=", "None", ",", "flags", "=", "None", ",", "storage_path", "=", "None", ",", "api_version", "=", "\"v3\"", ",", "readonly", "=", "False", ",", "http_client", "=", "None", ",", "ga_hook", ...
Create a client for a web or installed application. Create a client with a client secrets file. Args: client_secrets: str, path to the client secrets file (downloadable from Google API Console) storage: oauth2client.client.Storage, a Storage implementation to store credentials. storage_path: str, path to a file storage. readonly: bool, default False, if True only readonly access is requested from GA. http_client: httplib2.Http, Override the default http client used. ga_hook: function, a hook that is called every time a query is made against GA.
[ "Create", "a", "client", "for", "a", "web", "or", "installed", "application", "." ]
python
train
pybel/pybel
src/pybel/struct/graph.py
https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/struct/graph.py#L728-L731
def iter_equivalent_nodes(self, node: BaseEntity) -> Iterable[BaseEntity]: """Iterate over nodes that are equivalent to the given node, including the original.""" yield node yield from self._equivalent_node_iterator_helper(node, {node})
[ "def", "iter_equivalent_nodes", "(", "self", ",", "node", ":", "BaseEntity", ")", "->", "Iterable", "[", "BaseEntity", "]", ":", "yield", "node", "yield", "from", "self", ".", "_equivalent_node_iterator_helper", "(", "node", ",", "{", "node", "}", ")" ]
Iterate over nodes that are equivalent to the given node, including the original.
[ "Iterate", "over", "nodes", "that", "are", "equivalent", "to", "the", "given", "node", "including", "the", "original", "." ]
python
train
woolfson-group/isambard
isambard/tools/file_parsing.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/tools/file_parsing.py#L300-L340
def parse_PISCES_output(pisces_output, path=False): """ Takes the output list of a PISCES cull and returns in a usable dictionary. Notes ----- Designed for outputs of protein sequence redundancy culls conducted using the PISCES server. http://dunbrack.fccc.edu/PISCES.php G. Wang and R. L. Dunbrack, Jr. PISCES: a protein sequence culling server. Bioinformatics, 19:1589-1591, 2003. Parameters ---------- pisces_output : str or path Output list of non-redundant protein chains from PISCES, or path to text file. path : bool True if path given rather than string. Returns ------- pisces_dict : dict Data output by PISCES in dictionary form. """ pisces_dict = {} if path: pisces_path = Path(pisces_output) pisces_content = pisces_path.read_text().splitlines()[1:] else: pisces_content = pisces_output.splitlines()[1:] for line in pisces_content: pdb = line.split()[0][:4].lower() chain = line.split()[0][-1] pdb_dict = {'length': line.split()[1], 'method': line.split()[2], 'resolution': line.split()[3], 'R-factor': line.split()[4], 'R-free': line.split()[5]} if pdb in pisces_dict: pisces_dict[pdb]['chains'].append(chain) else: pdb_dict['chains'] = [chain] pisces_dict[pdb] = pdb_dict return pisces_dict
[ "def", "parse_PISCES_output", "(", "pisces_output", ",", "path", "=", "False", ")", ":", "pisces_dict", "=", "{", "}", "if", "path", ":", "pisces_path", "=", "Path", "(", "pisces_output", ")", "pisces_content", "=", "pisces_path", ".", "read_text", "(", ")",...
Takes the output list of a PISCES cull and returns in a usable dictionary. Notes ----- Designed for outputs of protein sequence redundancy culls conducted using the PISCES server. http://dunbrack.fccc.edu/PISCES.php G. Wang and R. L. Dunbrack, Jr. PISCES: a protein sequence culling server. Bioinformatics, 19:1589-1591, 2003. Parameters ---------- pisces_output : str or path Output list of non-redundant protein chains from PISCES, or path to text file. path : bool True if path given rather than string. Returns ------- pisces_dict : dict Data output by PISCES in dictionary form.
[ "Takes", "the", "output", "list", "of", "a", "PISCES", "cull", "and", "returns", "in", "a", "usable", "dictionary", "." ]
python
train
samastur/pyimagediet
pyimagediet/process.py
https://github.com/samastur/pyimagediet/blob/480c6e171577df36e166590b031bc8891b3c9e7b/pyimagediet/process.py#L58-L101
def parse_configuration(config): ''' Parse and fix configuration: - processed file should end up being same as input - pipelines should contain CLI commands to run - add missing sections :param config: raw configuration object :type config: dict :return: configuration ready for `diet()` :rtype: dict ''' new_config = copy.deepcopy(config) required_parts = ('commands', 'parameters', 'pipelines') for part in required_parts: new_config.setdefault(part, {}) # Parse only if it hasn't been parsed yet so it is safe to run it more than # once. if not new_config.get('parsed'): try: # Always end up with input file. If app outputs to a different one, # then replace old one with it for prog in new_config['parameters']: if '{output_file}' in new_config['parameters'][prog]: new_config['parameters'][prog] += " && mv '{output_file}' '{file}'" # Build pipelines for label, raw_pipeline in new_config['pipelines'].items(): commands = [] for app in raw_pipeline: full_command = " ".join([new_config['commands'][app], new_config['parameters'][app]]) commands.append(full_command) new_config['pipelines'][label] = " && ".join(commands) except KeyError as e: error_msg = "Missing key(s) in configuration: {0}.".format( ",".join(e.args)) raise ConfigurationErrorDietException(error_msg) new_config['parsed'] = True return new_config
[ "def", "parse_configuration", "(", "config", ")", ":", "new_config", "=", "copy", ".", "deepcopy", "(", "config", ")", "required_parts", "=", "(", "'commands'", ",", "'parameters'", ",", "'pipelines'", ")", "for", "part", "in", "required_parts", ":", "new_conf...
Parse and fix configuration: - processed file should end up being same as input - pipelines should contain CLI commands to run - add missing sections :param config: raw configuration object :type config: dict :return: configuration ready for `diet()` :rtype: dict
[ "Parse", "and", "fix", "configuration", ":", "-", "processed", "file", "should", "end", "up", "being", "same", "as", "input", "-", "pipelines", "should", "contain", "CLI", "commands", "to", "run", "-", "add", "missing", "sections" ]
python
train
pandas-dev/pandas
pandas/core/arrays/timedeltas.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/timedeltas.py#L392-L402
def _add_datetime_arraylike(self, other): """ Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray. """ if isinstance(other, np.ndarray): # At this point we have already checked that dtype is datetime64 from pandas.core.arrays import DatetimeArray other = DatetimeArray(other) # defer to implementation in DatetimeArray return other + self
[ "def", "_add_datetime_arraylike", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "np", ".", "ndarray", ")", ":", "# At this point we have already checked that dtype is datetime64", "from", "pandas", ".", "core", ".", "arrays", "import", ...
Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray.
[ "Add", "DatetimeArray", "/", "Index", "or", "ndarray", "[", "datetime64", "]", "to", "TimedeltaArray", "." ]
python
train
jxtech/wechatpy
wechatpy/client/api/invoice.py
https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/client/api/invoice.py#L251-L271
def set_pay_mch(self, mchid, s_pappid): """ 关联商户号与开票平台,设置支付后开票 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1496561731_2Z55U :param mchid: 微信支付商户号 :param s_pappid: 开票平台在微信的标识号,商户需要找开票平台提供 """ return self._post( 'setbizattr', params={ 'action': 'set_pay_mch', }, data={ 'paymch_info': { 'mchid': mchid, 's_pappid': s_pappid, }, }, )
[ "def", "set_pay_mch", "(", "self", ",", "mchid", ",", "s_pappid", ")", ":", "return", "self", ".", "_post", "(", "'setbizattr'", ",", "params", "=", "{", "'action'", ":", "'set_pay_mch'", ",", "}", ",", "data", "=", "{", "'paymch_info'", ":", "{", "'mc...
关联商户号与开票平台,设置支付后开票 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1496561731_2Z55U :param mchid: 微信支付商户号 :param s_pappid: 开票平台在微信的标识号,商户需要找开票平台提供
[ "关联商户号与开票平台,设置支付后开票", "详情请参考", "https", ":", "//", "mp", ".", "weixin", ".", "qq", ".", "com", "/", "wiki?id", "=", "mp1496561731_2Z55U" ]
python
train
AndresMWeber/Nomenclate
nomenclate/core/configurator.py
https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/configurator.py#L176-L190
def _get_path_entry_from_list(self, query_path): """ Returns the config entry at query path :param query_path: list(str), config header path to follow for entry :return: (list, str, dict, OrderedDict), config entry requested :raises: exceptions.ResourceNotFoundError """ cur_data = self.config_file_contents try: for child in query_path: cur_data = cur_data[child] return cur_data except (AttributeError, KeyError): raise errors.ResourceNotFoundError('Could not find query path %s in the config file contents' % query_path)
[ "def", "_get_path_entry_from_list", "(", "self", ",", "query_path", ")", ":", "cur_data", "=", "self", ".", "config_file_contents", "try", ":", "for", "child", "in", "query_path", ":", "cur_data", "=", "cur_data", "[", "child", "]", "return", "cur_data", "exce...
Returns the config entry at query path :param query_path: list(str), config header path to follow for entry :return: (list, str, dict, OrderedDict), config entry requested :raises: exceptions.ResourceNotFoundError
[ "Returns", "the", "config", "entry", "at", "query", "path" ]
python
train
insightindustry/validator-collection
validator_collection/checkers.py
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/checkers.py#L152-L194
def are_dicts_equivalent(*args, **kwargs): """Indicate if :ref:`dicts <python:dict>` passed to this function have identical keys and values. :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` have identical keys/values, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator """ # pylint: disable=too-many-return-statements if not args: return False if len(args) == 1: return True if not all(is_dict(x) for x in args): return False first_item = args[0] for item in args[1:]: if len(item) != len(first_item): return False for key in item: if key not in first_item: return False if not are_equivalent(item[key], first_item[key]): return False for key in first_item: if key not in item: return False if not are_equivalent(first_item[key], item[key]): return False return True
[ "def", "are_dicts_equivalent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=too-many-return-statements", "if", "not", "args", ":", "return", "False", "if", "len", "(", "args", ")", "==", "1", ":", "return", "True", "if", "not", "...
Indicate if :ref:`dicts <python:dict>` passed to this function have identical keys and values. :param args: One or more values, passed as positional arguments. :returns: ``True`` if ``args`` have identical keys/values, and ``False`` if not. :rtype: :class:`bool <python:bool>` :raises SyntaxError: if ``kwargs`` contains duplicate keyword parameters or duplicates keyword parameters passed to the underlying validator
[ "Indicate", "if", ":", "ref", ":", "dicts", "<python", ":", "dict", ">", "passed", "to", "this", "function", "have", "identical", "keys", "and", "values", "." ]
python
train
sorgerlab/indra
indra/preassembler/grounding_mapper.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/preassembler/grounding_mapper.py#L499-L559
def agent_texts_with_grounding(stmts): """Return agent text groundings in a list of statements with their counts Parameters ---------- stmts: list of :py:class:`indra.statements.Statement` Returns ------- list of tuple List of tuples of the form (text: str, ((name_space: str, ID: str, count: int)...), total_count: int) Where the counts within the tuple of groundings give the number of times an agent with the given agent_text appears grounded with the particular name space and ID. The total_count gives the total number of times an agent with text appears in the list of statements. """ allag = all_agents(stmts) # Convert PFAM-DEF lists into tuples so that they are hashable and can # be tabulated with a Counter for ag in allag: pfam_def = ag.db_refs.get('PFAM-DEF') if pfam_def is not None: ag.db_refs['PFAM-DEF'] = tuple(pfam_def) refs = [tuple(ag.db_refs.items()) for ag in allag] refs_counter = Counter(refs) refs_counter_dict = [(dict(entry[0]), entry[1]) for entry in refs_counter.items()] # First, sort by text so that we can do a groupby refs_counter_dict.sort(key=lambda x: x[0].get('TEXT')) # Then group by text grouped_by_text = [] for k, g in groupby(refs_counter_dict, key=lambda x: x[0].get('TEXT')): # Total occurrences of this agent text total = 0 entry = [k] db_ref_list = [] for db_refs, count in g: # Check if TEXT is our only key, indicating no grounding if list(db_refs.keys()) == ['TEXT']: db_ref_list.append((None, None, count)) # Add any other db_refs (not TEXT) for db, db_id in db_refs.items(): if db == 'TEXT': continue else: db_ref_list.append((db, db_id, count)) total += count # Sort the db_ref_list by the occurrences of each grounding entry.append(tuple(sorted(db_ref_list, key=lambda x: x[2], reverse=True))) # Now add the total frequency to the entry entry.append(total) # And add the entry to the overall list grouped_by_text.append(tuple(entry)) # Sort the list by the total number of occurrences of each unique key grouped_by_text.sort(key=lambda x: x[2], reverse=True) return grouped_by_text
[ "def", "agent_texts_with_grounding", "(", "stmts", ")", ":", "allag", "=", "all_agents", "(", "stmts", ")", "# Convert PFAM-DEF lists into tuples so that they are hashable and can", "# be tabulated with a Counter", "for", "ag", "in", "allag", ":", "pfam_def", "=", "ag", "...
Return agent text groundings in a list of statements with their counts Parameters ---------- stmts: list of :py:class:`indra.statements.Statement` Returns ------- list of tuple List of tuples of the form (text: str, ((name_space: str, ID: str, count: int)...), total_count: int) Where the counts within the tuple of groundings give the number of times an agent with the given agent_text appears grounded with the particular name space and ID. The total_count gives the total number of times an agent with text appears in the list of statements.
[ "Return", "agent", "text", "groundings", "in", "a", "list", "of", "statements", "with", "their", "counts" ]
python
train
dhondta/tinyscript
tinyscript/helpers/utils.py
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/helpers/utils.py#L57-L97
def user_input(prompt="", choices=None, default=None, choices_str="", required=False): """ Python2/3-compatible input method handling choices and default value. :param prompt: prompt message :param choices: list of possible choices or lambda function :param default: default value :param required: make non-null user input mandatory :return: handled user input """ if type(choices) in [list, tuple, set]: choices = list(map(str, choices)) choices_str = " {%s}" % (choices_str or \ '|'.join(list(map(str, choices)))) # consider choices of the form ["(Y)es", "(N)o"] ; # in this case, we want the choices to be ['y', 'n'] for the sake of # simplicity for the user m = list(map(lambda x: CHOICE_REGEX.match(x), choices)) choices = [x.group(1).lower() if x else c for x, c in zip(m, choices)] # this way, if using ["Yes", "No"], choices will remain so _check = lambda v: v in choices elif is_lambda(choices): _check = choices else: _check = lambda v: True prompt += "{}{}\n".format(choices_str, [" [{}]".format(default), ""]\ [default is None and required]) user_input, first = None, True while not user_input: user_input = std_input(["", prompt][first] + " >> ") first = False if type(choices) in [list, tuple, set]: choices = list(map(lambda x: x.lower(), choices)) user_input = user_input.lower() if user_input == "" and default is not None and _check(default): return str(default) if user_input != "" and _check(user_input): return user_input if not required: return
[ "def", "user_input", "(", "prompt", "=", "\"\"", ",", "choices", "=", "None", ",", "default", "=", "None", ",", "choices_str", "=", "\"\"", ",", "required", "=", "False", ")", ":", "if", "type", "(", "choices", ")", "in", "[", "list", ",", "tuple", ...
Python2/3-compatible input method handling choices and default value. :param prompt: prompt message :param choices: list of possible choices or lambda function :param default: default value :param required: make non-null user input mandatory :return: handled user input
[ "Python2", "/", "3", "-", "compatible", "input", "method", "handling", "choices", "and", "default", "value", ".", ":", "param", "prompt", ":", "prompt", "message", ":", "param", "choices", ":", "list", "of", "possible", "choices", "or", "lambda", "function",...
python
train
mitodl/pylti
pylti/flask.py
https://github.com/mitodl/pylti/blob/18a608282e0d5bc941beb2eaaeea3b7ad484b399/pylti/flask.py#L159-L213
def lti(app=None, request='any', error=default_error, role='any', *lti_args, **lti_kwargs): """ LTI decorator :param: app - Flask App object (optional). :py:attr:`flask.current_app` is used if no object is passed in. :param: error - Callback if LTI throws exception (optional). :py:attr:`pylti.flask.default_error` is the default. :param: request - Request type from :py:attr:`pylti.common.LTI_REQUEST_TYPE`. (default: any) :param: roles - LTI Role (default: any) :return: wrapper """ def _lti(function): """ Inner LTI decorator :param: function: :return: """ @wraps(function) def wrapper(*args, **kwargs): """ Pass LTI reference to function or return error. """ try: the_lti = LTI(lti_args, lti_kwargs) the_lti.verify() the_lti._check_role() # pylint: disable=protected-access kwargs['lti'] = the_lti return function(*args, **kwargs) except LTIException as lti_exception: error = lti_kwargs.get('error') exception = dict() exception['exception'] = lti_exception exception['kwargs'] = kwargs exception['args'] = args return error(exception=exception) return wrapper lti_kwargs['request'] = request lti_kwargs['error'] = error lti_kwargs['role'] = role if (not app) or isinstance(app, Flask): lti_kwargs['app'] = app return _lti else: # We are wrapping without arguments lti_kwargs['app'] = None return _lti(app)
[ "def", "lti", "(", "app", "=", "None", ",", "request", "=", "'any'", ",", "error", "=", "default_error", ",", "role", "=", "'any'", ",", "*", "lti_args", ",", "*", "*", "lti_kwargs", ")", ":", "def", "_lti", "(", "function", ")", ":", "\"\"\"\n ...
LTI decorator :param: app - Flask App object (optional). :py:attr:`flask.current_app` is used if no object is passed in. :param: error - Callback if LTI throws exception (optional). :py:attr:`pylti.flask.default_error` is the default. :param: request - Request type from :py:attr:`pylti.common.LTI_REQUEST_TYPE`. (default: any) :param: roles - LTI Role (default: any) :return: wrapper
[ "LTI", "decorator" ]
python
train
Opentrons/opentrons
api/src/opentrons/deck_calibration/endpoints.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/endpoints.py#L100-L124
def init_pipette(): """ Finds pipettes attached to the robot currently and chooses the correct one to add to the session. :return: The pipette type and mount chosen for deck calibration """ global session pipette_info = set_current_mount(session.adapter, session) pipette = pipette_info['pipette'] res = {} if pipette: session.current_model = pipette_info['model'] if not feature_flags.use_protocol_api_v2(): mount = pipette.mount session.current_mount = mount else: mount = pipette.get('mount') session.current_mount = mount_by_name[mount] session.pipettes[mount] = pipette res = {'mount': mount, 'model': pipette_info['model']} log.info("Pipette info {}".format(session.pipettes)) return res
[ "def", "init_pipette", "(", ")", ":", "global", "session", "pipette_info", "=", "set_current_mount", "(", "session", ".", "adapter", ",", "session", ")", "pipette", "=", "pipette_info", "[", "'pipette'", "]", "res", "=", "{", "}", "if", "pipette", ":", "se...
Finds pipettes attached to the robot currently and chooses the correct one to add to the session. :return: The pipette type and mount chosen for deck calibration
[ "Finds", "pipettes", "attached", "to", "the", "robot", "currently", "and", "chooses", "the", "correct", "one", "to", "add", "to", "the", "session", "." ]
python
train
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/breakpoint.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L912-L932
def __set_bp(self, aThread): """ Sets this breakpoint in the debug registers. @type aThread: L{Thread} @param aThread: Thread object. """ if self.__slot is None: aThread.suspend() try: ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS) self.__slot = DebugRegister.find_slot(ctx) if self.__slot is None: msg = "No available hardware breakpoint slots for thread ID %d" msg = msg % aThread.get_tid() raise RuntimeError(msg) DebugRegister.set_bp(ctx, self.__slot, self.get_address(), self.__trigger, self.__watch) aThread.set_context(ctx) finally: aThread.resume()
[ "def", "__set_bp", "(", "self", ",", "aThread", ")", ":", "if", "self", ".", "__slot", "is", "None", ":", "aThread", ".", "suspend", "(", ")", "try", ":", "ctx", "=", "aThread", ".", "get_context", "(", "win32", ".", "CONTEXT_DEBUG_REGISTERS", ")", "se...
Sets this breakpoint in the debug registers. @type aThread: L{Thread} @param aThread: Thread object.
[ "Sets", "this", "breakpoint", "in", "the", "debug", "registers", "." ]
python
train
rjw57/starman
starman/kalman.py
https://github.com/rjw57/starman/blob/1f9475e2354c9630a61f4898ad871de1d2fdbc71/starman/kalman.py#L131-L204
def predict(self, control=None, control_matrix=None, process_matrix=None, process_covariance=None): """ Predict the next *a priori* state mean and covariance given the last posterior. As a special case the first call to this method will initialise the posterior and prior estimates from the *initial_state_estimate* and *initial_covariance* arguments passed when this object was created. In this case the *process_matrix* and *process_covariance* arguments are unused but are still recorded in the :py:attr:`.process_matrices` and :py:attr:`.process_covariances` attributes. Args: control (array or None): If specified, the control input for this predict step. control_matrix (array or None): If specified, the control matrix to use for this time step. process_matrix (array or None): If specified, the process matrix to use for this time step. process_covariance (array or None): If specified, the process covariance to use for this time step. """ # Sanitise arguments if process_matrix is None: process_matrix = self._defaults['process_matrix'] if process_covariance is None: process_covariance = self._defaults['process_covariance'] if control_matrix is None: control_matrix = self._defaults['control_matrix'] if len(self.prior_state_estimates) == 0: # Special case: first call self.prior_state_estimates.append(self._initial_state_estimate) else: # Usual case process_matrix = as_square_array(process_matrix) process_covariance = as_square_array(process_covariance) if process_matrix.shape[0] != process_covariance.shape[0]: raise ValueError("Process matrix and noise have incompatible " \ "shapes: {} vs {}".format( process_matrix.shape, process_covariance.shape)) if control_matrix is not None: control_matrix = np.atleast_2d(control_matrix) if control is not None: control = np.atleast_1d(control) # Update state mean and covariance prev_posterior_mean = self.posterior_state_estimates[-1].mean prev_posterior_cov = self.posterior_state_estimates[-1].cov prior_mean = process_matrix.dot(prev_posterior_mean) if control is not None: prior_mean += control_matrix.dot(control) prior_cov = process_matrix.dot(prev_posterior_cov).dot( process_matrix.T) + process_covariance self.prior_state_estimates.append( MultivariateNormal(mean=prior_mean, cov=prior_cov)) # Record transition matrix self.process_matrices.append(process_matrix) self.process_covariances.append(process_covariance) # Append empty list to measurements for this time step self.measurements.append([]) self.measurement_matrices.append([]) # Seed posterior estimates with the prior one. self.posterior_state_estimates.append(self.prior_state_estimates[-1])
[ "def", "predict", "(", "self", ",", "control", "=", "None", ",", "control_matrix", "=", "None", ",", "process_matrix", "=", "None", ",", "process_covariance", "=", "None", ")", ":", "# Sanitise arguments", "if", "process_matrix", "is", "None", ":", "process_ma...
Predict the next *a priori* state mean and covariance given the last posterior. As a special case the first call to this method will initialise the posterior and prior estimates from the *initial_state_estimate* and *initial_covariance* arguments passed when this object was created. In this case the *process_matrix* and *process_covariance* arguments are unused but are still recorded in the :py:attr:`.process_matrices` and :py:attr:`.process_covariances` attributes. Args: control (array or None): If specified, the control input for this predict step. control_matrix (array or None): If specified, the control matrix to use for this time step. process_matrix (array or None): If specified, the process matrix to use for this time step. process_covariance (array or None): If specified, the process covariance to use for this time step.
[ "Predict", "the", "next", "*", "a", "priori", "*", "state", "mean", "and", "covariance", "given", "the", "last", "posterior", ".", "As", "a", "special", "case", "the", "first", "call", "to", "this", "method", "will", "initialise", "the", "posterior", "and"...
python
train
mrjoes/sockjs-tornado
sockjs/tornado/sessioncontainer.py
https://github.com/mrjoes/sockjs-tornado/blob/bd3a99b407f1181f054b3b1730f438dde375ca1c/sockjs/tornado/sessioncontainer.py#L82-L91
def add(self, session): """Add session to the container. `session` Session object """ self._items[session.session_id] = session if session.expiry is not None: heappush(self._queue, session)
[ "def", "add", "(", "self", ",", "session", ")", ":", "self", ".", "_items", "[", "session", ".", "session_id", "]", "=", "session", "if", "session", ".", "expiry", "is", "not", "None", ":", "heappush", "(", "self", ".", "_queue", ",", "session", ")" ...
Add session to the container. `session` Session object
[ "Add", "session", "to", "the", "container", "." ]
python
train
jazzband/django-ddp
dddp/websocket.py
https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/websocket.py#L431-L437
def recv_method(self, method, params, id_, randomSeed=None): """DDP method handler.""" if randomSeed is not None: this.random_streams.random_seed = randomSeed this.alea_random = alea.Alea(randomSeed) self.api.method(method, params, id_) self.reply('updated', methods=[id_])
[ "def", "recv_method", "(", "self", ",", "method", ",", "params", ",", "id_", ",", "randomSeed", "=", "None", ")", ":", "if", "randomSeed", "is", "not", "None", ":", "this", ".", "random_streams", ".", "random_seed", "=", "randomSeed", "this", ".", "alea_...
DDP method handler.
[ "DDP", "method", "handler", "." ]
python
test
MediaFire/mediafire-python-open-sdk
mediafire/uploader.py
https://github.com/MediaFire/mediafire-python-open-sdk/blob/8f1f23db1b16f16e026f5c6777aec32d00baa05f/mediafire/uploader.py#L198-L289
def upload(self, fd, name=None, folder_key=None, filedrop_key=None, path=None, action_on_duplicate=None): """Upload file, returns UploadResult object fd -- file-like object to upload from, expects exclusive access name -- file name folder_key -- folderkey of the target folder path -- path to file relative to folder_key filedrop_key -- filedrop to use instead of folder_key action_on_duplicate -- skip, keep, replace """ # Get file handle content length in the most reliable way fd.seek(0, os.SEEK_END) size = fd.tell() fd.seek(0, os.SEEK_SET) if size > UPLOAD_SIMPLE_LIMIT_BYTES: resumable = True else: resumable = False logger.debug("Calculating checksum") hash_info = compute_hash_info(fd) if hash_info.size != size: # Has the file changed beween computing the hash # and calling upload()? raise ValueError("hash_info.size mismatch") upload_info = _UploadInfo(fd=fd, name=name, folder_key=folder_key, hash_info=hash_info, size=size, path=path, filedrop_key=filedrop_key, action_on_duplicate=action_on_duplicate) # Check whether file is present check_result = self._upload_check(upload_info, resumable) upload_result = None upload_func = None folder_key = check_result.get('folder_key', None) if folder_key is not None: # We know precisely what folder_key to use, drop path upload_info.folder_key = folder_key upload_info.path = None if check_result['hash_exists'] == 'yes': # file exists somewhere in MediaFire if check_result['in_folder'] == 'yes' and \ check_result['file_exists'] == 'yes': # file exists in this directory different_hash = check_result.get('different_hash', 'no') if different_hash == 'no': # file is already there upload_func = self._upload_none if not upload_func: # different hash or in other folder upload_func = self._upload_instant if not upload_func: if resumable: resumable_upload_info = check_result['resumable_upload'] upload_info.hash_info = compute_hash_info( fd, int(resumable_upload_info['unit_size'])) upload_func = self._upload_resumable else: upload_func = self._upload_simple # Retry retriable exceptions retries = UPLOAD_RETRY_COUNT while retries > 0: try: # Provide check_result to avoid calling API twice upload_result = upload_func(upload_info, check_result) except (RetriableUploadError, MediaFireConnectionError): retries -= 1 logger.exception("%s failed (%d retries left)", upload_func.__name__, retries) # Refresh check_result for next iteration check_result = self._upload_check(upload_info, resumable) except Exception: logger.exception("%s failed", upload_func) break else: break if upload_result is None: raise UploadError("Upload failed") return upload_result
[ "def", "upload", "(", "self", ",", "fd", ",", "name", "=", "None", ",", "folder_key", "=", "None", ",", "filedrop_key", "=", "None", ",", "path", "=", "None", ",", "action_on_duplicate", "=", "None", ")", ":", "# Get file handle content length in the most reli...
Upload file, returns UploadResult object fd -- file-like object to upload from, expects exclusive access name -- file name folder_key -- folderkey of the target folder path -- path to file relative to folder_key filedrop_key -- filedrop to use instead of folder_key action_on_duplicate -- skip, keep, replace
[ "Upload", "file", "returns", "UploadResult", "object" ]
python
train
guaix-ucm/numina
numina/array/display/iofunctions.py
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/display/iofunctions.py#L7-L67
def readc(prompt, default=None, valid=None, question_mark=True): """Return a single character read from keyboard Parameters ---------- prompt : str Prompt string. default : str Default value. valid : str String providing valid characters. If None, all characters are valid (default). question_mark : bool If True, display question mark after prompt. Returns ------- cresult : str Read value. """ cresult = None # Avoid PyCharm warning # question mark if question_mark: cquestion_mark = ' ? ' else: cquestion_mark = '' # main loop loop = True while loop: # display prompt if default is None: print(prompt + cquestion_mark, end='') sys.stdout.flush() else: print(prompt + ' [' + str(default) + ']' + cquestion_mark, end='') sys.stdout.flush() # read user's input cresult = sys.stdin.readline().strip() if cresult == '' and default is not None: cresult = str(default) if len(cresult) == 1: # check that all the characters are valid loop = False if valid is not None: for c in cresult: if c not in str(valid): print('*** Error: invalid characters found.') print('*** Valid characters are:', valid) print('*** Try again!') loop = True else: print('*** Error: invalid string length. Try again!') return cresult
[ "def", "readc", "(", "prompt", ",", "default", "=", "None", ",", "valid", "=", "None", ",", "question_mark", "=", "True", ")", ":", "cresult", "=", "None", "# Avoid PyCharm warning", "# question mark", "if", "question_mark", ":", "cquestion_mark", "=", "' ? '"...
Return a single character read from keyboard Parameters ---------- prompt : str Prompt string. default : str Default value. valid : str String providing valid characters. If None, all characters are valid (default). question_mark : bool If True, display question mark after prompt. Returns ------- cresult : str Read value.
[ "Return", "a", "single", "character", "read", "from", "keyboard" ]
python
train
StyXman/ayrton
ayrton/parser/error.py
https://github.com/StyXman/ayrton/blob/e1eed5c7ef230e3c2340a1f0bf44c72bbdc0debb/ayrton/parser/error.py#L300-L312
def get_traceback(self): """Calling this marks the PyTraceback as escaped, i.e. it becomes accessible and inspectable by app-level Python code. For the JIT. Note that this has no effect if there are already several traceback frames recorded, because in this case they are already marked as escaping by executioncontext.leave() being called with got_exception=True. """ from pypy.interpreter.pytraceback import PyTraceback tb = self._application_traceback if tb is not None and isinstance(tb, PyTraceback): tb.frame.mark_as_escaped() return tb
[ "def", "get_traceback", "(", "self", ")", ":", "from", "pypy", ".", "interpreter", ".", "pytraceback", "import", "PyTraceback", "tb", "=", "self", ".", "_application_traceback", "if", "tb", "is", "not", "None", "and", "isinstance", "(", "tb", ",", "PyTraceba...
Calling this marks the PyTraceback as escaped, i.e. it becomes accessible and inspectable by app-level Python code. For the JIT. Note that this has no effect if there are already several traceback frames recorded, because in this case they are already marked as escaping by executioncontext.leave() being called with got_exception=True.
[ "Calling", "this", "marks", "the", "PyTraceback", "as", "escaped", "i", ".", "e", ".", "it", "becomes", "accessible", "and", "inspectable", "by", "app", "-", "level", "Python", "code", ".", "For", "the", "JIT", ".", "Note", "that", "this", "has", "no", ...
python
train
numberly/appnexus-client
appnexus/client.py
https://github.com/numberly/appnexus-client/blob/d6a813449ab6fd93bfbceaa937a168fa9a78b890/appnexus/client.py#L144-L146
def get(self, service_name, **kwargs): """Retrieve data from AppNexus API""" return self._send(requests.get, service_name, **kwargs)
[ "def", "get", "(", "self", ",", "service_name", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_send", "(", "requests", ".", "get", ",", "service_name", ",", "*", "*", "kwargs", ")" ]
Retrieve data from AppNexus API
[ "Retrieve", "data", "from", "AppNexus", "API" ]
python
train
mgraffg/EvoDAG
EvoDAG/gp.py
https://github.com/mgraffg/EvoDAG/blob/e11fa1fd1ca9e69cca92696c86661a3dc7b3a1d5/EvoDAG/gp.py#L43-L56
def _eval(self): "Evaluates a individual using recursion and self._pos as pointer" pos = self._pos self._pos += 1 node = self._ind[pos] if isinstance(node, Function): args = [self._eval() for x in range(node.nargs)] node.eval(args) for x in args: x.hy = None x.hy_test = None else: node.eval(self._X) return node
[ "def", "_eval", "(", "self", ")", ":", "pos", "=", "self", ".", "_pos", "self", ".", "_pos", "+=", "1", "node", "=", "self", ".", "_ind", "[", "pos", "]", "if", "isinstance", "(", "node", ",", "Function", ")", ":", "args", "=", "[", "self", "."...
Evaluates a individual using recursion and self._pos as pointer
[ "Evaluates", "a", "individual", "using", "recursion", "and", "self", ".", "_pos", "as", "pointer" ]
python
train
djordon/queueing-tool
queueing_tool/network/queue_network.py
https://github.com/djordon/queueing-tool/blob/ccd418cf647ac03a54f78ba5e3725903f541b808/queueing_tool/network/queue_network.py#L667-L741
def draw(self, update_colors=True, line_kwargs=None, scatter_kwargs=None, **kwargs): """Draws the network. The coloring of the network corresponds to the number of agents at each queue. Parameters ---------- update_colors : ``bool`` (optional, default: ``True``). Specifies whether all the colors are updated. line_kwargs : dict (optional, default: None) Any keyword arguments accepted by :class:`~matplotlib.collections.LineCollection` scatter_kwargs : dict (optional, default: None) Any keyword arguments accepted by :meth:`~matplotlib.axes.Axes.scatter`. bgcolor : list (optional, keyword only) A list with 4 floats representing a RGBA color. The default is defined in ``self.colors['bgcolor']``. figsize : tuple (optional, keyword only, default: ``(7, 7)``) The width and height of the canvas in inches. **kwargs Any parameters to pass to :meth:`.QueueNetworkDiGraph.draw_graph`. Notes ----- This method relies heavily on :meth:`.QueueNetworkDiGraph.draw_graph`. Also, there is a parameter that sets the background color of the canvas, which is the ``bgcolor`` parameter. Examples -------- To draw the current state of the network, call: >>> import queueing_tool as qt >>> g = qt.generate_pagerank_graph(100, seed=13) >>> net = qt.QueueNetwork(g, seed=13) >>> net.initialize(100) >>> net.simulate(1200) >>> net.draw() # doctest: +SKIP If you specify a file name and location, the drawing will be saved to disk. For example, to save the drawing to the current working directory do the following: >>> net.draw(fname="state.png", scatter_kwargs={'s': 40}) # doctest: +SKIP .. figure:: current_state1.png :align: center The shade of each edge depicts how many agents are located at the corresponding queue. The shade of each vertex is determined by the total number of inbound agents. Although loops are not visible by default, the vertex that corresponds to a loop shows how many agents are in that loop. There are several additional parameters that can be passed -- all :meth:`.QueueNetworkDiGraph.draw_graph` parameters are valid. For example, to show the edges as dashed lines do the following. >>> net.draw(line_kwargs={'linestyle': 'dashed'}) # doctest: +SKIP """ if not HAS_MATPLOTLIB: raise ImportError("matplotlib is necessary to draw the network.") if update_colors: self._update_all_colors() if 'bgcolor' not in kwargs: kwargs['bgcolor'] = self.colors['bgcolor'] self.g.draw_graph(line_kwargs=line_kwargs, scatter_kwargs=scatter_kwargs, **kwargs)
[ "def", "draw", "(", "self", ",", "update_colors", "=", "True", ",", "line_kwargs", "=", "None", ",", "scatter_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "HAS_MATPLOTLIB", ":", "raise", "ImportError", "(", "\"matplotlib is necessary...
Draws the network. The coloring of the network corresponds to the number of agents at each queue. Parameters ---------- update_colors : ``bool`` (optional, default: ``True``). Specifies whether all the colors are updated. line_kwargs : dict (optional, default: None) Any keyword arguments accepted by :class:`~matplotlib.collections.LineCollection` scatter_kwargs : dict (optional, default: None) Any keyword arguments accepted by :meth:`~matplotlib.axes.Axes.scatter`. bgcolor : list (optional, keyword only) A list with 4 floats representing a RGBA color. The default is defined in ``self.colors['bgcolor']``. figsize : tuple (optional, keyword only, default: ``(7, 7)``) The width and height of the canvas in inches. **kwargs Any parameters to pass to :meth:`.QueueNetworkDiGraph.draw_graph`. Notes ----- This method relies heavily on :meth:`.QueueNetworkDiGraph.draw_graph`. Also, there is a parameter that sets the background color of the canvas, which is the ``bgcolor`` parameter. Examples -------- To draw the current state of the network, call: >>> import queueing_tool as qt >>> g = qt.generate_pagerank_graph(100, seed=13) >>> net = qt.QueueNetwork(g, seed=13) >>> net.initialize(100) >>> net.simulate(1200) >>> net.draw() # doctest: +SKIP If you specify a file name and location, the drawing will be saved to disk. For example, to save the drawing to the current working directory do the following: >>> net.draw(fname="state.png", scatter_kwargs={'s': 40}) # doctest: +SKIP .. figure:: current_state1.png :align: center The shade of each edge depicts how many agents are located at the corresponding queue. The shade of each vertex is determined by the total number of inbound agents. Although loops are not visible by default, the vertex that corresponds to a loop shows how many agents are in that loop. There are several additional parameters that can be passed -- all :meth:`.QueueNetworkDiGraph.draw_graph` parameters are valid. For example, to show the edges as dashed lines do the following. >>> net.draw(line_kwargs={'linestyle': 'dashed'}) # doctest: +SKIP
[ "Draws", "the", "network", ".", "The", "coloring", "of", "the", "network", "corresponds", "to", "the", "number", "of", "agents", "at", "each", "queue", "." ]
python
valid
Qiskit/qiskit-terra
qiskit/extensions/standard/cswap.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/extensions/standard/cswap.py#L53-L55
def cswap(self, ctl, tgt1, tgt2): """Apply Fredkin to circuit.""" return self.append(FredkinGate(), [ctl, tgt1, tgt2], [])
[ "def", "cswap", "(", "self", ",", "ctl", ",", "tgt1", ",", "tgt2", ")", ":", "return", "self", ".", "append", "(", "FredkinGate", "(", ")", ",", "[", "ctl", ",", "tgt1", ",", "tgt2", "]", ",", "[", "]", ")" ]
Apply Fredkin to circuit.
[ "Apply", "Fredkin", "to", "circuit", "." ]
python
test
knipknap/exscript
Exscript/protocols/protocol.py
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/protocols/protocol.py#L954-L974
def execute(self, command, consume=True): """ Sends the given data to the remote host (with a newline appended) and waits for a prompt in the response. The prompt attempts to use a sane default that works with many devices running Unix, IOS, IOS-XR, or Junos and others. If that fails, a custom prompt may also be defined using the set_prompt() method. This method also modifies the value of the response (self.response) attribute, for details please see the documentation of the expect() method. :type command: string :param command: The data that is sent to the remote host. :type consume: boolean (Default: True) :param consume: Whether to consume the prompt from the buffer or not. :rtype: int, re.MatchObject :return: The index of the prompt regular expression that matched, and the match object. """ self.send(command + '\r') return self.expect_prompt(consume)
[ "def", "execute", "(", "self", ",", "command", ",", "consume", "=", "True", ")", ":", "self", ".", "send", "(", "command", "+", "'\\r'", ")", "return", "self", ".", "expect_prompt", "(", "consume", ")" ]
Sends the given data to the remote host (with a newline appended) and waits for a prompt in the response. The prompt attempts to use a sane default that works with many devices running Unix, IOS, IOS-XR, or Junos and others. If that fails, a custom prompt may also be defined using the set_prompt() method. This method also modifies the value of the response (self.response) attribute, for details please see the documentation of the expect() method. :type command: string :param command: The data that is sent to the remote host. :type consume: boolean (Default: True) :param consume: Whether to consume the prompt from the buffer or not. :rtype: int, re.MatchObject :return: The index of the prompt regular expression that matched, and the match object.
[ "Sends", "the", "given", "data", "to", "the", "remote", "host", "(", "with", "a", "newline", "appended", ")", "and", "waits", "for", "a", "prompt", "in", "the", "response", ".", "The", "prompt", "attempts", "to", "use", "a", "sane", "default", "that", ...
python
train
ngmarchant/oasis
oasis/experiments.py
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/experiments.py#L216-L239
def calc_confusion_matrix(self, printout = False): """ Calculates number of TP, FP, TN, FN """ if self.labels is None: raise DataError("Cannot calculate confusion matrix before data " "has been read.") if self.preds is None: raise DataError("Predictions not available. Please run " "`scores_to_preds` before calculating confusion " "matrix") self.TP = np.sum(np.logical_and(self.preds == 1, self.labels == 1)) self.TN = np.sum(np.logical_and(self.preds == 0, self.labels == 0)) self.FP = np.sum(np.logical_and(self.preds == 1, self.labels == 0)) self.FN = np.sum(np.logical_and(self.preds == 0, self.labels == 1)) if printout: print("Contingency matrix is:") print("----------------------") print("TP: {} \t FN: {}".format(self.TP,self.FN)) print("FP: {} \t TN: {}".format(self.FP,self.TN)) print("\n")
[ "def", "calc_confusion_matrix", "(", "self", ",", "printout", "=", "False", ")", ":", "if", "self", ".", "labels", "is", "None", ":", "raise", "DataError", "(", "\"Cannot calculate confusion matrix before data \"", "\"has been read.\"", ")", "if", "self", ".", "pr...
Calculates number of TP, FP, TN, FN
[ "Calculates", "number", "of", "TP", "FP", "TN", "FN" ]
python
train
trec-kba/streamcorpus-pipeline
streamcorpus_pipeline/_hyperlink_labels.py
https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_hyperlink_labels.py#L254-L295
def byte_href_anchors(self, chars=False): ''' simple, regex-based extractor of anchor tags, so we can compute BYTE offsets for anchor texts and associate them with their href. Generates tuple(href_string, first_byte, byte_length, anchor_text) ''' input_buffer = self.clean_html if chars: input_buffer = input_buffer.decode('utf8') idx = 0 ## split doc up into pieces that end on an anchor tag parts = input_buffer.split('</a>') assert len('</a>'.join(parts) ) == len(input_buffer) for part in parts: ## try to get an A tag out: m = anchors_re.match(part) if not m: idx += len(part) + 4 continue before = m.group('before') ahref = m.group('ahref') ## increment the index to get line number for the anchor idx += len(before) + len(ahref) first = idx length = len(m.group('anchor')) ## update the index for the next loop # include anchor plus the </a> idx += length + 4 if chars: yield m.group('href').encode('utf8'), first, length, m.group('anchor').encode('utf8') else: yield m.group('href'), first, length, m.group('anchor') assert idx - 4 == len(input_buffer)
[ "def", "byte_href_anchors", "(", "self", ",", "chars", "=", "False", ")", ":", "input_buffer", "=", "self", ".", "clean_html", "if", "chars", ":", "input_buffer", "=", "input_buffer", ".", "decode", "(", "'utf8'", ")", "idx", "=", "0", "## split doc up into ...
simple, regex-based extractor of anchor tags, so we can compute BYTE offsets for anchor texts and associate them with their href. Generates tuple(href_string, first_byte, byte_length, anchor_text)
[ "simple", "regex", "-", "based", "extractor", "of", "anchor", "tags", "so", "we", "can", "compute", "BYTE", "offsets", "for", "anchor", "texts", "and", "associate", "them", "with", "their", "href", ".", "Generates", "tuple", "(", "href_string", "first_byte", ...
python
test
marrow/cinje
cinje/util.py
https://github.com/marrow/cinje/blob/413bdac7242020ce8379d272720c649a9196daa2/cinje/util.py#L475-L511
def stream(self): """The workhorse of cinje: transform input lines and emit output lines. After constructing an instance with a set of input lines iterate this property to generate the template. """ if 'init' not in self.flag: root = True self.prepare() else: root = False # Track which lines were generated in response to which lines of source code. # The end result is that there is one entry here for every line emitted, each integer representing the source # line number that triggered it. If any lines are returned with missing line numbers, they're inferred from # the last entry already in the list. # Fun fact: this list is backwards; we optimize by using a deque and appending to the left edge. this updates # the head of a linked list; the whole thing needs to be reversed to make sense. mapping = self.mapping for line in self.input: handler = self.classify(line) if line.kind == 'code' and line.stripped == 'end': # Exit the current child scope. return assert handler, "Unable to identify handler for line; this should be impossible!" self.input.push(line) # Put it back so it can be consumed by the handler. for line in handler(self): # This re-indents the code to match, if missing explicit scope. if root: mapping.appendleft(line.number or mapping[0]) # Track source line number. if line.scope is None: line = line.clone(scope=self.scope) yield line
[ "def", "stream", "(", "self", ")", ":", "if", "'init'", "not", "in", "self", ".", "flag", ":", "root", "=", "True", "self", ".", "prepare", "(", ")", "else", ":", "root", "=", "False", "# Track which lines were generated in response to which lines of source code...
The workhorse of cinje: transform input lines and emit output lines. After constructing an instance with a set of input lines iterate this property to generate the template.
[ "The", "workhorse", "of", "cinje", ":", "transform", "input", "lines", "and", "emit", "output", "lines", ".", "After", "constructing", "an", "instance", "with", "a", "set", "of", "input", "lines", "iterate", "this", "property", "to", "generate", "the", "temp...
python
train
aws/aws-dynamodb-encryption-python
src/dynamodb_encryption_sdk/internal/crypto/encryption.py
https://github.com/aws/aws-dynamodb-encryption-python/blob/8de3bbe13df39c59b21bf431010f7acfcf629a2f/src/dynamodb_encryption_sdk/internal/crypto/encryption.py#L52-L67
def decrypt_attribute(attribute_name, attribute, decryption_key, algorithm): # type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.RAW_ATTRIBUTE """Decrypt a single DynamoDB attribute. :param str attribute_name: DynamoDB attribute name :param dict attribute: Encrypted DynamoDB attribute :param DelegatedKey encryption_key: DelegatedKey to use to encrypt the attribute :param str algorithm: Decryption algorithm descriptor (passed to encryption_key as algorithm) :returns: Plaintext DynamoDB attribute :rtype: dict """ encrypted_attribute = attribute[Tag.BINARY.dynamodb_tag] decrypted_attribute = decryption_key.decrypt( algorithm=algorithm, name=attribute_name, ciphertext=encrypted_attribute ) return deserialize_attribute(decrypted_attribute)
[ "def", "decrypt_attribute", "(", "attribute_name", ",", "attribute", ",", "decryption_key", ",", "algorithm", ")", ":", "# type: (Text, dynamodb_types.RAW_ATTRIBUTE, DelegatedKey, Text) -> dynamodb_types.RAW_ATTRIBUTE", "encrypted_attribute", "=", "attribute", "[", "Tag", ".", ...
Decrypt a single DynamoDB attribute. :param str attribute_name: DynamoDB attribute name :param dict attribute: Encrypted DynamoDB attribute :param DelegatedKey encryption_key: DelegatedKey to use to encrypt the attribute :param str algorithm: Decryption algorithm descriptor (passed to encryption_key as algorithm) :returns: Plaintext DynamoDB attribute :rtype: dict
[ "Decrypt", "a", "single", "DynamoDB", "attribute", "." ]
python
train
ltalirz/aiida-gudhi
aiida_gudhi/calculations/rips.py
https://github.com/ltalirz/aiida-gudhi/blob/81ebec782ddff3ab97a3e3242b809fec989fa4b9/aiida_gudhi/calculations/rips.py#L118-L155
def _prepare_for_submission(self, tempfolder, inputdict): """ Create input files. :param tempfolder: aiida.common.folders.Folder subclass where the plugin should put all its files. :param inputdict: dictionary of the input nodes as they would be returned by get_inputs_dict """ parameters, code, distance_matrix, symlink = \ self._validate_inputs(inputdict) # Prepare CalcInfo to be returned to aiida calcinfo = CalcInfo() calcinfo.uuid = self.uuid calcinfo.remote_copy_list = [] calcinfo.retrieve_list = parameters.output_files codeinfo = CodeInfo() codeinfo.code_uuid = code.uuid if distance_matrix is not None: calcinfo.local_copy_list = [ [ distance_matrix.get_file_abs_path(), distance_matrix.filename ], ] codeinfo.cmdline_params = parameters.cmdline_params( distance_matrix_file_name=distance_matrix.filename) else: calcinfo.remote_symlink_list = [symlink] codeinfo.cmdline_params = parameters.cmdline_params( remote_folder_path=self._REMOTE_FOLDER_LINK) calcinfo.codes_info = [codeinfo] return calcinfo
[ "def", "_prepare_for_submission", "(", "self", ",", "tempfolder", ",", "inputdict", ")", ":", "parameters", ",", "code", ",", "distance_matrix", ",", "symlink", "=", "self", ".", "_validate_inputs", "(", "inputdict", ")", "# Prepare CalcInfo to be returned to aiida", ...
Create input files. :param tempfolder: aiida.common.folders.Folder subclass where the plugin should put all its files. :param inputdict: dictionary of the input nodes as they would be returned by get_inputs_dict
[ "Create", "input", "files", "." ]
python
train
spacetelescope/stsci.tools
lib/stsci/tools/fileutil.py
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L154-L159
def getLTime(): """Returns a formatted string with the current local time.""" _ltime = _time.localtime(_time.time()) tlm_str = _time.strftime('%H:%M:%S (%d/%m/%Y)', _ltime) return tlm_str
[ "def", "getLTime", "(", ")", ":", "_ltime", "=", "_time", ".", "localtime", "(", "_time", ".", "time", "(", ")", ")", "tlm_str", "=", "_time", ".", "strftime", "(", "'%H:%M:%S (%d/%m/%Y)'", ",", "_ltime", ")", "return", "tlm_str" ]
Returns a formatted string with the current local time.
[ "Returns", "a", "formatted", "string", "with", "the", "current", "local", "time", "." ]
python
train
ladybug-tools/ladybug
ladybug/datacollection.py
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/datacollection.py#L129-L139
def filter_by_hoys(self, hoys): """Filter the Data Collection based on an analysis period. Args: hoys: A List of hours of the year 0..8759 Return: A new Data Collection with filtered data """ _moys = tuple(int(hour * 60) for hour in hoys) return self.filter_by_moys(_moys)
[ "def", "filter_by_hoys", "(", "self", ",", "hoys", ")", ":", "_moys", "=", "tuple", "(", "int", "(", "hour", "*", "60", ")", "for", "hour", "in", "hoys", ")", "return", "self", ".", "filter_by_moys", "(", "_moys", ")" ]
Filter the Data Collection based on an analysis period. Args: hoys: A List of hours of the year 0..8759 Return: A new Data Collection with filtered data
[ "Filter", "the", "Data", "Collection", "based", "on", "an", "analysis", "period", "." ]
python
train
walkr/nanoservice
benchmarks/bench_pub_sub_auth.py
https://github.com/walkr/nanoservice/blob/e2098986b1baa5f283167ae487d14f3c6c21961a/benchmarks/bench_pub_sub_auth.py#L13-L31
def start_service(addr, n, authenticator): """ Start a service """ s = Subscriber(addr, authenticator=authenticator) def do_something(line): pass s.subscribe('test', do_something) started = time.time() for _ in range(n): s.process() s.socket.close() duration = time.time() - started print('Subscriber service stats:') util.print_stats(n, duration) return
[ "def", "start_service", "(", "addr", ",", "n", ",", "authenticator", ")", ":", "s", "=", "Subscriber", "(", "addr", ",", "authenticator", "=", "authenticator", ")", "def", "do_something", "(", "line", ")", ":", "pass", "s", ".", "subscribe", "(", "'test'...
Start a service
[ "Start", "a", "service" ]
python
train
splunk/splunk-sdk-python
examples/analytics/bottle.py
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1576-L1604
def path_shift(script_name, path_info, shift=1): ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1) ''' if shift == 0: return script_name, path_info pathlist = path_info.strip('/').split('/') scriptlist = script_name.strip('/').split('/') if pathlist and pathlist[0] == '': pathlist = [] if scriptlist and scriptlist[0] == '': scriptlist = [] if shift > 0 and shift <= len(pathlist): moved = pathlist[:shift] scriptlist = scriptlist + moved pathlist = pathlist[shift:] elif shift < 0 and shift >= -len(scriptlist): moved = scriptlist[shift:] pathlist = moved + pathlist scriptlist = scriptlist[:shift] else: empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO' raise AssertionError("Cannot shift. Nothing left from %s" % empty) new_script_name = '/' + '/'.join(scriptlist) new_path_info = '/' + '/'.join(pathlist) if path_info.endswith('/') and pathlist: new_path_info += '/' return new_script_name, new_path_info
[ "def", "path_shift", "(", "script_name", ",", "path_info", ",", "shift", "=", "1", ")", ":", "if", "shift", "==", "0", ":", "return", "script_name", ",", "path_info", "pathlist", "=", "path_info", ".", "strip", "(", "'/'", ")", ".", "split", "(", "'/'"...
Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. :return: The modified paths. :param script_name: The SCRIPT_NAME path. :param script_name: The PATH_INFO path. :param shift: The number of path fragments to shift. May be negative to change the shift direction. (default: 1)
[ "Shift", "path", "fragments", "from", "PATH_INFO", "to", "SCRIPT_NAME", "and", "vice", "versa", "." ]
python
train
perrygeo/simanneal
examples/watershed/shapefile.py
https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L347-L353
def __recordFmt(self): """Calculates the size of a .shp geometry record.""" if not self.numRecords: self.__dbfHeader() fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in self.fields]) fmtSize = calcsize(fmt) return (fmt, fmtSize)
[ "def", "__recordFmt", "(", "self", ")", ":", "if", "not", "self", ".", "numRecords", ":", "self", ".", "__dbfHeader", "(", ")", "fmt", "=", "''", ".", "join", "(", "[", "'%ds'", "%", "fieldinfo", "[", "2", "]", "for", "fieldinfo", "in", "self", "."...
Calculates the size of a .shp geometry record.
[ "Calculates", "the", "size", "of", "a", ".", "shp", "geometry", "record", "." ]
python
train
reorx/torext
torext/app.py
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L223-L240
def route_many(self, *args, **kwargs): """ >>> from torext.route import include >>> app = TorextApp() >>> app.route_many([ ... ('/account', include('account.views')), ... ('/account', include('account.views')), ... ], '^account.example.com$') """ if len(args) == 2: prefix, rules = args elif len(args) == 1: prefix = None rules = args[0] else: raise ValueError('The amount of args of route_many method can only be one or two') router = Router(rules, prefix=prefix) self.add_handlers(router.get_handlers(), host=kwargs.get('host'))
[ "def", "route_many", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "2", ":", "prefix", ",", "rules", "=", "args", "elif", "len", "(", "args", ")", "==", "1", ":", "prefix", "=", "None", ...
>>> from torext.route import include >>> app = TorextApp() >>> app.route_many([ ... ('/account', include('account.views')), ... ('/account', include('account.views')), ... ], '^account.example.com$')
[ ">>>", "from", "torext", ".", "route", "import", "include", ">>>", "app", "=", "TorextApp", "()", ">>>", "app", ".", "route_many", "(", "[", "...", "(", "/", "account", "include", "(", "account", ".", "views", "))", "...", "(", "/", "account", "include...
python
train
google/flatbuffers
python/flatbuffers/builder.py
https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L735-L753
def vtableEqual(a, objectStart, b): """vtableEqual compares an unwritten vtable to a written vtable.""" N.enforce_number(objectStart, N.UOffsetTFlags) if len(a) * N.VOffsetTFlags.bytewidth != len(b): return False for i, elem in enumerate(a): x = encode.Get(packer.voffset, b, i * N.VOffsetTFlags.bytewidth) # Skip vtable entries that indicate a default value. if x == 0 and elem == 0: pass else: y = objectStart - elem if x != y: return False return True
[ "def", "vtableEqual", "(", "a", ",", "objectStart", ",", "b", ")", ":", "N", ".", "enforce_number", "(", "objectStart", ",", "N", ".", "UOffsetTFlags", ")", "if", "len", "(", "a", ")", "*", "N", ".", "VOffsetTFlags", ".", "bytewidth", "!=", "len", "(...
vtableEqual compares an unwritten vtable to a written vtable.
[ "vtableEqual", "compares", "an", "unwritten", "vtable", "to", "a", "written", "vtable", "." ]
python
train
niklasf/python-chess
chess/engine.py
https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/engine.py#L2314-L2325
def close(self) -> None: """ Closes the transport and the background event loop as soon as possible. """ def _shutdown() -> None: self.transport.close() self.shutdown_event.set() with self._shutdown_lock: if not self._shutdown: self._shutdown = True self.protocol.loop.call_soon_threadsafe(_shutdown)
[ "def", "close", "(", "self", ")", "->", "None", ":", "def", "_shutdown", "(", ")", "->", "None", ":", "self", ".", "transport", ".", "close", "(", ")", "self", ".", "shutdown_event", ".", "set", "(", ")", "with", "self", ".", "_shutdown_lock", ":", ...
Closes the transport and the background event loop as soon as possible.
[ "Closes", "the", "transport", "and", "the", "background", "event", "loop", "as", "soon", "as", "possible", "." ]
python
train
glitchassassin/lackey
lackey/InputEmulation.py
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/InputEmulation.py#L59-L73
def moveSpeed(self, location, seconds=0.3): """ Moves cursor to specified ``Location`` over ``seconds``. If ``seconds`` is 0, moves the cursor immediately. Used for smooth somewhat-human-like motion. """ self._lock.acquire() original_location = mouse.get_position() mouse.move(location.x, location.y, duration=seconds) if mouse.get_position() == original_location and original_location != location.getTuple(): raise IOError(""" Unable to move mouse cursor. This may happen if you're trying to automate a program running as Administrator with a script running as a non-elevated user. """) self._lock.release()
[ "def", "moveSpeed", "(", "self", ",", "location", ",", "seconds", "=", "0.3", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "original_location", "=", "mouse", ".", "get_position", "(", ")", "mouse", ".", "move", "(", "location", ".", "x", ...
Moves cursor to specified ``Location`` over ``seconds``. If ``seconds`` is 0, moves the cursor immediately. Used for smooth somewhat-human-like motion.
[ "Moves", "cursor", "to", "specified", "Location", "over", "seconds", "." ]
python
train
juju/theblues
theblues/identity_manager.py
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/identity_manager.py#L33-L42
def get_user(self, username, macaroons): """Fetch user data. Raise a ServerError if an error occurs in the request process. @param username the user's name. @param macaroons the encoded macaroons string. """ url = '{}u/{}'.format(self.url, username) return make_request(url, timeout=self.timeout, macaroons=macaroons)
[ "def", "get_user", "(", "self", ",", "username", ",", "macaroons", ")", ":", "url", "=", "'{}u/{}'", ".", "format", "(", "self", ".", "url", ",", "username", ")", "return", "make_request", "(", "url", ",", "timeout", "=", "self", ".", "timeout", ",", ...
Fetch user data. Raise a ServerError if an error occurs in the request process. @param username the user's name. @param macaroons the encoded macaroons string.
[ "Fetch", "user", "data", "." ]
python
train
langloisjp/tstore
tstore/pgtablestorage.py
https://github.com/langloisjp/tstore/blob/b438f8aaf09117bf6f922ba06ae5cf46b7b97a57/tstore/pgtablestorage.py#L398-L409
def sqldelete(table, where): """Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5]) """ validate_name(table) (whereclause, wherevalues) = sqlwhere(where) sql = "delete from {}".format(table) if whereclause: sql += " where " + whereclause return (sql, wherevalues)
[ "def", "sqldelete", "(", "table", ",", "where", ")", ":", "validate_name", "(", "table", ")", "(", "whereclause", ",", "wherevalues", ")", "=", "sqlwhere", "(", "where", ")", "sql", "=", "\"delete from {}\"", ".", "format", "(", "table", ")", "if", "wher...
Generates SQL delete from ... where ... >>> sqldelete('t', {'id': 5}) ('delete from t where id=%s', [5])
[ "Generates", "SQL", "delete", "from", "...", "where", "..." ]
python
train
chaimleib/intervaltree
intervaltree/node.py
https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/node.py#L205-L214
def remove(self, interval): """ Returns self after removing the interval and balancing. If interval is not present, raise ValueError. """ # since this is a list, called methods can set this to [1], # making it true done = [] return self.remove_interval_helper(interval, done, should_raise_error=True)
[ "def", "remove", "(", "self", ",", "interval", ")", ":", "# since this is a list, called methods can set this to [1],", "# making it true", "done", "=", "[", "]", "return", "self", ".", "remove_interval_helper", "(", "interval", ",", "done", ",", "should_raise_error", ...
Returns self after removing the interval and balancing. If interval is not present, raise ValueError.
[ "Returns", "self", "after", "removing", "the", "interval", "and", "balancing", "." ]
python
train
sosy-lab/benchexec
benchexec/tablegenerator/__init__.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/tablegenerator/__init__.py#L214-L228
def _get_columns_relevant_for_diff(columns_to_show): """ Extract columns that are relevant for the diff table. @param columns_to_show: (list) A list of columns that should be shown @return: (set) Set of columns that are relevant for the diff table. If none is marked relevant, the column named "status" will be returned in the set. """ cols = set([col.title for col in columns_to_show if col.relevant_for_diff]) if len(cols) == 0: return set( [col.title for col in columns_to_show if col.title == "status"]) else: return cols
[ "def", "_get_columns_relevant_for_diff", "(", "columns_to_show", ")", ":", "cols", "=", "set", "(", "[", "col", ".", "title", "for", "col", "in", "columns_to_show", "if", "col", ".", "relevant_for_diff", "]", ")", "if", "len", "(", "cols", ")", "==", "0", ...
Extract columns that are relevant for the diff table. @param columns_to_show: (list) A list of columns that should be shown @return: (set) Set of columns that are relevant for the diff table. If none is marked relevant, the column named "status" will be returned in the set.
[ "Extract", "columns", "that", "are", "relevant", "for", "the", "diff", "table", "." ]
python
train
fedora-infra/fedora-messaging
fedora_messaging/_session.py
https://github.com/fedora-infra/fedora-messaging/blob/be3e88534e2b15d579bcd24f9c4b7e795cb7e0b7/fedora_messaging/_session.py#L324-L358
def _on_connection_close(self, connection, reply_code_or_reason, reply_text=None): """ Callback invoked when a previously-opened connection is closed. Args: connection (pika.connection.SelectConnection): The connection that was just closed. reply_code_or_reason (int|Exception): The reason why the channel was closed. In older versions of pika, this is the AMQP code. reply_text (str): The human-readable reason the connection was closed (only in older versions of pika) """ self._channel = None if isinstance(reply_code_or_reason, pika_errs.ConnectionClosed): reply_code = reply_code_or_reason.reply_code reply_text = reply_code_or_reason.reply_text elif isinstance(reply_code_or_reason, int): reply_code = reply_code_or_reason else: reply_code = 0 reply_text = str(reply_code_or_reason) if reply_code == 200: # Normal shutdown, exit the consumer. _log.info("Server connection closed (%s), shutting down", reply_text) connection.ioloop.stop() else: _log.warning( "Connection to %s closed unexpectedly (%d): %s", connection.params.host, reply_code, reply_text, ) self.call_later(1, self.reconnect)
[ "def", "_on_connection_close", "(", "self", ",", "connection", ",", "reply_code_or_reason", ",", "reply_text", "=", "None", ")", ":", "self", ".", "_channel", "=", "None", "if", "isinstance", "(", "reply_code_or_reason", ",", "pika_errs", ".", "ConnectionClosed", ...
Callback invoked when a previously-opened connection is closed. Args: connection (pika.connection.SelectConnection): The connection that was just closed. reply_code_or_reason (int|Exception): The reason why the channel was closed. In older versions of pika, this is the AMQP code. reply_text (str): The human-readable reason the connection was closed (only in older versions of pika)
[ "Callback", "invoked", "when", "a", "previously", "-", "opened", "connection", "is", "closed", "." ]
python
train
dunovank/jupyter-themes
jupyterthemes/stylefx.py
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L400-L420
def set_mathjax_style(style_css, mathfontsize): """Write mathjax settings, set math fontsize """ jax_style = """<script> MathJax.Hub.Config({ "HTML-CSS": { /*preferredFont: "TeX",*/ /*availableFonts: ["TeX", "STIX"],*/ styles: { scale: %d, ".MathJax_Display": { "font-size": %s, } } } });\n</script> """ % (int(mathfontsize), '"{}%"'.format(str(mathfontsize))) style_css += jax_style return style_css
[ "def", "set_mathjax_style", "(", "style_css", ",", "mathfontsize", ")", ":", "jax_style", "=", "\"\"\"<script>\n MathJax.Hub.Config({\n \"HTML-CSS\": {\n /*preferredFont: \"TeX\",*/\n /*availableFonts: [\"TeX\", \"STIX\"],*/\n styles: {\n ...
Write mathjax settings, set math fontsize
[ "Write", "mathjax", "settings", "set", "math", "fontsize" ]
python
train
wilzbach/smarkov
smarkov/hmm.py
https://github.com/wilzbach/smarkov/blob/c98c08cc432e18c5c87fb9a6e013b1b8eaa54d37/smarkov/hmm.py#L93-L96
def _emitHMM(self, token_type, past_states, past_emissions): """ emits a word based on previous tokens """ assert token_type in self.emissions return utils.weighted_choice(self.emissions[token_type].items())
[ "def", "_emitHMM", "(", "self", ",", "token_type", ",", "past_states", ",", "past_emissions", ")", ":", "assert", "token_type", "in", "self", ".", "emissions", "return", "utils", ".", "weighted_choice", "(", "self", ".", "emissions", "[", "token_type", "]", ...
emits a word based on previous tokens
[ "emits", "a", "word", "based", "on", "previous", "tokens" ]
python
train
xtrementl/focus
focus/plugin/modules/timer.py
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/timer.py#L55-L69
def parse_option(self, option, block_name, *values): """ Parse duration option for timer. """ try: if len(values) != 1: raise TypeError self.total_duration = int(values[0]) if self.total_duration <= 0: raise ValueError except ValueError: pattern = u'"{0}" must be an integer > 0' raise ValueError(pattern.format(option))
[ "def", "parse_option", "(", "self", ",", "option", ",", "block_name", ",", "*", "values", ")", ":", "try", ":", "if", "len", "(", "values", ")", "!=", "1", ":", "raise", "TypeError", "self", ".", "total_duration", "=", "int", "(", "values", "[", "0",...
Parse duration option for timer.
[ "Parse", "duration", "option", "for", "timer", "." ]
python
train
proversity-org/bibblio-api-python
bibbliothon/enrichment.py
https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/enrichment.py#L15-L33
def create_content_item(access_token, payload): ''' Name: create_content_item Parameters: access_token, payload (dict) Return: dictionary ''' headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + str(access_token) } request = requests.post(enrichment_url, json=payload, headers=headers) if request.status_code == 201: content_item = request.json() return content_item return {'status': request.status_code, "message": request.text}
[ "def", "create_content_item", "(", "access_token", ",", "payload", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'Authorization'", ":", "'Bearer '", "+", "str", "(", "access_token", ")", "}", "request", "=", "requests", ".", ...
Name: create_content_item Parameters: access_token, payload (dict) Return: dictionary
[ "Name", ":", "create_content_item", "Parameters", ":", "access_token", "payload", "(", "dict", ")", "Return", ":", "dictionary" ]
python
train
chaoss/grimoirelab-perceval
perceval/backends/core/phabricator.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/phabricator.py#L196-L210
def parse_users(raw_json): """Parse a Phabricator users JSON stream. The method parses a JSON stream and returns a list iterator. Each item is a dictionary that contais the user parsed data. :param raw_json: JSON string to parse :returns: a generator of parsed users """ results = json.loads(raw_json) users = results['result'] for u in users: yield u
[ "def", "parse_users", "(", "raw_json", ")", ":", "results", "=", "json", ".", "loads", "(", "raw_json", ")", "users", "=", "results", "[", "'result'", "]", "for", "u", "in", "users", ":", "yield", "u" ]
Parse a Phabricator users JSON stream. The method parses a JSON stream and returns a list iterator. Each item is a dictionary that contais the user parsed data. :param raw_json: JSON string to parse :returns: a generator of parsed users
[ "Parse", "a", "Phabricator", "users", "JSON", "stream", "." ]
python
test
sony/nnabla
python/src/nnabla/experimental/mixed_precision_training.py
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/experimental/mixed_precision_training.py#L86-L143
def update(self): """Monolithic update method. This method calls the following methods with the dynamic loss scaling. 1. solver.zerograd 2. feed data 3. loss.forward 4. loss.backward 5. comm.all_reduce (if it is specified) 6. solver.update """ # Initialize gradients. self.solver.zero_grad() # Forward and backward for _ in range(self.accum_grad): # feed data self.data_feeder() # forward self.loss.forward(clear_no_need_grad=self.clear_buffer) # backward with scale self.loss.backward(self.scale, clear_buffer=self.clear_buffer) # AllReduce if self.comm and len(self.grads) != 0: self.comm.all_reduce(self.grads, division=False, inplace=False) # Check Inf/NaN in grads if self.solver.check_inf_or_nan_grad(): self.scale /= self.scaling_factor self._counter = 0 # Recursively call udpate function until no inf nor nan. self._recursive_count += 1 if self._recursive_count > self._max_recursive_count: self._recursive_count = 0 return # skip return self.update() self._recursive_count = 0 # Rescale grads self.solver.scale_grad(1. / self.scale) # Do some gradient clipping, etc. if self.weight_decay is not None: self.solver.weight_decay(self.weight_decay) # Update self.solver.update() if self._counter > self.N: self.scale *= self.scaling_factor self._counter = 0 self._counter += 1
[ "def", "update", "(", "self", ")", ":", "# Initialize gradients.", "self", ".", "solver", ".", "zero_grad", "(", ")", "# Forward and backward", "for", "_", "in", "range", "(", "self", ".", "accum_grad", ")", ":", "# feed data", "self", ".", "data_feeder", "(...
Monolithic update method. This method calls the following methods with the dynamic loss scaling. 1. solver.zerograd 2. feed data 3. loss.forward 4. loss.backward 5. comm.all_reduce (if it is specified) 6. solver.update
[ "Monolithic", "update", "method", "." ]
python
train
StackStorm/pybind
pybind/nos/v6_0_2f/brocade_ras_ext_rpc/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/brocade_ras_ext_rpc/__init__.py#L176-L199
def _set_show_system_info(self, v, load=False): """ Setter method for show_system_info, mapped from YANG variable /brocade_ras_ext_rpc/show_system_info (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_system_info is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_show_system_info() directly. YANG Description: Shows the system information MAC etc. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=show_system_info.show_system_info, is_leaf=True, yang_name="show-system-info", rest_name="show-system-info", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'hidden': u'rpccmd', u'actionpoint': u'showSystemInfo'}}, namespace='urn:brocade.com:mgmt:brocade-ras-ext', defining_module='brocade-ras-ext', yang_type='rpc', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """show_system_info must be of a type compatible with rpc""", 'defined-type': "rpc", 'generated-type': """YANGDynClass(base=show_system_info.show_system_info, is_leaf=True, yang_name="show-system-info", rest_name="show-system-info", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'hidden': u'rpccmd', u'actionpoint': u'showSystemInfo'}}, namespace='urn:brocade.com:mgmt:brocade-ras-ext', defining_module='brocade-ras-ext', yang_type='rpc', is_config=True)""", }) self.__show_system_info = t if hasattr(self, '_set'): self._set()
[ "def", "_set_show_system_info", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
Setter method for show_system_info, mapped from YANG variable /brocade_ras_ext_rpc/show_system_info (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_system_info is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_show_system_info() directly. YANG Description: Shows the system information MAC etc.
[ "Setter", "method", "for", "show_system_info", "mapped", "from", "YANG", "variable", "/", "brocade_ras_ext_rpc", "/", "show_system_info", "(", "rpc", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "so...
python
train
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/cli/commands/entitlements.py
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L316-L360
def update(ctx, opts, owner_repo_identifier, show_tokens, name, token): """ Update (set) a entitlement in a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents update your-org/your-repo/abcdef123456 --name 'Newly' """ owner, repo, identifier = owner_repo_identifier # Use stderr for messages if the output is something else (e.g. # JSON) use_stderr = opts.output != "pretty" click.secho( "Updating %(identifier)s entitlement for the %(repository)s " "repository ... " % { "identifier": click.style(identifier, bold=True), "repository": click.style(repo, bold=True), }, nl=False, err=use_stderr, ) context_msg = "Failed to update the entitlement!" with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg): with maybe_spinner(opts): entitlement = api.update_entitlement( owner=owner, repo=repo, identifier=identifier, name=name, token=token, show_tokens=show_tokens, ) click.secho("OK", fg="green", err=use_stderr) print_entitlements(opts=opts, data=[entitlement], show_list_info=False)
[ "def", "update", "(", "ctx", ",", "opts", ",", "owner_repo_identifier", ",", "show_tokens", ",", "name", ",", "token", ")", ":", "owner", ",", "repo", ",", "identifier", "=", "owner_repo_identifier", "# Use stderr for messages if the output is something else (e.g. # JS...
Update (set) a entitlement in a repository. - OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org), and the REPO name that has an entitlement identified by IDENTIFIER. All separated by a slash. Example: 'your-org/your-repo/abcdef123456' Full CLI example: $ cloudsmith ents update your-org/your-repo/abcdef123456 --name 'Newly'
[ "Update", "(", "set", ")", "a", "entitlement", "in", "a", "repository", "." ]
python
train
bwhite/hadoopy
hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winresource.py
https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winresource.py#L93-L104
def update_resources_from_dict(self, res, types=None, names=None, languages=None): """ Update or add resources from resource dict. types = a list of resource types to update (None = all) names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ UpdateResourcesFromDict(self.filename, res, types, names, languages)
[ "def", "update_resources_from_dict", "(", "self", ",", "res", ",", "types", "=", "None", ",", "names", "=", "None", ",", "languages", "=", "None", ")", ":", "UpdateResourcesFromDict", "(", "self", ".", "filename", ",", "res", ",", "types", ",", "names", ...
Update or add resources from resource dict. types = a list of resource types to update (None = all) names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all)
[ "Update", "or", "add", "resources", "from", "resource", "dict", ".", "types", "=", "a", "list", "of", "resource", "types", "to", "update", "(", "None", "=", "all", ")", "names", "=", "a", "list", "of", "resource", "names", "to", "update", "(", "None", ...
python
train
dgomes/pyipma
pyipma/api.py
https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L76-L97
async def forecast(self, globalIdLocal): """Retrieve next 5 days forecast.""" data = await self.retrieve(API_FORECAST + "{globalIdLocal}.json". format(globalIdLocal=globalIdLocal)) if not self.weather_type: await self.weather_type_classe() if not self.wind_type: await self.wind_type_classe() _forecasts = [] for forecast in data['data']: Forecast = namedtuple('Forecast', list(forecast.keys())+['description']) _description = self.weather_type[forecast['idWeatherType']] if forecast['classWindSpeed'] != -99.0: _description += ", com vento "+ self.wind_type[forecast['classWindSpeed']] +\ " de " + WIND_DIRECTION[forecast['predWindDir']] vals = [self._to_number(v) for v in forecast.values()] + [_description] _forecasts.append(Forecast(*vals)) return _forecasts
[ "async", "def", "forecast", "(", "self", ",", "globalIdLocal", ")", ":", "data", "=", "await", "self", ".", "retrieve", "(", "API_FORECAST", "+", "\"{globalIdLocal}.json\"", ".", "format", "(", "globalIdLocal", "=", "globalIdLocal", ")", ")", "if", "not", "s...
Retrieve next 5 days forecast.
[ "Retrieve", "next", "5", "days", "forecast", "." ]
python
train
fedora-infra/fmn.rules
fmn/rules/generic.py
https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/generic.py#L26-L44
def not_user_filter(config, message, fasnick=None, *args, **kw): """ Everything except a particular user Use this rule to exclude messages that are associated with one or more users. Specify several users by separating them with a comma ','. """ fasnick = kw.get('fasnick', fasnick) if not fasnick: return False fasnick = (fasnick or []) and fasnick.split(',') valid = True for nick in fasnick: if nick.strip() in fmn.rules.utils.msg2usernames(message, **config): valid = False break return valid
[ "def", "not_user_filter", "(", "config", ",", "message", ",", "fasnick", "=", "None", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "fasnick", "=", "kw", ".", "get", "(", "'fasnick'", ",", "fasnick", ")", "if", "not", "fasnick", ":", "return", "...
Everything except a particular user Use this rule to exclude messages that are associated with one or more users. Specify several users by separating them with a comma ','.
[ "Everything", "except", "a", "particular", "user" ]
python
train
ralphje/imagemounter
imagemounter/volume.py
https://github.com/ralphje/imagemounter/blob/86213781c366cad65096447d91f522f0a3fb4b93/imagemounter/volume.py#L374-L409
def init(self, only_mount=None, skip_mount=None, swallow_exceptions=True): """Generator that mounts this volume and either yields itself or recursively generates its subvolumes. More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by :func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded, or the result of the :func:`init` call on each subvolume is yielded :param only_mount: if specified, only volume indexes in this list are mounted. Volume indexes are strings. :param skip_mount: if specified, volume indexes in this list are not mounted. :param swallow_exceptions: if True, any error occuring when mounting the volume is swallowed and added as an exception attribute to the yielded objects. """ if swallow_exceptions: self.exception = None try: if not self._should_mount(only_mount, skip_mount): yield self return if not self.init_volume(): yield self return except ImageMounterError as e: if swallow_exceptions: self.exception = e else: raise if not self.volumes: yield self else: for v in self.volumes: for s in v.init(only_mount, skip_mount, swallow_exceptions): yield s
[ "def", "init", "(", "self", ",", "only_mount", "=", "None", ",", "skip_mount", "=", "None", ",", "swallow_exceptions", "=", "True", ")", ":", "if", "swallow_exceptions", ":", "self", ".", "exception", "=", "None", "try", ":", "if", "not", "self", ".", ...
Generator that mounts this volume and either yields itself or recursively generates its subvolumes. More specifically, this function will call :func:`load_fsstat_data` (iff *no_stats* is False), followed by :func:`mount`, followed by a call to :func:`detect_mountpoint`, after which ``self`` is yielded, or the result of the :func:`init` call on each subvolume is yielded :param only_mount: if specified, only volume indexes in this list are mounted. Volume indexes are strings. :param skip_mount: if specified, volume indexes in this list are not mounted. :param swallow_exceptions: if True, any error occuring when mounting the volume is swallowed and added as an exception attribute to the yielded objects.
[ "Generator", "that", "mounts", "this", "volume", "and", "either", "yields", "itself", "or", "recursively", "generates", "its", "subvolumes", "." ]
python
train
ConsenSys/mythril-classic
mythril/laser/ethereum/state/machine_state.py
https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/laser/ethereum/state/machine_state.py#L174-L185
def pop(self, amount=1) -> Union[BitVec, List[BitVec]]: """Pops amount elements from the stack. :param amount: :return: """ if amount > len(self.stack): raise StackUnderflowException values = self.stack[-amount:][::-1] del self.stack[-amount:] return values[0] if amount == 1 else values
[ "def", "pop", "(", "self", ",", "amount", "=", "1", ")", "->", "Union", "[", "BitVec", ",", "List", "[", "BitVec", "]", "]", ":", "if", "amount", ">", "len", "(", "self", ".", "stack", ")", ":", "raise", "StackUnderflowException", "values", "=", "s...
Pops amount elements from the stack. :param amount: :return:
[ "Pops", "amount", "elements", "from", "the", "stack", "." ]
python
train
riga/tfdeploy
tfdeploy.py
https://github.com/riga/tfdeploy/blob/8481f657d6e3a51d76185a195b993e45f448828a/tfdeploy.py#L705-L719
def func(self, values): """ The actual ensembling logic that combines multiple *values*. The method call is forwareded tothe ensemble method-specific variant which is determined using *method*. """ if self.method == METHOD_MEAN: return self.func_mean(values) elif self.method == METHOD_MAX: return self.func_max(values) elif self.method == METHOD_MIN: return self.func_min(values) elif self.method == METHOD_CUSTOM: return self.func_custom(values) else: raise UnknownEnsembleMethodException(self.method)
[ "def", "func", "(", "self", ",", "values", ")", ":", "if", "self", ".", "method", "==", "METHOD_MEAN", ":", "return", "self", ".", "func_mean", "(", "values", ")", "elif", "self", ".", "method", "==", "METHOD_MAX", ":", "return", "self", ".", "func_max...
The actual ensembling logic that combines multiple *values*. The method call is forwareded tothe ensemble method-specific variant which is determined using *method*.
[ "The", "actual", "ensembling", "logic", "that", "combines", "multiple", "*", "values", "*", ".", "The", "method", "call", "is", "forwareded", "tothe", "ensemble", "method", "-", "specific", "variant", "which", "is", "determined", "using", "*", "method", "*", ...
python
train
olucurious/PyFCM
pyfcm/baseapi.py
https://github.com/olucurious/PyFCM/blob/28096cd5f6ef515bb6034e63327723d12304249a/pyfcm/baseapi.py#L363-L390
def subscribe_registration_ids_to_topic(self, registration_ids, topic_name): """ Subscribes a list of registration ids to a topic Args: registration_ids (list): ids to be subscribed topic_name (str): name of topic Returns: True: if operation succeeded Raises: InvalidDataError: data sent to server was incorrectly formatted FCMError: an error occured on the server """ url = 'https://iid.googleapis.com/iid/v1:batchAdd' payload = { 'to': '/topics/' + topic_name, 'registration_tokens': registration_ids, } response = self.requests_session.post(url, json=payload) if response.status_code == 200: return True elif response.status_code == 400: error = response.json() raise InvalidDataError(error['error']) else: raise FCMError()
[ "def", "subscribe_registration_ids_to_topic", "(", "self", ",", "registration_ids", ",", "topic_name", ")", ":", "url", "=", "'https://iid.googleapis.com/iid/v1:batchAdd'", "payload", "=", "{", "'to'", ":", "'/topics/'", "+", "topic_name", ",", "'registration_tokens'", ...
Subscribes a list of registration ids to a topic Args: registration_ids (list): ids to be subscribed topic_name (str): name of topic Returns: True: if operation succeeded Raises: InvalidDataError: data sent to server was incorrectly formatted FCMError: an error occured on the server
[ "Subscribes", "a", "list", "of", "registration", "ids", "to", "a", "topic" ]
python
train
dgketchum/satellite_image
sat_image/mtl.py
https://github.com/dgketchum/satellite_image/blob/0207fbb7b2bbf14f4307db65489bb4d4c5b92f52/sat_image/mtl.py#L148-L194
def _checkstatus(status, line): """Returns state/status after reading the next line. The status codes are:: LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF - BEGIN parsing; 1 - ENTER METADATA GROUP, 2 - READ METADATA LINE, 3 - END METDADATA GROUP, 4 - END PARSING Permitted Transitions:: LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF --> 1, LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF --> 4 1 --> 1, 1 --> 2, 1 --> 3 2 --> 2, 2 --> 3 3 --> 1, 1 --> 3, 3 --> 4 """ newstatus = 0 if status == 0: # begin --> enter metadata group OR end if _islinetype(line, GRPSTART): newstatus = 1 elif _isfinal(line): newstatus = 4 elif status == 1: # enter metadata group --> enter metadata group # OR add metadata item OR leave metadata group if _islinetype(line, GRPSTART): newstatus = 1 elif _islinetype(line, GRPEND): newstatus = 3 elif _isassignment(line): # test AFTER start and end, as both are also assignments newstatus = 2 elif status == 2: if _islinetype(line, GRPEND): newstatus = 3 elif _isassignment(line): # test AFTER start and end, as both are also assignments newstatus = 2 elif status == 3: if _islinetype(line, GRPSTART): newstatus = 1 elif _islinetype(line, GRPEND): newstatus = 3 elif _isfinal(line): newstatus = 4 if newstatus != 0: return newstatus elif status != 4: raise MTLParseError( "Cannot parse the following line after status " + "'%s':\n%s" % (STATUSCODE[status], line))
[ "def", "_checkstatus", "(", "status", ",", "line", ")", ":", "newstatus", "=", "0", "if", "status", "==", "0", ":", "# begin --> enter metadata group OR end", "if", "_islinetype", "(", "line", ",", "GRPSTART", ")", ":", "newstatus", "=", "1", "elif", "_isfin...
Returns state/status after reading the next line. The status codes are:: LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF - BEGIN parsing; 1 - ENTER METADATA GROUP, 2 - READ METADATA LINE, 3 - END METDADATA GROUP, 4 - END PARSING Permitted Transitions:: LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF --> 1, LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF --> 4 1 --> 1, 1 --> 2, 1 --> 3 2 --> 2, 2 --> 3 3 --> 1, 1 --> 3, 3 --> 4
[ "Returns", "state", "/", "status", "after", "reading", "the", "next", "line", ".", "The", "status", "codes", "are", "::", "LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1", ".", "TIF", "-", "BEGIN", "parsing", ";", "1", "-", "ENTER", "METADATA", "GROUP", "2", ...
python
train
saltstack/salt
salt/states/boto_apigateway.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_apigateway.py#L1280-L1285
def _aws_model_ref_from_swagger_ref(self, r): ''' Helper function to reference models created on aws apigw ''' model_name = r.split('/')[-1] return 'https://apigateway.amazonaws.com/restapis/{0}/models/{1}'.format(self.restApiId, model_name)
[ "def", "_aws_model_ref_from_swagger_ref", "(", "self", ",", "r", ")", ":", "model_name", "=", "r", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "return", "'https://apigateway.amazonaws.com/restapis/{0}/models/{1}'", ".", "format", "(", "self", ".", "restAp...
Helper function to reference models created on aws apigw
[ "Helper", "function", "to", "reference", "models", "created", "on", "aws", "apigw" ]
python
train
spyder-ide/spyder
spyder/plugins/console/utils/interpreter.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/console/utils/interpreter.py#L298-L308
def eval(self, text): """ Evaluate text and return (obj, valid) where *obj* is the object represented by *text* and *valid* is True if object evaluation did not raise any exception """ assert is_text_string(text) try: return eval(text, self.locals), True except: return None, False
[ "def", "eval", "(", "self", ",", "text", ")", ":", "assert", "is_text_string", "(", "text", ")", "try", ":", "return", "eval", "(", "text", ",", "self", ".", "locals", ")", ",", "True", "except", ":", "return", "None", ",", "False" ]
Evaluate text and return (obj, valid) where *obj* is the object represented by *text* and *valid* is True if object evaluation did not raise any exception
[ "Evaluate", "text", "and", "return", "(", "obj", "valid", ")", "where", "*", "obj", "*", "is", "the", "object", "represented", "by", "*", "text", "*", "and", "*", "valid", "*", "is", "True", "if", "object", "evaluation", "did", "not", "raise", "any", ...
python
train
FactoryBoy/factory_boy
factory/builder.py
https://github.com/FactoryBoy/factory_boy/blob/edaa7c7f5a14065b229927903bd7989cc93cd069/factory/builder.py#L251-L306
def build(self, parent_step=None, force_sequence=None): """Build a factory instance.""" # TODO: Handle "batch build" natively pre, post = parse_declarations( self.extras, base_pre=self.factory_meta.pre_declarations, base_post=self.factory_meta.post_declarations, ) if force_sequence is not None: sequence = force_sequence elif self.force_init_sequence is not None: sequence = self.force_init_sequence else: sequence = self.factory_meta.next_sequence() step = BuildStep( builder=self, sequence=sequence, parent_step=parent_step, ) step.resolve(pre) args, kwargs = self.factory_meta.prepare_arguments(step.attributes) instance = self.factory_meta.instantiate( step=step, args=args, kwargs=kwargs, ) postgen_results = {} for declaration_name in post.sorted(): declaration = post[declaration_name] unrolled_context = declaration.declaration.unroll_context( instance=instance, step=step, context=declaration.context, ) postgen_context = PostGenerationContext( value_provided='' in unrolled_context, value=unrolled_context.get(''), extra={k: v for k, v in unrolled_context.items() if k != ''}, ) postgen_results[declaration_name] = declaration.declaration.call( instance=instance, step=step, context=postgen_context, ) self.factory_meta.use_postgeneration_results( instance=instance, step=step, results=postgen_results, ) return instance
[ "def", "build", "(", "self", ",", "parent_step", "=", "None", ",", "force_sequence", "=", "None", ")", ":", "# TODO: Handle \"batch build\" natively", "pre", ",", "post", "=", "parse_declarations", "(", "self", ".", "extras", ",", "base_pre", "=", "self", ".",...
Build a factory instance.
[ "Build", "a", "factory", "instance", "." ]
python
train
seb-m/pyinotify
python2/pyinotify.py
https://github.com/seb-m/pyinotify/blob/0f3f8950d12e4a6534320153eed1a90a778da4ae/python2/pyinotify.py#L1838-L1849
def __format_path(self, path): """ Format path to its internal (stored in watch manager) representation. """ # Unicode strings are converted back to strings, because it seems # that inotify_add_watch from ctypes does not work well when # it receives an ctypes.create_unicode_buffer instance as argument. # Therefore even wd are indexed with bytes string and not with # unicode paths. if isinstance(path, unicode): path = path.encode(sys.getfilesystemencoding()) return os.path.normpath(path)
[ "def", "__format_path", "(", "self", ",", "path", ")", ":", "# Unicode strings are converted back to strings, because it seems", "# that inotify_add_watch from ctypes does not work well when", "# it receives an ctypes.create_unicode_buffer instance as argument.", "# Therefore even wd are index...
Format path to its internal (stored in watch manager) representation.
[ "Format", "path", "to", "its", "internal", "(", "stored", "in", "watch", "manager", ")", "representation", "." ]
python
train
spyder-ide/spyder
spyder/plugins/help/plugin.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/plugin.py#L247-L267
def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" color_scheme_n = 'color_scheme_name' color_scheme_o = self.get_color_scheme() connect_n = 'connect_to_oi' wrap_n = 'wrap' wrap_o = self.get_option(wrap_n) self.wrap_action.setChecked(wrap_o) math_n = 'math' math_o = self.get_option(math_n) if color_scheme_n in options: self.set_plain_text_color_scheme(color_scheme_o) if wrap_n in options: self.toggle_wrap_mode(wrap_o) if math_n in options: self.toggle_math_mode(math_o) # To make auto-connection changes take place instantly self.main.editor.apply_plugin_settings(options=[connect_n]) self.main.ipyconsole.apply_plugin_settings(options=[connect_n])
[ "def", "apply_plugin_settings", "(", "self", ",", "options", ")", ":", "color_scheme_n", "=", "'color_scheme_name'", "color_scheme_o", "=", "self", ".", "get_color_scheme", "(", ")", "connect_n", "=", "'connect_to_oi'", "wrap_n", "=", "'wrap'", "wrap_o", "=", "sel...
Apply configuration file's plugin settings
[ "Apply", "configuration", "file", "s", "plugin", "settings" ]
python
train
honeynet/beeswarm
beeswarm/drones/honeypot/helpers/common.py
https://github.com/honeynet/beeswarm/blob/db51ea0bc29f631c3e3b5312b479ac9d5e31079a/beeswarm/drones/honeypot/helpers/common.py#L10-L15
def list2dict(list_of_options): """Transforms a list of 2 element tuples to a dictionary""" d = {} for key, value in list_of_options: d[key] = value return d
[ "def", "list2dict", "(", "list_of_options", ")", ":", "d", "=", "{", "}", "for", "key", ",", "value", "in", "list_of_options", ":", "d", "[", "key", "]", "=", "value", "return", "d" ]
Transforms a list of 2 element tuples to a dictionary
[ "Transforms", "a", "list", "of", "2", "element", "tuples", "to", "a", "dictionary" ]
python
train
apache/spark
python/pyspark/sql/functions.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L1856-L1867
def translate(srcCol, matching, replace): """A function translate any character in the `srcCol` by a character in `matching`. The characters in `replace` is corresponding to the characters in `matching`. The translate will happen when any character in the string matching with the character in the `matching`. >>> spark.createDataFrame([('translate',)], ['a']).select(translate('a', "rnlt", "123") \\ ... .alias('r')).collect() [Row(r=u'1a2s3ae')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.translate(_to_java_column(srcCol), matching, replace))
[ "def", "translate", "(", "srcCol", ",", "matching", ",", "replace", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "return", "Column", "(", "sc", ".", "_jvm", ".", "functions", ".", "translate", "(", "_to_java_column", "(", "srcCol", ")",...
A function translate any character in the `srcCol` by a character in `matching`. The characters in `replace` is corresponding to the characters in `matching`. The translate will happen when any character in the string matching with the character in the `matching`. >>> spark.createDataFrame([('translate',)], ['a']).select(translate('a', "rnlt", "123") \\ ... .alias('r')).collect() [Row(r=u'1a2s3ae')]
[ "A", "function", "translate", "any", "character", "in", "the", "srcCol", "by", "a", "character", "in", "matching", ".", "The", "characters", "in", "replace", "is", "corresponding", "to", "the", "characters", "in", "matching", ".", "The", "translate", "will", ...
python
train
Opentrons/opentrons
api/src/opentrons/legacy_api/containers/placeable.py
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L568-L581
def get_wellseries(self, matrix): """ Returns the grid as a WellSeries of WellSeries """ res = OrderedDict() for col, cells in matrix.items(): if col not in res: res[col] = OrderedDict() for row, cell in cells.items(): res[col][row] = self.children_by_name[ ''.join(cell) ] res[col] = WellSeries(res[col], name=col) return WellSeries(res)
[ "def", "get_wellseries", "(", "self", ",", "matrix", ")", ":", "res", "=", "OrderedDict", "(", ")", "for", "col", ",", "cells", "in", "matrix", ".", "items", "(", ")", ":", "if", "col", "not", "in", "res", ":", "res", "[", "col", "]", "=", "Order...
Returns the grid as a WellSeries of WellSeries
[ "Returns", "the", "grid", "as", "a", "WellSeries", "of", "WellSeries" ]
python
train