code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_input_join_channel_id(url, user_1): <NEW_LINE> <INDENT> arg_join = { 'token' : user_1['token'], 'channel_id': -1, } <NEW_LINE> res_err = requests.post(url + 'channel/join', json=arg_join) <NEW_LINE> assert res_err.status_code == InputError.code <NEW_LINE> arg_join = { 'token' : user_1['token'], 'channe... | Testing when Channel ID is not a valid channel
| 625941e976e4537e8c351b2a |
def InsertRows(onesheet, listoflists, lastrowused=''): <NEW_LINE> <INDENT> numnewrows = len(listoflists) <NEW_LINE> if not lastrowused: <NEW_LINE> <INDENT> lastrowused = globs.numrows <NEW_LINE> <DEDENT> numrowsneeded = len(listoflists) <NEW_LINE> allrowsevenempty = onesheet.row_count <NEW_LINE> availableblankrows = al... | Inserts a list-of-lists as rows into spreadsheet from lastrowused. | 625941e9167d2b6e31219049 |
def split_uc_words(words): <NEW_LINE> <INDENT> size = len(words)-1 <NEW_LINE> new_words = [] <NEW_LINE> tmp_word = '' <NEW_LINE> for i, c in enumerate(words): <NEW_LINE> <INDENT> if i == 0 or c.isupper(): <NEW_LINE> <INDENT> tmp_word += c.upper() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if i+1 <= size: <NEW_LINE> ... | Split a string using a forward look-ahead for upper case letters to act as word
boundaries. If while iterating the next character will be upper case or if the current character is the last
of the given string, then mark that as the end of the current word and add is to the new_words list to be
returned.
:param words: ... | 625941e9c4546d3d9de72eec |
def _read(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def inner(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.fdlock: <NEW_LINE> <INDENT> out = func(self, *args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._open_fd_r() <NEW_LINE> self._shlock(self.fd) <NEW_LINE> self.fdlock = 'shared' <NEW... | Decorator for opening state file for reading and applying shared
lock.
Applying this decorator to a method will ensure that the file is opened
for reading and that a shared lock is obtained before that method is
executed. It also ensures that the lock is removed and the file closed
after the method returns. | 625941e982261d6c526ab95b |
def retrieveOrCreateTags(self, tagList): <NEW_LINE> <INDENT> openBISTags = [] <NEW_LINE> if tagList is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> tags = ["".join(t.strip()) for t in tagList.split(",")] <NEW_LINE> for tag in tags: <NEW_LINE> <INDENT> if len(tag) == 0: <NEW_LINE> <INDENT> continue <NEW_LINE>... | Retrieve or create the tags (metaprojects) with specified names. | 625941e90c0af96317bb869c |
@app.teardown_appcontext <NEW_LINE> def close_db(error): <NEW_LINE> <INDENT> if hasattr(g, 'sqlite_db'): <NEW_LINE> <INDENT> g.sqlite_db.close() | close the database again at the end of the request | 625941e91f5feb6acb0c4ffd |
def data_fetch(self, individual, interface_index, fea_name): <NEW_LINE> <INDENT> if self.is_interface_na(individual, interface_index) or self.is_interface_an(individual, interface_index): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> result = individual[interface_index]['data'] <NEW_LINE> structural_loc = self.STRU... | 返回一个客户在接口interface_index中的数据
:param individual: dict
字典的键为接口编号
:param interface_index: str
需要返回的数据的接口编号
:param structural_loc: list
需要提取的指标在individual中的具体位置,是一些格式化的key名称。
:return: (list/dict, bool)
客户在接口interface_index中的数据,返回类型视具体情况而定 | 625941e901c39578d7e752f0 |
def __init__(self, id, texts, toggled=None, label=None): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.texts = texts <NEW_LINE> self.label = label <NEW_LINE> self.toggled = toggled if toggled is not None else [False] * len(self.texts) | Row of buttons where each one may be toggled separately
Parameters
----------
id : string
widget identifier
texts : list
list of texts to appear on buttons
toggled : list
list of boolean values that control whether button at respective position is toggled | 625941e91f5feb6acb0c4ffe |
def set_beam_stability_profile(self, stability_profile: np.ndarray): <NEW_LINE> <INDENT> self.illuminator_element_dict[MetadataDeviceTags.BEAM_STABILITY_PROFILE.tag] = stability_profile | Parameters
----------
stability_profile:
a two element array [wavelengths,laser_stability,] describing the laser stability profile.
Beam stability and wavelengths are also arrays where len(stability_profile) == len(wavelengths).
The units can be found in MetadataDeviceTags.BEAM_STABILITY_PROFILE.unit.
Retu... | 625941e985dfad0860c3b310 |
def prime_subfield(self): <NEW_LINE> <INDENT> return GF2 | Return the prime subfield `\GF{p}` of ``self`` if ``self`` is
`\GF{p^n}`.
EXAMPLES::
sage: F.<a> = GF(2^16)
sage: F.prime_subfield()
Finite Field of size 2 | 625941e90383005118ecfa95 |
def branches(self, _raw=0, **p4options): <NEW_LINE> <INDENT> def branches_result_cb(output): <NEW_LINE> <INDENT> branchRe = re.compile("^Branch (?P<branch>[^\s@]+) " "(?P<update>[\d/]+) " "'(?P<description>.*?)'$") <NEW_LINE> all_matches = (_match_or_raise(branchRe, l, "branches") for l in output.splitlines(True)) <NEW... | Return a list of branches.
Returns a list of dicts, each representing one branches spec,
e.g.:
[{'branch': 'zope-aspn',
'description': 'Contrib Zope into ASPN ',
'update': '2001/10/15'},
...
]
If '_raw' is true then the return value is simply a dictionary
with the unprocessed results of calli... | 625941e94527f215b584c906 |
def readmol(path): <NEW_LINE> <INDENT> sformat = 'pdb' <NEW_LINE> obc = openbabel.OBConversion() <NEW_LINE> obc.SetInFormat("pdb") <NEW_LINE> obmol = openbabel.OBMol() <NEW_LINE> with read(path) as f: <NEW_LINE> <INDENT> filestr = str(f.read()) <NEW_LINE> <DEDENT> obc.ReadString(obmol, filestr) <NEW_LINE> return pybel.... | Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type.
In contrast to the standard Pybel implementation, the file is closed properly. | 625941e9d58c6744b4258112 |
def upload(self): <NEW_LINE> <INDENT> body = read_file(self.src) <NEW_LINE> bucket, key = find_bucket_key(self.dest) <NEW_LINE> if sys.version_info[:2] == (2, 6): <NEW_LINE> <INDENT> stream_body = StringIO(body) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stream_body = bytearray(body) <NEW_LINE> <DEDENT> params = {'e... | Redirects the file to the multipart upload function if the file is
large. If it is small enough, it puts the file as an object in s3. | 625941e9d268445f265b5323 |
def set_ClientID(self, value): <NEW_LINE> <INDENT> super(LikesInputSet, self)._set_input('ClientID', value) | Set the value of the ClientID input for this Choreo. ((conditional, string) Your Foursquare client ID, obtained after registering at Foursquare. Required unless using the OauthToken input.) | 625941e9d164cc6175783203 |
def __init__(self, host, is_ssl=False): <NEW_LINE> <INDENT> mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> asynchat.async_chat.__init__(self, sock=mysock) <NEW_LINE> self._inbuf = bytearray() <NEW_LINE> self.is_ssl = is_ssl <NEW_LINE> self.set_terminator(b'\r\n') <NEW_LINE> self.host = host <NEW... | constructor of the class IrcClient.
host is a tuple fed to socket.connect().
is_ssl bool, use ssl. Default is False
logger is the logging handler.Default logger prints errors on stderr. | 625941e966673b3332b92546 |
def notify_page(self, html_page): <NEW_LINE> <INDENT> logging.debug('notifier_browser: maybe notify: %s', html_page) <NEW_LINE> honor_enabled = CONFIG['notifier_browser.honor_enabled'] <NEW_LINE> enabled = CONFIG['enabled'] <NEW_LINE> if not enabled and honor_enabled: <NEW_LINE> <INDENT> logging.debug('notifier_browser... | Open a webpage to notify the user | 625941e93346ee7daa2b3224 |
def run(maxPages, persist, campaignName=None, query=None): <NEW_LINE> <INDENT> global API_CONN <NEW_LINE> utilityCampaignRec = Campaign.getOrCreate(UTILITY_CAMPAIGN, None) <NEW_LINE> if query: <NEW_LINE> <INDENT> customCampaignRec = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> customCampaignRec = Campaign.getOrRa... | Get labels first before attempting to do searches and then find labels
are missing.
:param maxPages: Count.
:param persist: Flag.
:param campaignName: Custom campaign name to label tweets with.
:param query: Search query.
:return: Tuple of processed profile and tweet counts. | 625941e923e79379d52eea12 |
def assertions_for_concept(concept, direction='all', limit=20): <NEW_LINE> <INDENT> def assertion_filter(assertion): <NEW_LINE> <INDENT> if direction == 'all': return True <NEW_LINE> elif direction == 'forward': <NEW_LINE> <INDENT> return assertion['concept1']['text'] == concept['text'] <NEW_LINE> <DEDENT> elif directi... | Given a dictionary representing a concept, look up the assertions it
appears in.
By default, this returns all matching assertions. By setting the
optional argument `direction` to "forward" or "backward", you can restrict
it to only assertions that have that concept on the left or the right
respectively.
You may set t... | 625941e9cc40096d61595e03 |
def serialize(self): <NEW_LINE> <INDENT> if len(self.headers) == 0: <NEW_LINE> <INDENT> headers = ['NONE'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> headers = ['%s:%s' % (name, value) for name, value in self.headers.items()] <NEW_LINE> <DEDENT> headers = '::'.join(headers) <NEW_LINE> return headers + ':::' + self.d... | Serializes the job.
The output can be sent over a wire. A serialized job
can be read with a cursor with no specific preprocessing. | 625941e95fc7496912cc3e32 |
def test_with(self): <NEW_LINE> <INDENT> tmp_file = join(self.tmp_dir, 'NNTPContent_Test.with', '1MB.rar') <NEW_LINE> assert(isfile(tmp_file) is False) <NEW_LINE> assert(self.touch(tmp_file, size='1MB', random=True) is True) <NEW_LINE> assert(isfile(tmp_file) is True) <NEW_LINE> content_a = NNTPContent(filepath=tmp_fil... | Test the use of the with clause | 625941e9cdde0d52a9e534eb |
def deleteAttribute(self, name): <NEW_LINE> <INDENT> if name in self.contents: <NEW_LINE> <INDENT> del self.contents[name] <NEW_LINE> return 1 <NEW_LINE> <DEDENT> return 0 | Delete a named attribute
| 625941e944b2445a33932547 |
def _ListAclPermissions(self): <NEW_LINE> <INDENT> resource_id = eval(input('Enter an resource id: ')) <NEW_LINE> query = gdata.docs.service.DocumentAclQuery(resource_id) <NEW_LINE> print('\nListing document permissions:') <NEW_LINE> feed = self.gd_client.GetDocumentListAclFeed(query.ToUri()) <NEW_LINE> for acl_entry i... | Retrieves a list of a user's folders and displays them. | 625941e976e4537e8c351b2b |
def get_source_voice(self, source, player): <NEW_LINE> <INDENT> voice_key = (source.audio_format.channels, source.audio_format.sample_size) <NEW_LINE> if len(self._voice_pool[voice_key]) > 0: <NEW_LINE> <INDENT> source_voice = self._voice_pool[voice_key].pop(0) <NEW_LINE> source_voice.acquired(player) <NEW_LINE> <DEDEN... | Get a source voice from the pool. Source voice creation can be slow to create/destroy. So pooling is
recommended. We pool based on audio channels as channels must be the same as well as frequency.
Source voice handles all of the audio playing and state for a single source. | 625941e930c21e258bdfa957 |
def get_mood_categories(self) -> Dict: <NEW_LINE> <INDENT> sections = {} <NEW_LINE> response = self._send_request('browse', {'browseId': 'FEmusic_moods_and_genres'}) <NEW_LINE> for section in nav(response, SINGLE_COLUMN_TAB + SECTION_LIST): <NEW_LINE> <INDENT> title = nav(section, GRID + ['header', 'gridHeaderRenderer'... | Fetch "Moods & Genres" categories from YouTube Music.
:return: Dictionary of sections and categories.
Example::
{
'For you': [
{
'params': 'ggMPOg1uX1ZwN0pHT2NBT1Fk',
'title': '1980s'
},
{
'params': 'ggMPOg1uXzZQbDB5eThLR... | 625941e9d7e4931a7ee9e3d4 |
def t_AJOUTER(t): <NEW_LINE> <INDENT> return t | ajouter | 625941e9cc0a2c11143dd347 |
def checkPassWordAddWorker(self) : <NEW_LINE> <INDENT> if self.checkPassWord() : <NEW_LINE> <INDENT> self.showAddWorker() <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> tkmsg.showerror("Erreur ", "Mot de passe incorrect") | check the password. if is good, show elements to add worker. | 625941e9711fe17d82542815 |
def createActions(self, parent=None): <NEW_LINE> <INDENT> pass | Should add actions as instance attributes.
The QActions should get icons and shortcuts. Texts should be set
in translateUI(). The actions are created with the parent given on instantiation. | 625941e94d74a7450ccd4679 |
def write_output(contigs, name, outpath): <NEW_LINE> <INDENT> with open(os.path.join(outpath, name),'w') as o: <NEW_LINE> <INDENT> seqs = (SeqRecord(contigs[s], s, description='') for s in contigs) <NEW_LINE> SeqIO.write(sorted(seqs, key=lambda x: x.id), o, 'fasta') | Writes a fasta file with contigs sorted by contig name | 625941e94428ac0f6e5bacab |
def test_unpatch(self): <NEW_LINE> <INDENT> original_init = httplib.HTTPConnection.__init__.__wrapped__ <NEW_LINE> original_putrequest = httplib.HTTPConnection.putrequest.__wrapped__ <NEW_LINE> original_getresponse = httplib.HTTPConnection.getresponse.__wrapped__ <NEW_LINE> unpatch() <NEW_LINE> self.assertEqual(httplib... | When unpatching httplib
we restore the correct module/methods | 625941e94d74a7450ccd467a |
def _end_outermost_bulk_operation(self, bulk_write_record, structure_key): <NEW_LINE> <INDENT> dirty = False <NEW_LINE> for _id in bulk_write_record.structures.keys() - bulk_write_record.structures_in_db: <NEW_LINE> <INDENT> dirty = True <NEW_LINE> try: <NEW_LINE> <INDENT> self.db_connection.insert_structure(bulk_write... | End the active bulk write operation on structure_key (course or library key). | 625941e94c3428357757c7da |
def semifact2(n): <NEW_LINE> <INDENT> alternatives= [ (lambda n: 1) if n == 0 else None, (lambda n: 1) if n == 1 else None, (lambda n: 2) if n == 2 else None, (lambda n: semifact2(n-2)*n) if n > 2 else None] <NEW_LINE> f= next(filter(None, alternatives)) <NEW_LINE> return f(n) | >>> semifact2(9)
945 | 625941e991af0d3eaac9bed2 |
def set_definition_and_get_response(slash_command, command_params, user_name): <NEW_LINE> <INDENT> set_components = command_params.split('=', 1) <NEW_LINE> set_term = set_components[0].strip() <NEW_LINE> set_value = set_components[1].strip() if len(set_components) > 1 else u'' <NEW_LINE> if u'=' not in command_params o... | Set the definition for the passed parameters and return the approriate responses
| 625941e9d164cc6175783204 |
@jit <NEW_LINE> def Dsoft(M,penalty): <NEW_LINE> <INDENT> penalty=float(penalty) <NEW_LINE> return np.maximum((M-penalty),0.0,out=None) | Inverts the singular values
takes advantage of the fact that singular values are never negative
Parameters
----------
M : numpy array
penalty: float number
penalty scalar to penalize singular values
Returns
-------
M matrix with elements penalized when them viole this condition | 625941e9d486a94d0b98e5fc |
def serialize(document, resource=None, schema=None): <NEW_LINE> <INDENT> if app.data.serializers: <NEW_LINE> <INDENT> if resource: <NEW_LINE> <INDENT> schema = config.DOMAIN[resource]['schema'] <NEW_LINE> <DEDENT> for field in document: <NEW_LINE> <INDENT> if field in schema: <NEW_LINE> <INDENT> field_schema = schema[f... | Recursively handles field values that require data-aware serialization.
Relies on the app.data.serializers dictionary.
.. versionchanged:: 0.3
Fix serialization of sub-documents. See #244.
.. versionadded:: 0.1.1 | 625941e992d797404e304641 |
def test_get_geocoders(self): <NEW_LINE> <INDENT> tc = UtilsTestConfig() <NEW_LINE> tc.GEOCODERS = ( (test_geocode_controller.MockGeocoder, {}), ) <NEW_LINE> current_app.config.from_object(tc) <NEW_LINE> gc, *_ = util.get_geocoders() <NEW_LINE> self.assertIsInstance(gc, test_geocode_controller.MockGeocoder, "config is ... | Vanilla test case for get_geocoders
Utility function for setting up and configuring geocoder objects | 625941e9bd1bec0571d90ae4 |
def load_from_module(item): <NEW_LINE> <INDENT> mod_name, _, cls_name = item.rpartition(".") <NEW_LINE> module = importlib.import_module(mod_name) <NEW_LINE> cls = getattr(module, cls_name) <NEW_LINE> return cls | Load something from a module like django
Args:
item (str): Item in a module, separated by dots - eg
"package.module.MyClass"
Returns:
object: whatever was loaded
Raises:
ImportError: No such module
AttributeError: No such item in module | 625941e9f548e778e58cda35 |
def asRGBA(self): <NEW_LINE> <INDENT> width, height, pixels, info = self.asDirect() <NEW_LINE> if info['alpha'] and not info['greyscale']: <NEW_LINE> <INDENT> return width, height, pixels, info <NEW_LINE> <DEDENT> typecode = 'BH'[info['bitdepth'] > 8] <NEW_LINE> maxval = 2**info['bitdepth'] - 1 <NEW_LINE> maxbuffer = s... | Return image as RGBA pixels.
Greyscales are expanded into RGB triplets;
an alpha channel is synthesized if necessary.
The return values are as for the :meth:`read` method except that
the *info* reflect the returned pixels, not the source image.
In particular, for this method
``info['greyscale']`` will be ``False``, and... | 625941e963b5f9789fde759b |
def init_graphe_zone(actual_graphe): <NEW_LINE> <INDENT> new_graphe = copy.deepcopy(actual_graphe) <NEW_LINE> for node in new_graphe: <NEW_LINE> <INDENT> if len(new_graphe[node]) == 2: <NEW_LINE> <INDENT> new_graphe = supprCouloir(new_graphe, node) <NEW_LINE> <DEDENT> <DEDENT> for node in actual_graphe: <NEW_LINE> <IND... | renvoie le graphe d'entrée sans impasses ni couloirs | 625941e907f4c71912b11939 |
def text_to_numeric(text: str, dtype=np.float64): <NEW_LINE> <INDENT> if isinstance(text, str): <NEW_LINE> <INDENT> only_number_chars = "[^0-9\.\-]" <NEW_LINE> clean_str = re.sub(only_number_chars, "", text) <NEW_LINE> try: <NEW_LINE> <INDENT> return dtype(clean_str) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <I... | Removes non numeric characters from a string and transforms it into the selected data type.
Returns np.nan in case of ValueError when casting the string to numeric dtype. | 625941e994891a1f4081bf60 |
def assign_person_to_uid(uid, pid): <NEW_LINE> <INDENT> if pid == -1: <NEW_LINE> <INDENT> pid = dbinter.create_new_author_by_uid(uid, uid_is_owner=True) <NEW_LINE> return pid, True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current_uid = get_persons_data([pid], 'uid') <NEW_LINE> if len(current_uid[pid]) == 0: <NEW_L... | Assigns a person to a userid. If person already assigned to someone else, create new person.
Returns two value. Firstly the person id assigned and secondly if uid was successfully assigned to given pid.
If parameter pid equals to -1 then we assign the uid to a new person
@param uid: user id, int
@param pid: person id, ... | 625941e9a79ad161976cc5fa |
def test_item_string(self): <NEW_LINE> <INDENT> item_description = 'test desc' <NEW_LINE> item = N(Item, description=item_description) <NEW_LINE> self.assertEqual(unicode(item), item.description) | Items should use their description for their human readable form | 625941e9851cf427c661a9c0 |
def stop_server(channel, server_name): <NEW_LINE> <INDENT> channel.basic_publish(exchange='direct_logs', routing_key=common.make_key_server_stop(), body=server_name) | Publishes server advert about stopping server.
@param channel: pika.BlockingChannel
@param server_name: name of server | 625941e907f4c71912b1193a |
def output_affiliation_relation(affiliation, status, sko, people, person_info): <NEW_LINE> <INDENT> xmlwriter.startElement("relation", {"relationtype": get_affiliation_type(affiliation, status)}) <NEW_LINE> xmlwriter.startElement("subject") <NEW_LINE> output_ou(sko) <NEW_LINE> xmlwriter.endElement("subject") <NEW_LINE>... | Output one <relation>-element as described in output_affiliations. | 625941e9be7bc26dc91cdaac |
def batchnorm_backward_alt(dout, cache): <NEW_LINE> <INDENT> dx, dgamma, dbeta = None, None, None <NEW_LINE> x, gamma, x_norm, eps = cache <NEW_LINE> N = x.shape[0] <NEW_LINE> sample_mean = np.mean(x, axis=0) <NEW_LINE> sample_var = np.var(x, axis=0) <NEW_LINE> dbeta = np.sum(dout, axis=0) <NEW_LINE> dgamma = np.sum(x_... | Alternative backward pass for batch normalization.
For this implementation you should work out the derivatives for the batch
normalizaton backward pass on paper and simplify as much as possible. You
should be able to derive a simple expression for the backward pass.
Note: This implementation should expect to receive ... | 625941e9d18da76e23532991 |
def _establish_session(self): <NEW_LINE> <INDENT> iq_id = str(uuid.uuid4()) <NEW_LINE> iq = ET.Element("iq", { "xmlns": XMLNS_XMPP_IQ, "type": "set", "id": iq_id, }) <NEW_LINE> session = ET.SubElement(iq, "session") <NEW_LINE> session.set("xmlns", XMLNS_SESSION) <NEW_LINE> ret_xml, ret_elems = self._send_body(self._bui... | Establish session for connection. | 625941e9d268445f265b5324 |
@nodeHandle <NEW_LINE> def TaskExcuteTalk_1419(dynamicId, request_proto): <NEW_LINE> <INDENT> arguments = TaskExcuteTalkTaskRequest1419_pb2.TaskExcuteTalkTaskRequest() <NEW_LINE> arguments.ParseFromString(request_proto) <NEW_LINE> response = TaskExcuteTalkTaskRequest1419_pb2.TaskExcuteTalkTaskResponse() <NEW_LINE> char... | 任务交谈 | 625941e950812a4eaa59c7d2 |
def search(self, word): <NEW_LINE> <INDENT> head = self.TrieNode <NEW_LINE> if word == "": <NEW_LINE> <INDENT> if head.isChild == 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> for s in word: <NEW_LINE> <INDENT> if head.next.has_key(s): <NEW_LINE> <INDENT> head = head.next[s] <N... | Returns if the word is in the trie.
:type word: str
:rtype: bool | 625941e9ad47b63b2c50a434 |
def _odd_iter(): <NEW_LINE> <INDENT> n = 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> n += 2 <NEW_LINE> yield n | 创建奇数序列 | 625941e9b830903b967e9dbb |
def index(request): <NEW_LINE> <INDENT> return HttpResponse("Witaj w aplikacji Czat!") | Strona główna aplikacji. | 625941e94e4d5625662d4886 |
def identifier(self): <NEW_LINE> <INDENT> length = 30 <NEW_LINE> if self.pos + length > len(self.text): <NEW_LINE> <INDENT> length = len(self.text) - self.pos <NEW_LINE> <DEDENT> return '*' + self.text[self.pos:self.pos + length] + '*' | Return a sample of the remaining text. | 625941e9e5267d203edce14c |
def clear_secret_key_from_email_address(self, email_secret_key): <NEW_LINE> <INDENT> email_address_found = False <NEW_LINE> email_address = None <NEW_LINE> status = '' <NEW_LINE> try: <NEW_LINE> <INDENT> if positive_value_exists(email_secret_key): <NEW_LINE> <INDENT> email_address = EmailAddress.objects.get( secret_key... | :param email_secret_key:
:return: | 625941e9cb5e8a47e48b7f58 |
def make_loss_hessian_func(self, ext): <NEW_LINE> <INDENT> loss_hessian_strategy = ext.loss_hessian_strategy <NEW_LINE> if loss_hessian_strategy == LossHessianStrategy.EXACT: <NEW_LINE> <INDENT> return self.derivatives.sqrt_hessian <NEW_LINE> <DEDENT> elif loss_hessian_strategy == LossHessianStrategy.SAMPLING: <NEW_LIN... | Get function that produces the backpropagated quantity. | 625941e97047854f462a18b9 |
def shutdown_session(exception=None): <NEW_LINE> <INDENT> Session.remove() | Remove the DB session at the end of each request. | 625941e9d10714528d60019e |
def get_ensembl_gene(ensembl_id, ENSEMBL_REST_SERVER=GRCH37_ENSEMBL_REST_SERVER): <NEW_LINE> <INDENT> key = (ensembl_id, ENSEMBL_REST_SERVER) <NEW_LINE> if key not in known_genes: <NEW_LINE> <INDENT> known_genes[key] = Gene( name=ensembl_id, id=ensembl_id, chrom=None, tss=None, biotype=None ) <NEW_LINE> <DEDENT> return... | Get gene details from name
* string
Returntype: Gene | 625941e98c3a873295158876 |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_get_struct_Hf().pack(_x.flags, _x.score)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) <NEW_LINE> ... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941e9be8e80087fb210f1 |
def _sparse_copy(src_path, dst_path, virtual_size, block_size=4096): <NEW_LINE> <INDENT> start_time = last_log_time = timeutils.utcnow() <NEW_LINE> EMPTY_BLOCK = '\0' * block_size <NEW_LINE> bytes_read = 0 <NEW_LINE> skipped_bytes = 0 <NEW_LINE> left = virtual_size <NEW_LINE> LOG.debug("Starting sparse_copy src=%(src_p... | Copy data, skipping long runs of zeros to create a sparse file. | 625941e9aad79263cf390efe |
def jd(seconds): <NEW_LINE> <INDENT> return T0 + seconds / S_PER_DAY | Convert a number of seconds since J2000 to a Julian Date.
| 625941e9d6c5a10208144504 |
def clear(self, clear_settings): <NEW_LINE> <INDENT> for attr in self._cached_attrs: <NEW_LINE> <INDENT> delattr(self, attr) <NEW_LINE> <DEDENT> self._cached_attrs.clear() <NEW_LINE> if clear_settings: <NEW_LINE> <INDENT> self.user_settings.clear() | 清空缓存,或用户配置 | 625941e944b2445a33932548 |
def texts( self, nb_texts: int = 3, max_nb_chars: int = 200, ext_word_list: Optional[Sequence[str]] = None, ) -> List[str]: <NEW_LINE> <INDENT> return [self.text(max_nb_chars, ext_word_list) for _ in range(0, nb_texts)] | Generate a list of text strings.
The ``nb_texts`` argument controls how many text strings the list will
contain, and this method uses |text| under the hood for text generation,
so the two remaining arguments, ``max_nb_chars`` and ``ext_word_list``
will work in exactly the same way as well.
:sample: nb_texts=5
:sample... | 625941e930c21e258bdfa958 |
def __str__(self): <NEW_LINE> <INDENT> currentTime=map(lambda x: "0"+str(x) if x<10 else str(x),[self.timeNow.tm_mday,self.timeNow.tm_mon, self.timeNow.tm_year, self.timeNow.tm_hour,self.timeNow.tm_min, self.timeNow.tm_sec]) <NEW_LINE> return self.mode.value.format(*currentTime) | Is used to create string representation of the MyTime Class to be used in print, etc | 625941e9dd821e528d63b65b |
def _video_buddy_for_message(self, message): <NEW_LINE> <INDENT> _from = message.get_from() <NEW_LINE> if _from.domain != 'guest.digsby.org': <NEW_LINE> <INDENT> return log.info('not a video widget: domain is %r', _from.domain) <NEW_LINE> <DEDENT> resource = _from.resource <NEW_LINE> if not resource.startswith('video.'... | Returns a video buddy info for a message object. | 625941e9435de62698dfe102 |
def init_with_list(self, lst): <NEW_LINE> <INDENT> n = len(lst) <NEW_LINE> if n < 1: <NEW_LINE> <INDENT> raise BITError('Illegal input length') <NEW_LINE> <DEDENT> self.tree_lst = [0] * (n + 1) <NEW_LINE> for j, x in enumerate(lst): <NEW_LINE> <INDENT> self.add_at(j, x) | This implementation requires O(n*lg(n)) operations.
:param lst: the list to initialize the tree with
:return: | 625941e9bde94217f36832a2 |
def __init__(self, expectation=0.001): <NEW_LINE> <INDENT> self._mean = float(expectation) | Constructor method. The parameters are used to construct the
probability distribution.
@param expectation: mean success probability; S{lambda} | 625941e9b7558d58953c53c0 |
def __init__(self, addresses=[], authport=1812, acctport=1813, coaport=3799, hosts=None, dict=None): <NEW_LINE> <INDENT> host.Host.__init__(self, authport, acctport, coaport, dict) <NEW_LINE> if hosts is None: <NEW_LINE> <INDENT> self.hosts = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.hosts = hosts <NEW_LINE... | Constructor.
:param addresses: IP addresses to listen on
:type addresses: sequence of strings
:param authport: port to listen on for authentication packets
:type authport: integer
:param acctport: port to listen on for accounting packets
:type acctport: integer
:param coaport: port to listen on for CoA packets... | 625941e9e76e3b2f99f3acba |
def _import_controllers(): <NEW_LINE> <INDENT> exports = [] <NEW_LINE> package_path = os.path.dirname(__file__) <NEW_LINE> for module_file in os.listdir(package_path): <NEW_LINE> <INDENT> if module_file[0] != '_' and module_file[-3:] == '.py': <NEW_LINE> <INDENT> exports.append(module_file[:-3]) <NEW_LINE> <DEDENT> <DE... | Dynamically import all modules containing controllers.
Unlike models, these are not injected into the global
environment upon import. | 625941e9090684286d50f1a2 |
def test_product_link(self): <NEW_LINE> <INDENT> login.login(self.driver, 'test01', 'newdream123') <NEW_LINE> self.driver.find_element(By.XPATH,'//li[@data-id="product"]').click() <NEW_LINE> WebDriverWait(self.driver,10).until(EC.title_is('产品主页 - 禅道')) | 验证产品菜单能否正确链接 | 625941e97b25080760e3990c |
def sdata(s): <NEW_LINE> <INDENT> return set(iv.data for iv in s) | Makes a set of all data fields in an iterable of Intervals. | 625941e9498bea3a759b9f63 |
def test_stacked_lstm_char_prediction(): <NEW_LINE> <INDENT> alphabet = string.ascii_lowercase <NEW_LINE> number_of_chars = len(alphabet) <NEW_LINE> sequence_length = 2 <NEW_LINE> sentences = [alphabet[i: i + sequence_length] for i in range(len(alphabet) - sequence_length)] <NEW_LINE> next_chars = [alphabet[i + sequenc... | Learn alphabetical char sequence with stacked LSTM.
Predict the whole alphabet based on the first two letters ('ab' -> 'ab...z')
See non-toy example in examples/lstm_text_generation.py | 625941e9379a373c97cfaffd |
def test_init_02(self): <NEW_LINE> <INDENT> babi = babigo.Babigo(APPID, CACHE) | babbigo concate test
Arguments:
- `self`: | 625941e921bff66bcd684e04 |
def __init__( self, app ): <NEW_LINE> <INDENT> super( HDCAManager, self ).__init__( app ) | Set up and initialize other managers needed by hdcas. | 625941e93617ad0b5ed683ac |
def VectorizeLoop(enable_vectorize: bool = True): <NEW_LINE> <INDENT> return _ffi_api.VectorizeLoop(enable_vectorize) | Lower vectorization loops.
Parameters
----------
enable_vectorize : bool
Whether vectorization is enabled.
Will lower to scalar loop when it is turned off.
Returns
-------
fpass : tvm.transform.Pass
The result pass | 625941e9656771135c3ebd2a |
def convert_percentile_to_thresh(g, percentile): <NEW_LINE> <INDENT> assert percentile < 100 and percentile > 0, ( "percentile must be between 0 and 100. percentile: {}".format(percentile)) <NEW_LINE> thresh = np.nanpercentile(np.abs(g.es["weight"]), percentile) <NEW_LINE> return thresh | Figure out what value in g corresponds to the given percentile.
Args:
@param g:
@type g: igraph.Graph
@param percentile: between 0 and 100
@type percentile: float
Returns:
thresh | 625941e9cb5e8a47e48b7f59 |
def _hincrby(self, hashkey, attribute, command, type_, increment): <NEW_LINE> <INDENT> redis_hash = self._get_hash(hashkey, command, create=True) <NEW_LINE> attribute = self._encode(attribute) <NEW_LINE> previous_value = type_(self._decode(redis_hash.get(attribute, '0'))) <NEW_LINE> redis_hash[attribute] = self._encode... | Shared hincrby and hincrbyfloat routine | 625941e97c178a314d6ef91d |
def connect(self, stage, service, db=None): <NEW_LINE> <INDENT> cluster_id = self._get_cluster_id(stage, service) <NEW_LINE> print('Getting ElastiCache node info...') <NEW_LINE> resp = redis.describe_cache_clusters( CacheClusterId=cluster_id, ShowCacheNodeInfo=True) <NEW_LINE> assert len(resp['CacheClusters']) == 1 <NE... | Connect to ElastiCache by redis-cli | 625941e929b78933be1e5b5c |
def setUp(self): <NEW_LINE> <INDENT> self.hass = get_test_home_assistant() <NEW_LINE> self.hass.config.components.add('group') <NEW_LINE> self.hass.config.components.add('sun') <NEW_LINE> self.calls = [] <NEW_LINE> @callback <NEW_LINE> def record_call(service): <NEW_LINE> <INDENT> self.calls.append(service) <NEW_LINE> ... | Setup things to be run when tests are started. | 625941e9cc40096d61595e04 |
def test_init(self): <NEW_LINE> <INDENT> st = PrepTemplate(1) <NEW_LINE> self.assertTrue(st.id, 1) | Init successfully instantiates the object | 625941e976e4537e8c351b2c |
def __init__(self): <NEW_LINE> <INDENT> self.data = [] <NEW_LINE> self.minData = [] | initialize your data structure here. | 625941e9d18da76e23532992 |
def __init__(self, code: int, data_rcv: Optional[bytes] = None ) -> None: <NEW_LINE> <INDENT> self.code: int = code <NEW_LINE> self.data_rcv: bytes = data_rcv <NEW_LINE> self.data = None | Constructor of the class BitcopMessage
In the subclasses, data needs to be added
:param code: integer code of the message
:param data_rcv: stream of data bytes received that will be parsed to construct the object. None if the object
is being created to send a new message. | 625941e9167d2b6e3121904b |
def delete_memoized(self, *keys): <NEW_LINE> <INDENT> def deletes(item): <NEW_LINE> <INDENT> if item[0] in keys: <NEW_LINE> <INDENT> self.cache.delete(item[1]) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> self._memoized[:] = [x for x in self._memoized if not deletes(x)] | Deletes all of the cached functions that used Memoize for caching.
Example::
@cache.memoize(50)
def random_func():
return random.randrange(1, 50)
.. code-block:: pycon
>>> random_func()
43
>>> random_func()
43
>>> cache.delete_memoized('random_func')
>>> random_func()
... | 625941e938b623060ff0b2a3 |
def run_test(self): <NEW_LINE> <INDENT> print("Generating {} random routes with prefix between {} and {}".format( self.entries, self.minprefix, self.maxprefix)) <NEW_LINE> self.routes = self.generate_random_routes() <NEW_LINE> print("... done.") <NEW_LINE> print("Inserting initial routes into the switch...") <NEW_LINE>... | Run actual test | 625941e9baa26c4b54cb15d1 |
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: <NEW_LINE> <INDENT> arr = [] <NEW_LINE> i = j = 0 <NEW_LINE> while i<m and j<n: <NEW_LINE> <INDENT> if nums1[i] < nums2[j]: <NEW_LINE> <INDENT> arr.append(nums1[i]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> arr.append(num... | Do not return anything, modify nums1 in-place instead. | 625941e94c3428357757c7db |
def _bounded_selector(self, selector): <NEW_LINE> <INDENT> return '.discussions-management {}'.format(selector) | Return `selector`, but limited to the divided discussion management context. | 625941e94e696a04525c9904 |
def pipeline( self, operations, index=0, fragment=False, multiple=0, timeout=None, depth=1 ): <NEW_LINE> <INDENT> class drainable( collections.deque ): <NEW_LINE> <INDENT> def __iter__( self ): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__( self ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return ... | Issue the requested 'operations', allowing up to 'depth' outstanding requests to be in the
pipeline, before beginning to harvest results. Yield each harvested record. | 625941e956ac1b37e626467c |
def parse(text, problem_class=None, special=None): <NEW_LINE> <INDENT> Problem = problem_class or models.StandardProblem <NEW_LINE> return Problem.parse(text, special=special) | Load a problem from raw text.
:param str text: text of a TSPLIB problem
:param type problem_class: special/custom problem class
:param callable special: special/custom distance function
:return: problem instance
:rtype: :class:`~Problem` | 625941e9e5267d203edce14d |
def combine_images(img_list): <NEW_LINE> <INDENT> up = np.hstack(img_list[:2]) <NEW_LINE> down = np.hstack(img_list[2:]) <NEW_LINE> full = np.vstack([up, down]) <NEW_LINE> return full | Combines imgs using indexes as follows:
0 1
2 3 | 625941e9097d151d1a22330d |
def __call__(self, width=None, over=None): <NEW_LINE> <INDENT> over = over or OVERSAMPLING <NEW_LINE> if width is None: <NEW_LINE> <INDENT> if self.pos is None: <NEW_LINE> <INDENT> self.pos, self.intensity = self.funct(self.width) <NEW_LINE> <DEDENT> return self.pos, self.intensity <NEW_LINE> <DEDENT> else: <NEW_LINE> ... | Return the beam profile I=f(x) | 625941e92ae34c7f2600d5e7 |
def __init__(self, site1, site2): <NEW_LINE> <INDENT> self.site1 = site1 <NEW_LINE> self.site2 = site2 | Args:
site1:
First site.
site2:
Second site. | 625941e9956e5f7376d71322 |
def degrees_of_freedom(self, assumption="paths"): <NEW_LINE> <INDENT> assert assumption in ['paths', 'ngrams'], 'Error: Invalid assumption' <NEW_LINE> if assumption == 'paths': <NEW_LINE> <INDENT> return self.dof_paths <NEW_LINE> <DEDENT> return self.dof_ngrams | Calculates the degrees of freedom (i.e. number of parameters) of
this k-order model. Depending on the modeling assumptions, this either
corresponds to the number of paths of length k in the first-order network
or to the number of all possible k-grams. The degrees of freedom of a model
can be used to assess the model co... | 625941e966673b3332b92547 |
def getChildName(self): <NEW_LINE> <INDENT> parent = self.getParent() <NEW_LINE> for key, value in parent.getVisitableNodesNamed(): <NEW_LINE> <INDENT> if self is value: <NEW_LINE> <INDENT> return key <NEW_LINE> <DEDENT> if type(value) is tuple: <NEW_LINE> <INDENT> if self in value: <NEW_LINE> <INDENT> return key, valu... | Return the role in the current parent, subject to changes. | 625941e9d164cc6175783205 |
def __init__(self): <NEW_LINE> <INDENT> self.InstanceAdvanceSettings = None <NEW_LINE> self.InstanceId = None <NEW_LINE> self.InstanceRole = None <NEW_LINE> self.FailedReason = None <NEW_LINE> self.InstanceState = None | :param InstanceAdvanceSettings: 实例的附加信息
:type InstanceAdvanceSettings: :class:`tencentcloud.tke.v20180525.models.InstanceAdvancedSettings`
:param InstanceId: 实例ID
:type InstanceId: str
:param InstanceRole: 节点角色, MASTER, WORKER, ETCD, MASTER_ETCD,ALL, 默认为WORKER
:type InstanceRole: str
:param FailedReason: 实例异常(或者处于初始化中)... | 625941e907d97122c4178d4d |
@command(venusian_category='irc3.debug') <NEW_LINE> def reconnect(bot, mask, target, args): <NEW_LINE> <INDENT> plugin = bot.get_plugin(utils.maybedotted('irc3.plugins.core.Core')) <NEW_LINE> bot.loop.call_soon(plugin.reconnect) | force reconnect
%%reconnect | 625941e93346ee7daa2b3226 |
def GetInstanceMetadata(self, iid): <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> kwargs['InstanceId'] = iid <NEW_LINE> val = self.request(**kwargs) <NEW_LINE> return val['InstanceMetadata'] | 获取虚拟机的metadata
:param iid: 虚拟机ID
:type iid: string
:returns: 一个dict包含虚拟机所有metadata的key/value | 625941e966673b3332b92548 |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_5B.pack(_x.version, _x.supported, _x.defaultGnss, _x.enabled, _x.simultaneous)) <NEW_LINE> _x = self.reserved1 <NEW_LINE> if type(_x) in [list, tuple]: <NEW_LINE> <INDENT> buff.write(_struct_3B.pack(*_x)) <NE... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941e930dc7b7665901e17 |
def init(module_name="cyber_py"): <NEW_LINE> <INDENT> return _CYBER_INIT.py_init(module_name) | init cyber. | 625941e95fcc89381b1e1b79 |
def _ex_populate_volume_dict(self): <NEW_LINE> <INDENT> aggregated_items = self.connection.request_aggregated_items( "disks") <NEW_LINE> self._ex_volume_dict = self._build_volume_dict( aggregated_items['items']) <NEW_LINE> return None | Fetch the volume information using disks/aggregatedList
and store it in _ex_volume_dict.
return: ``None`` | 625941e95fdd1c0f98dc06ec |
def __str__(self): <NEW_LINE> <INDENT> string = '<script type="text/javascript">\n' <NEW_LINE> string += 'function init()\n' <NEW_LINE> string += '{\n' <NEW_LINE> for image, regions, colormap, contrast_bias, scale, interval, zoom, pan in zip(self.images, self.regions, self.colormaps, self.contrast_biases, self.scales, ... | This function ...
:return: | 625941e98da39b475bd65430 |
def cache(action): <NEW_LINE> <INDENT> action.cached = True <NEW_LINE> return action | Decorator which adds the *cached* attribute to the function.
Use *@cache* to force caching to always occur (for example, when
the function references remote resources, vastly reduces memory, or is
expensive to compute. Use *@nocache* when debugging a function
so that it will be recomputed each time regardless of whet... | 625941e930dc7b7665901e18 |
def tableview_delete(self, tableview, section, row): <NEW_LINE> <INDENT> pass | Called when the user confirms deletion of the given row.
| 625941e9097d151d1a22330e |
def get(self, chapter): <NEW_LINE> <INDENT> path = os.path.expanduser(self.path) <NEW_LINE> if not os.path.isdir(path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(path) <NEW_LINE> <DEDENT> except OSError as msg: <NEW_LINE> <INDENT> raise MangaException(msg) <NEW_LINE> <DEDENT> <DEDENT> cbz_name = chapter.... | Downloads manga chapter as cbz archive | 625941e9711fe17d82542817 |
def get_fixed_timezone(offset): <NEW_LINE> <INDENT> if isinstance(offset, datetime.timedelta): <NEW_LINE> <INDENT> offset = offset.seconds // 60 <NEW_LINE> <DEDENT> sign = '-' if offset < 0 else '+' <NEW_LINE> hhmm = '%02d%02d' % divmod(abs(offset), 60) <NEW_LINE> name = sign + hhmm <NEW_LINE> return FixedOffset(offset... | Return a tzinfo instance with a fixed offset from UTC. | 625941e938b623060ff0b2a4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.