code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def generate_ethsig( self, private_key: bytes, msg_hash: typing.Optional[bytes] = None ) -> None: <NEW_LINE> <INDENT> if not self.requestor_ethereum_public_key: <NEW_LINE> <INDENT> raise exceptions.FieldError( "It doesn't really make sense to" " generate the ethereum signature" " with no `requestor_ethereum_public_key`... | Calculate and set message's ethereum signature
using the provided ethereum private key by signing nested
WantToComputeTask message.
:param private_key: ethereum private key
:param msg_hash: may be optionally provided to skip generation
of the message hash while signing. If not provided,
... | 625941e8377c676e91272628 |
def test_get_unit_of_measure_by_id(self): <NEW_LINE> <INDENT> pass | Test case for get_unit_of_measure_by_id
Returns a single unit-of-measure corresponding to the unique id or name specified. | 625941e8a79ad161976cc5c7 |
def __init__(self, raw: dict): <NEW_LINE> <INDENT> self.raw = raw <NEW_LINE> self._parse(**raw) | :param raw: Объект account от balances_list
:type raw: dict | 625941e88a43f66fc4b544e1 |
def handlePlayerCommands(player,event): <NEW_LINE> <INDENT> if event.type == pygame.KEYDOWN: <NEW_LINE> <INDENT> if event.key == pygame.K_RIGHT: <NEW_LINE> <INDENT> player.moveRight() <NEW_LINE> <DEDENT> if event.key == pygame.K_LEFT: <NEW_LINE> <INDENT> player.moveLeft() <NEW_LINE> <DEDENT> if event.key == pygame.K_UP... | :param player: the player object to be manipulated
:param event: an event from the pygame.event queue to be checked | 625941e8d486a94d0b98e5c8 |
def get_extent_offsets(self, renderer): <NEW_LINE> <INDENT> whd_list = [c.get_extent(renderer) for c in self.get_children()] <NEW_LINE> whd_list = [(w, h, xd, (h-yd)) for w, h, xd, yd in whd_list] <NEW_LINE> wd_list = [(w, xd) for w, h, xd, yd in whd_list] <NEW_LINE> width, xdescent, xoffsets = _get_aligned_offsets(wd_... | update offset of childrens and return the extents of the box | 625941e8dd821e528d63b626 |
def test_add_event_data_type_error(self): <NEW_LINE> <INDENT> payload = {'eid':11,'name':'一加5手机发布会','limit':2000,'address':"深圳宝体",'start_time':'2017','time':self.client_time,'sign':self.sign_md5} <NEW_LINE> r = requests.post(self.base_url,data=payload) <NEW_LINE> result = r.json() <NEW_LINE> self.assertEqual(result['st... | 日期格式错误 | 625941e8f548e778e58cda01 |
def get(self, file_id): <NEW_LINE> <INDENT> def ok(doc): <NEW_LINE> <INDENT> if doc is None: <NEW_LINE> <INDENT> raise NoFile("TxMongo: no file in gridfs with _id {0}".format(repr(file_id))) <NEW_LINE> <DEDENT> return GridOut(self.__collection, doc) <NEW_LINE> <DEDENT> return self.__collection.files.find_one({"_id": fi... | Get a file from GridFS by ``"_id"``.
Returns an instance of :class:`~gridfs.grid_file.GridOut`,
which provides a file-like interface for reading.
:Parameters:
- `file_id`: ``"_id"`` of the file to get
.. versionadded:: 1.6 | 625941e84c3428357757c7a6 |
def __apply(self, expr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self['$$nrpush']('apply') <NEW_LINE> return self['$eval'](expr) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.__digest() <NEW_LINE> self['$$nrpop']('apply') | Performs an evaluation of an expression, and then a digest cycle. | 625941e80a366e3fb873eca0 |
def test_Parenchyma1(self): <NEW_LINE> <INDENT> self.delayDisplay("Starting the test") <NEW_LINE> import urllib <NEW_LINE> downloads = ( ('http://10.163.46.32/midas/download?items=163', '0.nrrd', slicer.util.loadVolume),) <NEW_LINE> for url,name,loader in downloads: <NEW_LINE> <INDENT> filePath = slicer.app.temporaryPa... | Ideally you should have several levels of tests. At the lowest level
tests sould exercise the functionality of the logic with different inputs
(both valid and invalid). At higher levels your tests should emulate the
way the user would interact with your code and confirm that it still works
the way you intended.
One o... | 625941e8be383301e01b58fe |
def _node_out_link_ids(shape): <NEW_LINE> <INDENT> node_horizontal_link_ids = np.empty(shape, np.int) <NEW_LINE> node_horizontal_link_ids[:, :-1] = horizontal_link_ids(shape) <NEW_LINE> node_horizontal_link_ids[:, -1] = -1 <NEW_LINE> node_vertical_link_ids = np.empty(shape, np.int) <NEW_LINE> node_vertical_link_ids[:-1... | Link IDs for links leaving each node.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
tuple :
Tuple of array of link IDs as (vertical_links, horizontal_links).
Examples
--------
>>> from landlab.grid.structured_quad.links import _node_out_link_ids
>>> (vert, horiz) = _node_... | 625941e8e76e3b2f99f3ac85 |
def _update(self, data, stat): <NEW_LINE> <INDENT> self._data = funcs.decode(data) <NEW_LINE> self._stat = stat <NEW_LINE> log.debug('[%s] Data change detected: %s, Stat: %s' % (self._path, self._data, self._stat)) <NEW_LINE> if self._watch_children and stat and not self._current_children_watch: <NEW_LINE> <INDENT> log... | Function executed by Kazoo upon data/stat changes for a path.
This function is registered during the __init__ process of this
Object with Kazoo. Upon the initial registration, and any subsequent
changes to the 'data' or 'stat' of a path, this function is called
again.
This function is responsible for updating the loc... | 625941e8ac7a0e7691ed4545 |
def restart(container, timeout=10): <NEW_LINE> <INDENT> client = _get_client() <NEW_LINE> status = base_status.copy() <NEW_LINE> try: <NEW_LINE> <INDENT> dcontainer = _get_container_infos(container)['Id'] <NEW_LINE> client.restart(dcontainer, timeout=timeout) <NEW_LINE> if is_running(dcontainer): <NEW_LINE> <INDENT> _v... | Restart a running container
container
container id
timeout
timeout for container to exit gracefully before killing it, Default is ``10`` seconds
CLI Example:
.. code-block:: bash
salt '*' docker.restart <container id> [timeout=20] | 625941e8f9cc0f698b140a79 |
def jrn(self, n): <NEW_LINE> <INDENT> self._jrcn(True, n) | Decrements/increments the PC by the signed byte n. | 625941e81d351010ab855f9c |
def replace(self, row, col_name, val): <NEW_LINE> <INDENT> self.remove_row(row, reorder=False) <NEW_LINE> key = [c[row] for c in self.columns] <NEW_LINE> key[self.col_position(col_name)] = val <NEW_LINE> self.data.add(tuple(key), row) | Replace the value of a column at a given position.
Parameters
----------
row : int
Row number to modify
col_name : str
Name of the Column to modify
val : col.info.dtype
Value to insert at specified row of col | 625941e83317a56b8693a0ce |
def update_week_days_list(self): <NEW_LINE> <INDENT> self.list_weekDays.clear() <NEW_LINE> for item in self.week_days: <NEW_LINE> <INDENT> time = f' - {item["hour"]:02}:{item["minute"]:02}' if self.group['type'] > 1 else '' <NEW_LINE> result = self.week_day_names[item['week_day']] + time <NEW_LINE> self.list_weekDays.a... | Обновление виджета списка дней недели | 625941e88e05c05ec3eea7fa |
def test_positiveStartPositiveStopLength(self): <NEW_LINE> <INDENT> sequence = ['a', 'b', 'c'] <NEW_LINE> view = SlicedView(sequence, slice(1, 2)) <NEW_LINE> self.assertEqual(len(view), 1) | Similar to L{test_length}, but for a L{SlicedView} constructed with a
slice with positive start and stop values. | 625941e8956e5f7376d712ed |
def __init__(self,*l,**kw): <NEW_LINE> <INDENT> kw_c = kw.copy() <NEW_LINE> cacheParsed = kw_c.pop("cacheParsed",False) <NEW_LINE> FastaReader.__init__(self,*l,**kw_c) <NEW_LINE> self.cacheParsed = cacheParsed <NEW_LINE> if cacheParsed: <NEW_LINE> <INDENT> self.parsedCache = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND... | Ctor.
@param cacheParsed Flag to cache previously read parsed headers [False].
Set to True if you expect to query records with findIdPep() in the order
different from the order in the input file. Beware of memory consumption
if you set this to True. | 625941e8b57a9660fec33d0c |
def cast(*args): <NEW_LINE> <INDENT> return _ITKCommonBasePython.itkMetaDataObjectBase_cast(*args) | cast(itkLightObject obj) -> itkMetaDataObjectBase | 625941e8435de62698dfe0ce |
def reload(self): <NEW_LINE> <INDENT> log.debug("{} is being reloaded".format(self.name())) <NEW_LINE> self._server.send_message("qemu.reload", {"id": self._qemu_id}, self._reloadCallback) | Reloads this QEMU VM instance. | 625941e8de87d2750b860219 |
def sendKexInit(self): <NEW_LINE> <INDENT> if self._keyExchangeState != self._KEY_EXCHANGE_NONE: <NEW_LINE> <INDENT> raise RuntimeError( "Cannot send KEXINIT while key exchange state is %r" % ( self._keyExchangeState,)) <NEW_LINE> <DEDENT> self.ourKexInitPayload = b''.join([ chr(MSG_KEXINIT), randbytes.secureRandom(16)... | Send a I{KEXINIT} message to initiate key exchange or to respond to a
key exchange initiated by the peer.
@raise RuntimeError: If a key exchange has already been started and it
is not appropriate to send a I{KEXINIT} message at this time.
@return: C{None} | 625941e8004d5f362079a7b2 |
def search(self, search_query): <NEW_LINE> <INDENT> raise StoreMethodNotImplemented('this store does not provide search') | Search the entire :py:class:`tiddler
<tiddlyweb.model.tiddler.Tiddler>` store for ``search_query``.
How search operates is entirely dependent on the StorageInterface
implementation. The only requirement is that an iterator of
tiddler objects is returned. | 625941e823e79379d52ee9e0 |
def handlingOneDb(self,sqlstr = ""): <NEW_LINE> <INDENT> if self.dbName is not None: <NEW_LINE> <INDENT> operDict = { "delete" : self.dbManager.deleteData, "add": self.dbManager.insertData, "update": self.dbManager.updateData } <NEW_LINE> sqlOperType = self.sqldict[sqlstr][0] <NEW_LINE> sqlStr = self.sqldict... | :param sqlls:
:return: | 625941e83539df3088e2e7cd |
def test_review_replies(self): <NEW_LINE> <INDENT> addon = Addon.objects.get(id=3615) <NEW_LINE> u = UserProfile.objects.get(pk=2519) <NEW_LINE> version = addon.get_current_version() <NEW_LINE> new_review = Review(version=version, user=u, rating=2, body='hello', addon=addon) <NEW_LINE> new_review.save() <NEW_LINE> new_... | Make sure that developer replies are not returned as if they were
original reviews. | 625941e885dfad0860c3b2dd |
def test_halt_expected(self): <NEW_LINE> <INDENT> halt = make_halt_function([6, 5]) <NEW_LINE> g1 = Genome([6, 6, 5]) <NEW_LINE> g1.fitness = MAX_REWARD <NEW_LINE> population = [ g1, ] <NEW_LINE> result = halt(population, 1) <NEW_LINE> self.assertTrue(result) | Ensure the function returns true if we're in a halting state. | 625941e86e29344779a62a91 |
def delete_cert(cert_store: CertificateStore, cert_path: str): <NEW_LINE> <INDENT> entry = CertificateStoreEntryImpl( details=get_certificate_details(cert_path), certificate=None) <NEW_LINE> cert_store.remove(entry) | Deletes the certificate designated in the path
:param cert_store: the certificate store
:type cert_store: CertificateStore
:param cert_path: the certificate path
:type cert_path: str | 625941e897e22403b379d41d |
def export_text_editor_shaders(self): <NEW_LINE> <INDENT> is_shaders = False <NEW_LINE> for t in bpy.data.texts: <NEW_LINE> <INDENT> if t.filepath: <NEW_LINE> <INDENT> name = os.path.basename(t.filepath) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = t.name <NEW_LINE> <DEDENT> ext = os.path.splitext(name)[1] <NEW... | Export all shaders in the text editor into text files. | 625941e810dbd63aa1bd3023 |
def duplicate(mode: typing.Union[str, int] = 'TRANSLATION'): <NEW_LINE> <INDENT> pass | Duplicate the selected strips
:param mode: Mode
:type mode: typing.Union[str, int] | 625941e8aad79263cf390ec9 |
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None): <NEW_LINE> <INDENT> import signal <NEW_LINE> class TimeoutError(Exception): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def handler(signum, frame): <NEW_LINE> <INDENT> raise TimeoutError() <NEW_LINE> <DEDENT> signal.signal(signal.SIGALRM, handler... | breaks the function func after timeout_duration seconds
# args = non named
# kwargs = named arguments | 625941e8d53ae8145f87a6e9 |
def checkTradeWindow(): <NEW_LINE> <INDENT> for y in range(cols): <NEW_LINE> <INDENT> for x in range(rows): <NEW_LINE> <INDENT> checkSlot(y,x) <NEW_LINE> <DEDENT> <DEDENT> sortOffered() | Will check every slot in the trade window and log its type and amount | 625941e8d18da76e2353295d |
def __init__(self, data, mbid, utc): <NEW_LINE> <INDENT> bytes, fmtid, t5, t4, t3, t2, t1, t0 = unpack('>hh6B', data[0:10]) <NEW_LINE> self.mbid = '%12.12x' % mbid <NEW_LINE> self.utc = utc <NEW_LINE> self.scalers = unpack('%dB' % (bytes - 10), data[10:]) <NEW_LINE> self.domclk = ((((t5 << 8 | t4) << 8 | t3) ... | Create from payload | 625941e8c432627299f050cb |
def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self._lock.release() | Context manager exit the block, release the lock. | 625941e8ec188e330fd5ac18 |
def getIndices(elem, dof): <NEW_LINE> <INDENT> ind = np.empty(dof*elem.size, dtype=np.int32) <NEW_LINE> for i in range(dof): <NEW_LINE> <INDENT> ind[i::dof] = dof*elem + i <NEW_LINE> <DEDENT> return ind | Return matrix indices for each dof for a given element
using the PETSc numbering.
Parameters
==========
elem : ndarray
The list of the mesh elements.
dof : int
Number of dof (2 in 2d and 3 in 3d).
Returns
=======
ind : ndarray
The list of the entries in the matrix. | 625941e85166f23b2e1a55db |
def rgb2grey(rgb): <NEW_LINE> <INDENT> return _convert(grey_from_rgb, rgb[:, :, :3])[..., 0] | Compute luminance of an RGB image.
Parameters
----------
rgb : array_like
The image in RGB format, in a 3-D array of shape (.., .., 3),
or in RGBA format with shape (.., .., 4).
Returns
-------
out : ndarray
The luminance image, a 2-D array.
Raises
------
ValueError
If `rgb2grey` is not a 3-D array o... | 625941e8e1aae11d1e74a13d |
def start_moving(self, includes): <NEW_LINE> <INDENT> compress = '--skip-compress={0}'.format('/'.join(self.skip_compress)) <NEW_LINE> exclude = ' '.join( map(lambda x: '='.join(['--exclude', x]), self.exclusions), ) <NEW_LINE> include = ' '.join( map(lambda x: '='.join(['--include', x]), includes), ) <NEW_LINE> if sel... | Генерирует команду для переноса и начинает его. | 625941e830c21e258bdfa924 |
def pmodel(m): <NEW_LINE> <INDENT> total = 0 <NEW_LINE> count = 0 <NEW_LINE> for num in m: <NEW_LINE> <INDENT> numv = m[num].as_long() <NEW_LINE> total += numv <NEW_LINE> print('[*] num{}:\t{}'.format(count, hex(numv))) <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> total &= 0xffffffff <NEW_LINE> print('[*] value:\t{}'.form... | Extracts values from z3 model and prints solutions.
Args:
m: z3 models that's been satified. | 625941e810dbd63aa1bd3024 |
def __init__(self, jsondict=None, strict=True, **kwargs): <NEW_LINE> <INDENT> self.code = None <NEW_LINE> self.criteria = None <NEW_LINE> self.description = None <NEW_LINE> super(MeasureGroupStratifierComponent, self).__init__(jsondict=jsondict, strict=strict, **kwargs) | Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError | 625941e8925a0f43d254a2fd |
def calculateAirDistance(self,start_lat,star_lang,end_lat,end_lang): <NEW_LINE> <INDENT> if not star_lang or not start_lat or not end_lang or not end_lat: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> R = 6373.0 <NEW_LINE> lat1 = radians(start_lat) <NEW_LINE> lon1 = radians(star_lang) <NEW_LINE> lat2 = radians(en... | will calculate the distance in KM between two coordinates
:param start_lat: start lattitude
:param star_lang: start longtitude
:param end_lat: end lattitude
:param end_lang: end longtitude
:return: | 625941e830bbd722463cc24a |
def initialise(self): <NEW_LINE> <INDENT> self.logger.debug("%s.initialise()" % self.__class__.__name__) <NEW_LINE> if self.clearing_policy == common.ClearingPolicy.ON_INITIALISE: <NEW_LINE> <INDENT> self.matching_result = None <NEW_LINE> <DEDENT> self.check_attr = operator.attrgetter(self.variable_name) | Clears the internally stored message ready for a new run
if ``old_data_is_valid`` wasn't set. | 625941e8379a373c97cfafc8 |
def clear_widget(self, event): <NEW_LINE> <INDENT> if self.userbox == self.focus_get() and self.userbox.get() == 'Enter Username': <NEW_LINE> <INDENT> self.userbox.delete(0,END) <NEW_LINE> <DEDENT> elif self.passbox == self.focus_get() and self.passbox.get() == 'Password': <NEW_LINE> <INDENT> self.passbox.delete(0,END) | This method clears the entry boxes when you click inside it | 625941e8aad79263cf390eca |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941e8435de62698dfe0cf |
def queryall_process(con, cur, sql, param=None): <NEW_LINE> <INDENT> rows = None <NEW_LINE> try: <NEW_LINE> <INDENT> cur.execute(sql, param) <NEW_LINE> rows = cur.fetchall() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> con.rollback() <NEW_LINE> logger.error(traceback.format_exc()) <NEW_LINE> logger.er... | " queryall:内部调用 | 625941e81b99ca400220af35 |
def Question2(): <NEW_LINE> <INDENT> h = 1 <NEW_LINE> plt.figure(figsize=(5, 3)) <NEW_LINE> lineType = ['g^--', 'bo--', 'rs--', 'yP--', 'g^:', 'm:'] <NEW_LINE> for i in range(6): <NEW_LINE> <INDENT> Display2(GetEuler(function1, 1, 4, h), lineType[i], label=str(h)) <NEW_LINE> h = h/2 <NEW_LINE> <DEDENT> Display2(GetEule... | 2. Plot the Euler solution using several different step-sizes, and exact solution, on the
same graph to show the solution is converging on the exact solution | 625941e83cc13d1c6d3c77fa |
def name_match(pattern, name): <NEW_LINE> <INDENT> match = pattern.match(name) <NEW_LINE> if match: <NEW_LINE> <INDENT> return match.end() == len(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Asserts that the regexp matches the entire name | 625941e855399d3f05588b39 |
def to_normal_errors(axes): <NEW_LINE> <INDENT> ax1 = 1/axes*axes[2]**2 <NEW_LINE> return ax1 | A temporary method that gets normal vector errors
corresponding with a fitted orientation | 625941e876d4e153a657efb5 |
def authorized(req): <NEW_LINE> <INDENT> auth_value = req.headers.get('Authorization') <NEW_LINE> if auth_value is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> token = auth_value.split(sep=' ')[-1] <NEW_LINE> existant_user = User.query.filter_by(auth_token=token).first() <NEW_LINE> if existant_user is Non... | Probes a request object's headers for the Authorization value, a
token. If the token value found belongs to any of our users we accept
the request, otherwise we reject.
Note that at this point the protected areas of the API are accessible
to any of our registered users
The Authorization header takes the form:
Aut... | 625941e81b99ca400220af36 |
def lengthOfLongestSubstring(s): <NEW_LINE> <INDENT> longest, start = 0,0 <NEW_LINE> substring_map = {} <NEW_LINE> for i in range(len(s)): <NEW_LINE> <INDENT> position = substring_map.get(s[i]) <NEW_LINE> if position is not None and position >= start: <NEW_LINE> <INDENT> length = i - start <NEW_LINE> start = position +... | :type s: str
:rtype: int | 625941e863f4b57ef000158e |
def getRandPrime(bits = 1024): <NEW_LINE> <INDENT> r = random.SystemRandom() <NEW_LINE> v = r.getrandbits(bits) <NEW_LINE> while not isPrime(v): <NEW_LINE> <INDENT> v = r.getrandbits(bits) <NEW_LINE> <DEDENT> return v | Get a random prime. | 625941e8be8e80087fb210be |
def edits1(word): <NEW_LINE> <INDENT> splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] <NEW_LINE> deletes = [a + b[1:] for a, b in splits if b] <NEW_LINE> transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] <NEW_LINE> replaces = [a + c + b[1:] for a, b in splits for c in alphabet... | Return possibilities of one operation.
splits: It divides the word in two parts, being the first of length i and the
second one of length len(word) - i with i<=len(word).
deletes: Drops a letter from the word for every pair of splits obtained before.
tranposes: It swaps two consecutive letters on the word for ... | 625941e87d43ff24873a3126 |
def setFIOState(self, fioNum, state = 1): <NEW_LINE> <INDENT> self.getFeedback(BitDirWrite(fioNum, 1), BitStateWrite(fioNum, state)) | Name: U3.setFIOState(fioNum, state = 1)
Args: fioNum, which FIO to change
state, 1 = High, 0 = Low
Desc: A convenience function to set the state of an FIO. Will also
set the direction to output. Note that this function can set
all digital I/O lines (FIO0 - CIO3), and is equivalent to using
the ... | 625941e85f7d997b87174f1e |
def render(self, goal, snake): <NEW_LINE> <INDENT> if self._thread is not None and self._thread.is_alive(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> pygame.quit() <NEW_LINE> raise self.ShutdownError() <NEW_LINE>... | Render the current state of the game. | 625941e8f8510a7c17cf9b82 |
def __init__(self,disable_ssl_verify=False,timeout=60): <NEW_LINE> <INDENT> self.client = requests.session() <NEW_LINE> self.disable_ssl_verify = disable_ssl_verify <NEW_LINE> self.timeout = timeout <NEW_LINE> if self.disable_ssl_verify: <NEW_LINE> <INDENT> urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWar... | Initialize method | 625941e89b70327d1c4e125a |
def last_date_of_month(value): <NEW_LINE> <INDENT> day = calendar.mdays[value.month] <NEW_LINE> if (day == 28) and calendar.isleap(value.year): <NEW_LINE> <INDENT> day = 29 <NEW_LINE> <DEDENT> return datetime.date(value.year, value.month, day) | Dado una fecha (value) devuelve el último día del mes de la fecha dada.
Ej:
value = date(2012, 5, 15) ==> date(2012, 5, 31) | 625941e86aa9bd52df037229 |
def copy(self, filename, **kws): <NEW_LINE> <INDENT> other = TIFF.open(filename, mode='w') <NEW_LINE> define_rewrite = {} <NEW_LINE> for _name, _value in list(kws.items()): <NEW_LINE> <INDENT> define = TIFF.get_tag_define(_name) <NEW_LINE> assert define is not None <NEW_LINE> if _name == 'compression': <NEW_LINE> <INDE... | Copy opened TIFF file to a new file.
Use keyword arguments to redefine tag values.
Parameters
----------
filename : str
Specify the name of file where TIFF file is copied to.
compression : {'none', 'lzw', 'deflate', ...}
Specify compression scheme.
bitspersample : {8,16,32,64,128,256}
Specify bit size of a samp... | 625941e867a9b606de4a8339 |
def plot_function_contour(x, y, function, **kwargs): <NEW_LINE> <INDENT> X, Y = np.meshgrid(x, y) <NEW_LINE> Z = [] <NEW_LINE> for y_value in y: <NEW_LINE> <INDENT> Z.append([]) <NEW_LINE> for x_value in x: <NEW_LINE> <INDENT> Z[-1].append(function(x_value, y_value)) <NEW_LINE> <DEDENT> <DEDENT> Z = np.array(Z) <NEW_LI... | Make a contour plot of a function of two variables.
Parameters
----------
x, y : array_like of float
The positions of the nodes of a plotting grid.
function : function
The function to plot.
filling : bool
Fill contours if True (default).
num_contours : int
The number of contours to plot, 50 by default.... | 625941e88c0ade5d55d3ee41 |
def __minmaxlist(self, x): <NEW_LINE> <INDENT> return x.min(), x.max() | return the minimum and maximum of the array
:param numpy.ndarray x: array to be examined | 625941e84e696a04525c98d0 |
def __init__(self, version, sid): <NEW_LINE> <INDENT> super(AddressConfigurationContext, self).__init__(version) <NEW_LINE> self._solution = {'sid': sid, } <NEW_LINE> self._uri = '/Configuration/Addresses/{sid}'.format(**self._solution) | Initialize the AddressConfigurationContext
:param Version version: Version that contains the resource
:param sid: The SID or Address of the Configuration.
:returns: twilio.rest.conversations.v1.address_configuration.AddressConfigurationContext
:rtype: twilio.rest.conversations.v1.address_configuration.AddressConfigur... | 625941e815baa723493c43fb |
def _test_logits(self, mode, hidden_units, logits_dimension, inputs, expected_logits): <NEW_LINE> <INDENT> with ops.Graph().as_default(): <NEW_LINE> <INDENT> training_util.create_global_step() <NEW_LINE> head = mock_head( self, hidden_units=hidden_units, logits_dimension=logits_dimension, expected_logits=expected_logit... | Tests that the expected logits are passed to mock head. | 625941e856ac1b37e6264649 |
def addLink(root, singleLink): <NEW_LINE> <INDENT> channel = root.find("channel") <NEW_LINE> today = currentTimeStr() <NEW_LINE> item = ET.SubElement(channel, "item") <NEW_LINE> title = ET.SubElement(item, "title") <NEW_LINE> title.text = "Link: " + singleLink.text <NEW_LINE> link = ET.SubElement(item, "link") <NEW_LIN... | add a link to the rss tree | 625941e89f2886367277ad0c |
def est_bien_par_no_pile(word): <NEW_LINE> <INDENT> value = 0 <NEW_LINE> for c in word: <NEW_LINE> <INDENT> if c == "(": <NEW_LINE> <INDENT> value += 1 <NEW_LINE> <DEDENT> elif value == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value -= 1 <NEW_LINE> <DEDENT> <DEDENT> return value... | verifie la validite d'un mot donne (par accumulateur) | 625941e8c4546d3d9de72ebb |
def compute_from_obs_fcst(self, obs, fcst, interval=None): <NEW_LINE> <INDENT> I = np.where((np.isnan(obs) | np.isnan(fcst)) == 0)[0] <NEW_LINE> obs = obs[I] <NEW_LINE> fcst = fcst[I] <NEW_LINE> if obs.shape[0] > 0: <NEW_LINE> <INDENT> return self._compute_from_obs_fcst(obs, fcst) <NEW_LINE> <DEDENT> else: <NEW_LINE> <... | Compute the score using only the observations and forecasts
obs and fcst must have the same length, but may contain nan values
Arguments:
obs (np.array): 1D array of observations
fcst (np.array): 1D array of forecasts
Returns:
float: Value of score | 625941e87cff6e4e81117e08 |
def set_up_down_bars(self, options=None): <NEW_LINE> <INDENT> if options is None: <NEW_LINE> <INDENT> options = {} <NEW_LINE> <DEDENT> up_line = None <NEW_LINE> up_fill = None <NEW_LINE> down_line = None <NEW_LINE> down_fill = None <NEW_LINE> if options.get('up'): <NEW_LINE> <INDENT> if 'border' in options['up']: <NEW_... | Set properties for the chart up-down bars.
Args:
options: A dictionary of options.
Returns:
Nothing. | 625941e85fdd1c0f98dc06b8 |
def test_insert_interposer_after_ensemble(self): <NEW_LINE> <INDENT> mock_ensemble_1 = mock.Mock(spec_set=["size_in"]) <NEW_LINE> mock_ensemble_1.size_in = 1 <NEW_LINE> e1 = EnsembleLIF(mock_ensemble_1) <NEW_LINE> mock_ensemble_2 = mock.Mock(spec_set=["size_in"]) <NEW_LINE> mock_ensemble_2.size_in = 512 <NEW_LINE> e2 =... | Test that an interposer can be inserted after a connection from an
ensemble. | 625941e8d58c6744b42580e1 |
def getMarkers(locations): <NEW_LINE> <INDENT> if len(locations) <=0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> base = "markers=" <NEW_LINE> for location in locations: <NEW_LINE> <INDENT> base += "%s"%location + "%7C" <NEW_LINE> <DEDENT> return base[:-3] | input: a list of strings in form of 'lat,lon'
output: a string of "markers=...&markers=:..." to be used
in a request to Google Static Map API | 625941e81f037a2d8b94667f |
@pytest.fixture <NEW_LINE> def get_driver(request, cmdopt_browser, cmdopt_window): <NEW_LINE> <INDENT> server = Server("C:\\Program Files (x86)\\browsermob-proxy\\bin\\browsermob-proxy", {"port": 9090}) <NEW_LINE> server.start() <NEW_LINE> proxy = server.create_proxy() <NEW_LINE> url = urllib.parse.urlparse(proxy.proxy... | Fixture to create, return and close driver | 625941e891f36d47f21ac97a |
def test_Value(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError) as e: <NEW_LINE> <INDENT> msg = 'width must be > 0' <NEW_LINE> r1 = r(-12, 10) <NEW_LINE> <DEDENT> with self.assertRaises(ValueError) as e: <NEW_LINE> <INDENT> msg = 'height must be > 0' <NEW_LINE> r1 = r(12, -10) <NEW_LINE> <DEDENT> with self... | Error | 625941e866656f66f7cbc62f |
def domain_detach_contact(domain_object, role): <NEW_LINE> <INDENT> current_contact = domain_object.get_contact(role) <NEW_LINE> domain_object.set_contact(role, None) <NEW_LINE> domain_object.save() <NEW_LINE> logger.info('domain %r contact role %r disconnected, previous was : %r', domain_object.name, role, current_con... | Remove given contact with given role from that domain.
This will only remove existing relation, contact object is not removed. | 625941e8bd1bec0571d90ab1 |
def selectionChanged(self,selected, deselected): <NEW_LINE> <INDENT> for index in deselected.indexes(): <NEW_LINE> <INDENT> self.closePersistentEditor(index) <NEW_LINE> <DEDENT> super(_TutorialTree, self).selectionChanged(selected, deselected) | close change file name dialog if still open | 625941e8e5267d203edce11a |
def __rmul__(self, other): <NEW_LINE> <INDENT> return self * other | (Vector, int/float) -> Vector
Return the reverse product. See __mul__(). | 625941e838b623060ff0b270 |
def set_plain_username(self, plain_username): <NEW_LINE> <INDENT> return lib.zsock_set_plain_username(self._as_parameter_, plain_username) | Set socket option `plain_username`. | 625941e88c3a873295158843 |
def planetAndStar(how='inner'): <NEW_LINE> <INDENT> df, columns = readSC() <NEW_LINE> deu = readExoplanetEU() <NEW_LINE> cols = ['stName', 'plMass', 'plRadius', 'period', 'sma', 'eccentricity', 'inclination', 'discovered', 'dist', 'b', 'mag_v', 'mag_i', 'mag_j', 'mag_h', 'mag_k', 'plDensity'] <NEW_LINE> d = pd.merge(df... | Read the SWEET-Cat and ExoplanetEU databases and merge them.
Input
-----
how : str (default: 'inner')
How to merge the two DataFrames. See pd.merge for documentation
Output
------
d : pd.DataFrame
The DataFrame of merged DataFrame
c : list
The columns that can be used for plotting | 625941e80383005118ecfa64 |
def _is_bonded(self, atom_index_1, atom_index_2): <NEW_LINE> <INDENT> self._construct_bonded_atoms_list() <NEW_LINE> atom1 = self._atoms[atom_index_1] <NEW_LINE> atom2 = self._atoms[atom_index_2] <NEW_LINE> return atom2 in self._bondedAtoms[atom1] | Return True if atoms are bonded, False if not.
Parameters
----------
atom_index_1 : int
atom_index_2 : int
Atom indices
Returns
-------
is_bonded : bool
True if atoms are bonded, False otherwise | 625941e84d74a7450ccd4647 |
def delete_index(self, index_name): <NEW_LINE> <INDENT> pass | Remove a named index.
:param index_name: The name of the index we are removing
:type index_name: str | 625941e84d74a7450ccd4648 |
def sigmoid_forward(z): <NEW_LINE> <INDENT> return 1 / (1 + np.exp(-z)), z | Calculates the sigmoid activation function.
Arguments:
z -- Input on which sigmoid function is calculated. Scalar or numpy array of any size.
Returns:
Output of sigmoid activation on Z. | 625941e8d6c5a102081444d1 |
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return NewSamlConnection( x509certificate = '0', account_id = 56, name = '0', enabled = True, issuer = '0', sign_on_url = '0', sign_out_url = '0', metadata_url = '0', audience_uri = '0' ) <NEW_LINE> <DEDENT> else : ... | Test NewSamlConnection
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | 625941e823849d37ff7b350e |
def longestCommonPrefix(self, strs): <NEW_LINE> <INDENT> if not strs: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> for index in range(len(strs[0])): <NEW_LINE> <INDENT> for string in strs[1:]: <NEW_LINE> <INDENT> if index >= len(string) or string[index] != strs[0][index]: <NEW_LINE> <INDENT> return strs[0][:index]... | :type strs: List[str]
:rtype: str | 625941e8711fe17d825427e4 |
def get_random_k(self, x, ratio, is_biased=True): <NEW_LINE> <INDENT> x_data = x.view(-1) <NEW_LINE> x_len = x_data.nelement() <NEW_LINE> top_k = max(1, int(x_len * (1 - ratio))) <NEW_LINE> selected_indices = np.random.choice(x_len, top_k, replace=False) <NEW_LINE> selected_indices = torch.LongTensor(selected_indices).... | it will randomly sample the 1-ratio of the samples. | 625941e860cbc95b062c69c6 |
def get_processor(aid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> path = get_achievement(aid=aid, show_disabled=True)["processor"] <NEW_LINE> return imp.load_source(path[:-3], join(processor_base_path, path)) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> raise InternalException("Achievement proce... | Returns the processor module for a given achievement.
Args:
aid: the achievement id
Returns:
The processor module | 625941e87b180e01f3dc4c77 |
def add_months(sourcedate, months): <NEW_LINE> <INDENT> month = sourcedate.month - 1 + months <NEW_LINE> year = int(sourcedate.year + month / 12) <NEW_LINE> month = month % 12 + 1 <NEW_LINE> day = min(sourcedate.day, calendar.monthrange(year, month)[1]) <NEW_LINE> return datetime.date(year, month, day) | Adds specified number of month to current date | 625941e88da39b475bd653fc |
def handle_event(self, e): <NEW_LINE> <INDENT> key_event = event.simplify_key_event(e) <NEW_LINE> if key_event: <NEW_LINE> <INDENT> self.handle(*key_event) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False | :return: True if event has been processed and hence consumed, otherwise False | 625941e866673b3332b92514 |
def test_delete_servicechain_spec(self): <NEW_LINE> <INDENT> resource = 'servicechain_spec' <NEW_LINE> cmd = servicechain.DeleteServiceChainSpec(test_cli20.MyApp(sys.stdout), None) <NEW_LINE> my_id = 'my-id' <NEW_LINE> args = [my_id] <NEW_LINE> self._test_delete_resource(resource, cmd, my_id, args) | service-chain-spec-delete my-id. | 625941e8b57a9660fec33d0d |
def transform_onto_tags(lst): <NEW_LINE> <INDENT> tags = ["O"] * len(lst) <NEW_LINE> flag = False <NEW_LINE> cur = "O" <NEW_LINE> for i in range(len(lst)): <NEW_LINE> <INDENT> if lst[i][0] == "(" and not flag: <NEW_LINE> <INDENT> cur = lst[i].replace("(", "").replace(")", "").replace("*", "") <NEW_LINE> tags[i] = "B-" ... | Convert bracketed tokens of an OntoNotes file (CoNLL-2012 dataset)
to a list of BIO-2 labels. | 625941e821bff66bcd684dd1 |
@pedsnetdcc.command() <NEW_LINE> @click.option('--pwprompt', '-p', is_flag=True, default=False, help='Prompt for database password.') <NEW_LINE> @click.option('--searchpath', '-s', help='Schema search path in database.') <NEW_LINE> @click.option('--site', required=True, help='PEDSnet site name for the config file.') <N... | Run R Script.
The steps are:
- Create the Argos file.
- Run the script.
The database should be specified using a DBURI:
postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&..] | 625941e850812a4eaa59c7a0 |
def __lt__(self, other): <NEW_LINE> <INDENT> firstStatus = self.getUserRank(self) <NEW_LINE> secondStatus = self.getUserRank(other) <NEW_LINE> if firstStatus != secondStatus: <NEW_LINE> <INDENT> return firstStatus < secondStatus <NEW_LINE> <DEDENT> if self.api.isMe(self.name): return True <NEW_LINE> if self.api.isMe(ot... | Comparison operator used for item list sorting | 625941e8e64d504609d74cc3 |
def __init__(self, *args): <NEW_LINE> <INDENT> this = _AriaPy.new_ArGPSConnector(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this | __init__(self, ArArgumentParser argParser) -> ArGPSConnector | 625941e8de87d2750b86021a |
def test_analog_in_out_loop(self): <NEW_LINE> <INDENT> for v in range(0, 6, 1): <NEW_LINE> <INDENT> self.l.output(ao0=v, ao1=v) <NEW_LINE> r = self.l.input(channels=(8,8,9,9), gains=(1,4,1,4))[0] <NEW_LINE> for i in r: <NEW_LINE> <INDENT> self.failUnless(abs(v-i) < .1, "measured %g for %g" % (i, v)) | requires ao0 to be connected with ai0, ai1
and ao1 with ai2, ai3 | 625941e899fddb7c1c9de812 |
def _process_note_message(self, status, current_velocity, swapped_note_message, current_pedal, current_note): <NEW_LINE> <INDENT> note_messages = self._set_note_velocity(current_pedal, status, current_velocity, swapped_note_message) <NEW_LINE> messages = [] <NEW_LINE> midi_and_sysex = current_pedal.get("@MessageList") ... | Proceses the note messages for the current pedal
Parameters:
* status: current MIDI status; either NOTE ON or NOTE OFF
* current_velocity: current velocity of the catched note
* swapped_note_message: inidicated if this was a NOTE ON message with a
velocity of zero, which was changed to NOTE OFF. On this case, the
v... | 625941e8099cdd3c635f10dc |
def get_cost_updates(self, corruption_level, learning_rate): <NEW_LINE> <INDENT> tilde_x =self.get_corrupted_input(self.x, corruption_level) <NEW_LINE> y = self.get_hidden_values(tilde_x) <NEW_LINE> z = self.get_reconstructed_input(y) <NEW_LINE> L = - T.sum(self.x * T.log(z) + (1 - self.x) * T.log(1-z), axis=1) <NEW_LI... | This function computes the cost and the updates for one training
step of the dA | 625941e80a366e3fb873eca2 |
def test_change_mode_from_cna_to_fc(self): <NEW_LINE> <INDENT> module_args = {} <NEW_LINE> module_args.update(self.set_default_args()) <NEW_LINE> set_module_args(module_args) <NEW_LINE> with pytest.raises(AnsibleExitJson) as exc: <NEW_LINE> <INDENT> self.get_ucadapter_mock_object().apply() <NEW_LINE> <DEDENT> assert no... | configuring ucadaptor and checking idempotency | 625941e8cb5e8a47e48b7f26 |
def drawContents(self, painter): <NEW_LINE> <INDENT> r = self.textRect() <NEW_LINE> if r.isEmpty(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> painter.setFont(self.font()) <NEW_LINE> painter.setPen(self.palette().color(QPalette.Active, QPalette.Text)) <NEW_LINE> self.drawText(painter, QRectF(r)) <NEW_LINE> if self.... | Redraw the text and focus indicator
:param QPainter painter: Painter | 625941e85fcc89381b1e1b45 |
def _class_weights_map_fn(*data): <NEW_LINE> <INDENT> x, y, sw = unpack_x_y_sample_weight(data) <NEW_LINE> if nest.is_nested(y): <NEW_LINE> <INDENT> raise ValueError( "`class_weight` is only supported for Models with a single output.") <NEW_LINE> <DEDENT> if y.shape.rank > 2: <NEW_LINE> <INDENT> raise ValueError("`clas... | Convert `class_weight` to `sample_weight`. | 625941e829b78933be1e5b29 |
def ocupou(self, ocupante): <NEW_LINE> <INDENT> self.vazio.ocupa(ocupante) <NEW_LINE> self.ocupante = ocupante <NEW_LINE> self.acessa = self._valida_acessa <NEW_LINE> self.sair = self._pede_sair | O candidato à vaga decidiu ocupá-la e efetivamente entra neste espaço.
:param ocupante: O canditato a ocupar a posição corrente.
Este ocupante vai entrar no elemento do Vitollino e definitivamente se tornar
o ocupante da vaga. Com isso ele troca o estado do método acessa para primeiro
consultar a si mesmo, o ocupante c... | 625941e82c8b7c6e89b35c40 |
def strtodict(string: str, delim=',', eq="="): <NEW_LINE> <INDENT> d = {} <NEW_LINE> string = string .replace("{", '') .replace("}", '') <NEW_LINE> ents = string.split(delim) <NEW_LINE> for entity in ents: <NEW_LINE> <INDENT> key, val = entity.split(eq) <NEW_LINE> d[key] = val <NEW_LINE> <DEDENT> return d | :param string:
:return:
Example:
strtodict("potato=good,tomato=yuck") -> {"potato": "good", "tomato": "yuck"} | 625941e8eab8aa0e5d26dfdd |
def _ensime_test(self, specs, project_dir=os.path.join('.pants.d', 'tmp-ensime', 'project'), project_name='project'): <NEW_LINE> <INDENT> if not os.path.exists(project_dir): <NEW_LINE> <INDENT> os.makedirs(project_dir) <NEW_LINE> <DEDENT> with temporary_dir(root_dir=project_dir) as path: <NEW_LINE> <INDENT> pants_run =... | Helper method that tests ensime generation on the input spec list. | 625941e8091ae356686673da |
def patch_positions_list(self, position, view): <NEW_LINE> <INDENT> the_slice = self.patch_positions_slice(position, view) <NEW_LINE> size = the_slice.shape[0] * the_slice.shape[1] <NEW_LINE> return the_slice.reshape((size * 4, 3)) | Returns patch positions as a list for use in Camera etc. | 625941e8e76e3b2f99f3ac88 |
def get_pending_vgroup(module, array): <NEW_LINE> <INDENT> vgroup = None <NEW_LINE> for vgrp in array.list_vgroups(pending=True): <NEW_LINE> <INDENT> if vgrp["name"] == module.params['vgroup'] and vgrp['time_remaining']: <NEW_LINE> <INDENT> vgroup = vgrp <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return vgroup | Get Deleted Volume Group | 625941e84e696a04525c98d1 |
@pytest.fixture <NEW_LINE> def os_name(): <NEW_LINE> <INDENT> return pytest.config.getoption("-P") | pytest fixture for os_name | 625941e81d351010ab855f9e |
def skip_lines(N,f): <NEW_LINE> <INDENT> for n in range(N): <NEW_LINE> <INDENT> next(f) | Simple. | 625941e88e7ae83300e4b452 |
@blueprint.route('/logout', methods=['GET']) <NEW_LINE> @login_required <NEW_LINE> def logout(): <NEW_LINE> <INDENT> logout_user() <NEW_LINE> return redirect(url_for('dashboard.login')) | Logout view
Will redirect to login view after logout current user | 625941e8de87d2750b86021b |
def _organize_files(self, directory, dir_fmt, file_fmt): <NEW_LINE> <INDENT> next_files = list() <NEW_LINE> arg_list = ([self.name] + [str(i) if i is not None else '' for i in self.exp]) <NEW_LINE> d = path.join(directory, dir_fmt.format(*arg_list)) <NEW_LINE> if not path.exists(d): <NEW_LINE> <INDENT> mkdir(d) <NEW_LI... | Give the files standardized names and put them in a similarly-named
directory
:param dir_fmt: the string template for the directory name, should
allow for the same number of arguments as the length of self.exp
:param file_fmt: the string template for the file name. This should
allow for the same number of arguments as ... | 625941e86e29344779a62a93 |
def handle(client_message, handle_event_partitionlost = None, to_object=None): <NEW_LINE> <INDENT> message_type = client_message.get_message_type() <NEW_LINE> if message_type == EVENT_PARTITIONLOST and handle_event_partitionlost is not None: <NEW_LINE> <INDENT> partition_id = client_message.read_int() <NEW_LINE> lost_b... | Event handler | 625941e8baa26c4b54cb159e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.