code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def cleanup_private_network(self): <NEW_LINE> <INDENT> if self.netdst: <NEW_LINE> <INDENT> LOG_JOB.info("Clear private bridge after test") <NEW_LINE> self.netdst.cleanup() <NEW_LINE> <DEDENT> return None | cleanup private network in the end of test; | 625941c6b5575c28eb68e020 |
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not isinstance(self._meta.get_field('pictures'), models.ManyToManyField) or self.pk is not None: <NEW_LINE> <INDENT> self.pictured = bool(self.has_pictures()) or (hasattr(self, 'picture') and self.picture is not None and self.picture.moderated is True) <NEW_LINE> ... | Enregistrer l'objet dans la base de données | 625941c6b545ff76a8913e37 |
def inception_v4(inputs, num_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionV4', create_aux_logits=True): <NEW_LINE> <INDENT> end_points = {} <NEW_LINE> with tf.variable_scope(scope, 'InceptionV4', [inputs], reuse=reuse) as scope: <NEW_LINE> <INDENT> with slim.arg_scope([slim.batch_n... | Creates the Inception V4 model.
Args:
inputs: a 4-D tensor of size [batch_size, height, width, 3].
num_classes: number of predicted classes.
is_training: whether is training or not.
dropout_keep_prob: float, the fraction to keep before final layer.
reuse: whether or not the network and its variables should be... | 625941c6004d5f362079a354 |
def spawn(cls, executable, args, path, env, spawnProcess=None): <NEW_LINE> <INDENT> d = defer.Deferred() <NEW_LINE> proto = cls(d, filepath.FilePath(path)) <NEW_LINE> if spawnProcess is None: <NEW_LINE> <INDENT> spawnProcess = reactor.spawnProcess <NEW_LINE> <DEDENT> spawnProcess( proto, executable, [executable] + args... | Run an executable with some arguments in the given working directory with
the given environment variables.
Returns a Deferred which fires with a two-tuple of (exit status, output
list) if the process terminates without timing out or being killed by a
signal. Otherwise, the Deferred errbacks with either L{error.Timeou... | 625941c624f1403a92600b88 |
def latest_email_date(self): <NEW_LINE> <INDENT> if not self.latest_email_out_date and not self.latest_email_in_date: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif not self.latest_email_out_date: <NEW_LINE> <INDENT> return self.latest_email_in_date <NEW_LINE> <DEDENT> elif not self.latest_email_in_date: <NEW... | Returns more recent of latest_email_out/in_date, or None if neither exists | 625941c63617ad0b5ed67f18 |
def returns(self, arguments): <NEW_LINE> <INDENT> self._obj.set_return(self._obj.curframe) <NEW_LINE> raise exceptions.CommandExit() | Continue execution until the current function returns. | 625941c63617ad0b5ed67f19 |
def test_download_file_with_format(self): <NEW_LINE> <INDENT> result=self.api.download_file_with_format("FileUpload.vdx","pdf",folder = storageTestFOLDER) <NEW_LINE> self.assertIsNotNone(result) <NEW_LINE> pass | Test case for download_file_with_format
Exports the document into the specified format. | 625941c65f7d997b87174ab7 |
def generate_real_time(self): <NEW_LINE> <INDENT> pattern = 'id' <NEW_LINE> if self.has_attr: <NEW_LINE> <INDENT> for key, _ in self.attr.items(): <NEW_LINE> <INDENT> pattern += ' %s' % key <NEW_LINE> <DEDENT> <DEDENT> yield pattern <NEW_LINE> for i in range(self.amount): <NEW_LINE> <INDENT> record = self.get_record(i)... | store a node real time
:return: None | 625941c61b99ca400220aad2 |
def handle_exception(self, exception, event=None): <NEW_LINE> <INDENT> callback = partial( App.get_running_app().handle_exception, exception[0], exc_info=exception[1], event=event, obj=self) <NEW_LINE> Clock.schedule_once(lambda *largs: callback()) | The overwritten method called by the devices when they encounter
an exception. | 625941c6fbf16365ca6f61e2 |
def print(self): <NEW_LINE> <INDENT> if len(self.description) > 0: <NEW_LINE> <INDENT> print("%s by %s: %s" % (self.course, self.author, self.description)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("%s by %s" % (self.course, self.author)) | Prints a textual representation of the course, including
name, author, and description, if available. | 625941c6b7558d58953c4f37 |
def completed(self): <NEW_LINE> <INDENT> if not self.has_opened(): <NEW_LINE> <INDENT> return len(self.bids) == 4 <NEW_LINE> <DEDENT> elif len(self.bids) < 4: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return all((b == "P" for b in self.bids[-3:])) | The auction is completed if all 4 players initiall pass,
or there are 3 consecutive passes following an opening bid. | 625941c694891a1f4081bac9 |
def find_longest_txts(db_file): <NEW_LINE> <INDENT> db = gffutils.FeatureDB(db_file) <NEW_LINE> longest_txts = set() <NEW_LINE> genes = db.features_of_type('gene') <NEW_LINE> for g in genes: <NEW_LINE> <INDENT> txts = db.children(g, featuretype = 'transcript') <NEW_LINE> l = [] <NEW_LINE> for t in txts: <NEW_LINE> <IND... | return a set of the longest transcripts for each gene | 625941c615fb5d323cde0b2e |
def get_monster_start(self): <NEW_LINE> <INDENT> sx = random.randrange(wizards.constants.WIDTH) <NEW_LINE> sy = random.randrange(wizards.constants.HEIGHT) <NEW_LINE> while self.collision_map[sy][sx] == 1: <NEW_LINE> <INDENT> sx = random.randrange(wizards.constants.WIDTH) <NEW_LINE> sy = random.randrange(wizards.constan... | Creates a start position for the monster | 625941c64e696a04525c946c |
def get_page_error(self): <NEW_LINE> <INDENT> logger.info('Get error message displayed under page title') <NEW_LINE> return self.wait_UI(self.__page_error_loc).text | Get the page error hint value
:return: string, error message | 625941c6377c676e912721ca |
def check_compilers_remote(self): <NEW_LINE> <INDENT> log.info("Checking the presence of C++ and MPI compilers ...") <NEW_LINE> cpp_path = self.modules.paths["cpp"] <NEW_LINE> cpp_version = self.modules.versions["cpp"] <NEW_LINE> cpp_module = self.modules.names["cpp"] <NEW_LINE> if cpp_module is not None: <NEW_LINE> <I... | This function ...
:return: | 625941c6097d151d1a222e7c |
def acquire_source(self, reuse_archive=True): <NEW_LINE> <INDENT> if not self.src: <NEW_LINE> <INDENT> raise ConfigurationError("No source code provided for %s" % self.title) <NEW_LINE> <DEDENT> if self.unmanaged: <NEW_LINE> <INDENT> return str(self.src) <NEW_LINE> <DEDENT> while self.src: <NEW_LINE> <INDENT> try: <NEW... | Acquires package source code archive file via download or file copy.
If the package is configured to use an existing installation as the source then
this routine does nothing.
Args:
reuse_archive (bool): If True don't download, just confirm that the archive exists.
Returns:
str: Absolute path to the source a... | 625941c62ae34c7f2600d152 |
def delete(self, accid, eventType, publisherAccids): <NEW_LINE> <INDENT> url = "https://api.netease.im/nimserver/event/subscribe/delete.action" <NEW_LINE> data = {'accid': accid, 'eventType': eventType, 'publisherAccids': publisherAccids} <NEW_LINE> resp = requests.post(url=url, headers=self.get_header(), data=data) <N... | 取消在线状态事件订阅
:param accid:
:param eventType:
:param publisherAccids:
:return: | 625941c6009cb60464c633d3 |
def visualize(self, time, pred, true): <NEW_LINE> <INDENT> plt.plot(time, true, label='Actual') <NEW_LINE> plt.plot(time, pred, label='Predicted') <NEW_LINE> plt.xlabel('Time') <NEW_LINE> plt.ylabel('Price ($)') <NEW_LINE> plt.legend(bbox_to_anchor=(0.1, 1), loc=2, borderaxespad=0., prop={'size': 14}) <NEW_LINE> plt.sh... | Plots predicted and true values.
| 625941c6046cf37aa974cd6a |
def drop_into_layer(image_obj, layer_index): <NEW_LINE> <INDENT> rootfs.set_up() <NEW_LINE> if layer_index == 0: <NEW_LINE> <INDENT> target = rootfs.mount_base_layer( image_obj.layers[layer_index].tar_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> target = multi_layer.mount_overlay_fs(image_obj, layer_index) <NEW_... | Given the image object and the layer index, mount all the layers
upto the specified layer index and drop into a shell session | 625941c663d6d428bbe44510 |
def SetPopupTextColour(self, colour=None): <NEW_LINE> <INDENT> if colour is None: <NEW_LINE> <INDENT> colour = wx.BLACK <NEW_LINE> <DEDENT> self._foregroundcolour = colour | Sets the L{ToasterBox} foreground colour.
:param `colour`: a valid `wx.Colour` object. If defaulted to ``None``, then
the background colour will be black.
:note: Use this method only for a L{ToasterBox} created with the ``TB_SIMPLE`` style. | 625941c616aa5153ce362499 |
def uid(self, metadata): <NEW_LINE> <INDENT> return '_'.join(str(metadata[key]) for key in self._message_keys) | Get a unique id for the message. | 625941c632920d7e50b281f0 |
def get_name(self): <NEW_LINE> <INDENT> return self._intercepter.get_name(_next) | Gets the command name.
Results: the command name | 625941c6d10714528d5ffd02 |
def display(self, amount, show_contents=True): <NEW_LINE> <INDENT> if self.continuous == True: <NEW_LINE> <INDENT> return "{} {}".format(format(amount, '.3f'), self.abbr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not self.contents == '' and show_contents == True: <NEW_LINE> <INDENT> cont = " per {}".format(self.... | Returns a string consisting of an amount, the unit (prn plural) and the contents of the unit (can be deactivated)
The string may be used in batch/consumable information (stock, average etc) and as transaction description.
Examples: "2 bottles per 500 ml"; "1 package per 200 g"; "1.390 kg" | 625941c6462c4b4f79d1d6f1 |
def to_notebook(self, d, **kwargs): <NEW_LINE> <INDENT> return from_dict(d) | Convert from a raw JSON dict to a nested NotebookNode structure. | 625941c656b00c62f0f14679 |
def generate_letter_to_target_number_dict(): <NEW_LINE> <INDENT> values = {} <NEW_LINE> for index, letter in enumerate(string.ascii_lowercase, 1): <NEW_LINE> <INDENT> values[letter] = index <NEW_LINE> <DEDENT> return values | makes dict of letter:number comparisons
>>> a = {'g': 7, 'i': 9, 'v': 22, 'x': 24, 'b': 2, 'd': 4, 't': 20, 'y': 25, 's': 19, 'e': 5, 'a': 1, 'w': 23,
... 'q': 17, 'm': 13, 'l': 12, 'o': 15, 'h': 8, 'r': 18, 'f': 6, 'p': 16, 'n': 14, 'u': 21, 'k': 11, 'j': 10,
... 'z': 26, 'c': 3}
>>> a == generate_letter_to_target_nu... | 625941c6090684286d50ed05 |
def test_update_wrong_template_version(self): <NEW_LINE> <INDENT> hs = heat_stack.HeatStack(self.mock_murano_obj, None, None, None) <NEW_LINE> hs._name = 'test-stack' <NEW_LINE> hs._template = {'resources': {'test': 1}} <NEW_LINE> hs.type.properties = {} <NEW_LINE> erroring_template = { 'heat_template_version': 'someth... | Template version other than expected should cause error | 625941c6d18da76e235324f6 |
def _estimate_gaussian_precisions_cholesky_tied(resp, X, nk, means, reg_covar): <NEW_LINE> <INDENT> n_samples, n_features = X.shape <NEW_LINE> avg_X2 = np.dot(X.T, X) <NEW_LINE> avg_means2 = np.dot(nk * means.T, means) <NEW_LINE> covariances = avg_X2 - avg_means2 <NEW_LINE> covariances /= n_samples <NEW_LINE> covarianc... | Estimate the tied precision matrix.
Parameters
----------
resp : array-like, shape (n_samples, n_components)
X : array-like, shape (n_samples, n_features)
nk : array-like, shape (n_components,)
means : array-like, shape (n_components, n_features)
reg_covar : float
Returns
-------
precisions_chol : array, shape (n... | 625941c67d43ff24873a2cc1 |
@app.task <NEW_LINE> def send_active_email(to_email, user_name, token): <NEW_LINE> <INDENT> subject = "天天生鲜用户激活" <NEW_LINE> body = "" <NEW_LINE> sender = settings.EMAIL_FROM <NEW_LINE> receiver = [to_email] <NEW_LINE> html_body = '<h1>尊敬的用户 %s, 感谢您注册天天生鲜!</h1>' '<br/><p>请点击此链接激活您的帐号<a href="http://127.0.... | 封装发送邮件任务 | 625941c621a7993f00bc7d0e |
def __eq__(self, other): <NEW_LINE> <INDENT> if type(self) == type(other) and self.type == other.type and self.content == other.content and self.pick == other.pick and self.draw == other.draw: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE... | Validate object for equality
:param other: the other object to compare to
:return: True of False is the object is equal to this instance | 625941c699cbb53fe6792c08 |
def get_channel_id(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = req.urlopen(URL, None) <NEW_LINE> data = json.load(res) <NEW_LINE> channel_id = data["_id"] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> channel_id = 0 <NEW_LINE> <DEDENT> return channel_id | gets the channel ID for the streaming channel
:return: | 625941c60a366e3fb873e83a |
def __init__(self, sdata, parent=None): <NEW_LINE> <INDENT> super(AbstractPropertyItem, self).__init__(sdata, parent) <NEW_LINE> self._childrenPropertyTable = {} | Constructor.
@param sdata The initial instance of AbstractData or iterable object containing static data to be converted to an instance of AbstractData.
@param parent The initial parent AbstractDataTreeItem of this AbstractPropertyItem | 625941c63317a56b86939c7c |
def thread(self, board, t_id): <NEW_LINE> <INDENT> OP = self.posts_coll.find_one( {'board' : board, 'thread':0, 'id': t_id } ) <NEW_LINE> if not OP: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> replies = self.posts_coll.find( {'board':board, 'thread':t_id} ).sort('id',1) <NEW_LINE> OP=self.__process_data(OP) <NE... | returns a tuple with the first post(OP) and a list of replies | 625941c676e4537e8c351692 |
def generateLayer(self, nameCoverage, coverageTime, boundingBox=None): <NEW_LINE> <INDENT> url = self.generateURLForGeoTIFF(nameCoverage, coverageTime, boundingBox) <NEW_LINE> layerName = "{ct}_{nc}-{id}".format(ct=coverageTime, nc=nameCoverage, id=uuid.uuid4()) <NEW_LINE> if Utilities.is_linux(): <NEW_LINE> <INDENT> i... | Generates a raster layer for QGIS.
:param nameCoverage: the name identifier of the coverage we want to retrieve.
:type nameCoverage: str
:param coverageTime: the time dimension of the coverage we want.
:type coverageTime: str
:returns: a QGIS-compatible raster layer object for the coverage and times provided.
:rty... | 625941c630bbd722463cbde6 |
def inorderTraversal(self, root): <NEW_LINE> <INDENT> inorder = [] <NEW_LINE> self.recurse(root, inorder) <NEW_LINE> return inorder | :type root: TreeNode
:rtype: List[int] | 625941c6e8904600ed9f1f4c |
def getRow(self, rowIndex): <NEW_LINE> <INDENT> ans = [1] * (rowIndex + 1) <NEW_LINE> for i in range(2, rowIndex + 1): <NEW_LINE> <INDENT> ans[1:i] = [ans[j - 1] + ans[j] for j in range(1, i)] <NEW_LINE> <DEDENT> return ans | :type rowIndex: int
:rtype: List[int] | 625941c62eb69b55b151c8cf |
def generate_output_html(htmlfile): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(htmlfile) as f: <NEW_LINE> <INDENT> html = f.read().format(date_string) <NEW_LINE> return html <NEW_LINE> <DEDENT> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> logger.error('Exception occured while loading template {}. De... | Load HTML template and add current date, return result | 625941c65e10d32532c5ef48 |
def on_new_day(self): <NEW_LINE> <INDENT> pass | Called when game day changes. | 625941c697e22403b379cfbb |
@reg.register_legalize("nn.batch_matmul") <NEW_LINE> def legalize_batch_matmul(attrs, inputs, types): <NEW_LINE> <INDENT> return topi.nn.batch_matmul_legalize(attrs, inputs, types) | Legalize batch_matmul op.
Parameters
----------
attrs : tvm.ir.Attrs
Attributes of current convolution
inputs : list of tvm.relay.Expr
The args of the Relay expr to be legalized
types : list of types
List of input and output types
Returns
-------
result : tvm.relay.Expr
The legalized expr | 625941c65fc7496912cc399f |
def __str__(self): <NEW_LINE> <INDENT> return "Device %d" % self.device_id | Pretty prints this device.
@rtype: String
@return: a string containing the id of this device | 625941c63539df3088e2e36c |
def insert_node(self, node, target, position='last-child', save=False, allow_existing_pk=False): <NEW_LINE> <INDENT> if self._base_manager: <NEW_LINE> <INDENT> return self._base_manager.insert_node(node, target, position=position, save=save) <NEW_LINE> <DEDENT> if node.pk and not allow_existing_pk and self.filter(pk=no... | Sets up the tree state for ``node`` (which has not yet been
inserted into in the database) so it will be positioned relative
to a given ``target`` node as specified by ``position`` (when
appropriate) it is inserted, with any neccessary space already
having been made for it.
A ``target`` of ``None`` indicates that ``no... | 625941c6460517430c3941a9 |
def test_set_get_inventory_tree_reference(self): <NEW_LINE> <INDENT> tree = self.make_branch_and_tree('.') <NEW_LINE> if not isinstance(tree, inventorytree.InventoryTree): <NEW_LINE> <INDENT> raise TestNotApplicable('not an inventory tree') <NEW_LINE> <DEDENT> transform = tree.get_transform() <NEW_LINE> trans_id = tran... | This tests that setting a tree reference is persistent. | 625941c623849d37ff7b30b1 |
def register(self, func): <NEW_LINE> <INDENT> self.viewlet_func = func <NEW_LINE> self.viewlet_func_args = getargspec(func).args <NEW_LINE> if not self.name: <NEW_LINE> <INDENT> self.name = func.func_name <NEW_LINE> <DEDENT> func_argcount = len(self.viewlet_func_args) - 1 <NEW_LINE> if self.timeout: <NEW_LINE> <INDENT>... | Initial decorator wrapper that configures the viewlet instance,
adds it to the library and then returns a pointer to the call
function as the actual wrapper | 625941c666656f66f7cbc1cc |
def poly_degree(poly): <NEW_LINE> <INDENT> l = -1 <NEW_LINE> while poly: <NEW_LINE> <INDENT> poly >>= 1 <NEW_LINE> l += 1 <NEW_LINE> <DEDENT> return l | Return the degree of the polynomial | 625941c663f4b57ef000113e |
def get_esx_host_content(esx_ip, esx_user, esx_password): <NEW_LINE> <INDENT> log = logging.getLogger('vdnet') <NEW_LINE> if esx_user is None: <NEW_LINE> <INDENT> log.info("Using default username 'root' for esx") <NEW_LINE> esx_user = 'root' <NEW_LINE> <DEDENT> if esx_password is None: <NEW_LINE> <INDENT> log.info("Usi... | function to get content object of given esx host
@param esx_ip: IP of esx on which vm is running
@param esx_user: User of esx on which vm is running
@param esx_password: Password of esx on which vm is running
@return esx host content object | 625941c63c8af77a43ae37c0 |
def connect(self, address_a: str, address_b: str, bandwidth: int = 1000): <NEW_LINE> <INDENT> self.link_dict[(address_a, address_b)] = bandwidth <NEW_LINE> self.link_dict[(address_b, address_a)] = bandwidth | frames send between node address_a and node address_b are transmitted with bandwidth bandwidth
:param address_a:
:param address_b:
:param bandwidth: in MegaBit / Second == Bit / MicroSecond; default = 1000 MegaBit / Second == 1 GigaBit/Second
1 GigaBit / Second == 1000 MegaBit / Second == 1000 Bit / MicroSecond | 625941c615baa723493c3f96 |
def __start_copy_from(self, cursor: DictCursor, sql: str) -> None: <NEW_LINE> <INDENT> sql = decode_object_from_bytes_if_needed(sql) <NEW_LINE> if sql is None: <NEW_LINE> <INDENT> raise McDatabaseHandlerException("SQL is None.") <NEW_LINE> <DEDENT> if len(sql) == '': <NEW_LINE> <INDENT> raise McDatabaseHandlerException... | Start COPY FROM. | 625941c67cff6e4e811179a7 |
def get_vel_mag_rel_var(exp_data): <NEW_LINE> <INDENT> vx_data = exp_data['vx'] <NEW_LINE> vy_data = exp_data['vy'] <NEW_LINE> speed_data = np.sqrt(vx_data**2 + vy_data**2) <NEW_LINE> speed_var = np.var(speed_data, axis=1) <NEW_LINE> speed_mean = np.average(speed_data, axis=1) <NEW_LINE> speed_rel_var = speed_var / (sp... | Computes the relative variance of speed for particles averaged over time. Relative variance (X) = Var(X) / Mean(X)^2. | 625941c621bff66bcd684976 |
def filter_grade(self, first_function, second_function): <NEW_LINE> <INDENT> if StringEquality(first_function.func_md5, second_function.func_md5).ratio(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if (StringEquality(first_function.exe_md5, second_function.exe_md5).ratio() and IntegerEquality(first_function.fi... | Used for preliminary filtering of the DB. | 625941c696565a6dacc8f6ed |
def irc_REJECT_PRIVMSG(self, prefix, params): <NEW_LINE> <INDENT> target = params[0] <NEW_LINE> password = params[-1] <NEW_LINE> if self.nickname is None: <NEW_LINE> <INDENT> self.transport.loseConnection() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.svc_message("Please wait until authentication has completed to... | Send a (private) message.
Parameters: <msgtarget> <text to be sent> | 625941c67b25080760e3947b |
def get_users(self): <NEW_LINE> <INDENT> return [user[0] for user in self.session.query(self.Users.username).all()] | all user request
:return: list | 625941c691af0d3eaac9ba39 |
def comoving_distance_n(self, N): <NEW_LINE> <INDENT> H = ((1-self.sol()[999, 1])*np.exp(-3*self.n1) / (1-self.sol()[:, 1]))**(0.5) <NEW_LINE> H1 = np.exp(-self.n1)/H <NEW_LINE> tck3 = interpolate.splrep(self.n1, H1, s=0) <NEW_LINE> rs = interpolate.splint(N, 0, tck3) <NEW_LINE> return self.D_H()*rs | Line of sight comoving distance as a function of log(a)
as described in David Hogg paper
in units of Mpc | 625941c64e696a04525c946d |
def crawl_goubanjia(self): <NEW_LINE> <INDENT> for pageNo in range(1, 4): <NEW_LINE> <INDENT> start_url = 'http://www.goubanjia.com/free/gngn/index{}.shtml'.format(pageNo) <NEW_LINE> html = utils.get_page(start_url) <NEW_LINE> doc = pq(html) <NEW_LINE> tds = doc('td.ip').items() <NEW_LINE> for td in tds: <NEW_LINE> <IN... | 爬取goubanjia 国内高匿代理
由于网页结构较复杂,使用pyquery更简单快速
:return: | 625941c6d53ae8145f87a293 |
def switch_off(self): <NEW_LINE> <INDENT> if self._visible: <NEW_LINE> <INDENT> self._visible = False <NEW_LINE> turtle.up() <NEW_LINE> turtle.setpos(self._x, self._y) <NEW_LINE> turtle.down() <NEW_LINE> turtle.dot(turtle.bgcolor()) | Робить точку невидимою на екрані
| 625941c6d10714528d5ffd03 |
def get_f1(self, a): <NEW_LINE> <INDENT> b = self.get_b(a) <NEW_LINE> A = self.get_A(a) <NEW_LINE> Ax = sp.dot(A, self.xarray.T) <NEW_LINE> val = ((b[:, None] + Ax[:, :])**2).sum(0) - 1.0 <NEW_LINE> return val | Define the nth constraint function. | 625941c6ff9c53063f47c216 |
def unwind(game, displaced_ship): <NEW_LINE> <INDENT> cell = game.game_map[displaced_ship] <NEW_LINE> if DEBUG & (DEBUG_NAV): logging.info("Nav - unwinding {}".format(cell.position)) <NEW_LINE> if cell.ship is None: <NEW_LINE> <INDENT> cell.ship = displaced_ship <NEW_LINE> game.command_queue[displaced_ship.id] = displa... | Unwinds the moves starting from displaced_ship original position, would be better to consider unwinding
all ships in cardinal positions based on priority/halite
:param game
:param displaced_ship Ship that no longer has a position. Offending ship took the position.
:returns Returns the number of moves reverted | 625941c63c8af77a43ae37c1 |
def get_cashflow_data(year, quarter): <NEW_LINE> <INDENT> if ct._check_input(year, quarter) is True: <NEW_LINE> <INDENT> ct._write_head() <NEW_LINE> df = _get_cashflow_data(year, quarter, 1, pd.DataFrame()) <NEW_LINE> if df is not None: <NEW_LINE> <INDENT> df = df.drop_duplicates('code') <NEW_LINE> <DEDENT> return df | 获取现金流量数据
Parameters
--------
year:int 年度 e.g:2014
quarter:int 季度 :1、2、3、4,只能输入这4个季度
说明:由于是从网站获取的数据,需要一页页抓取,速度取决于您当前网络速度
Return
--------
DataFrame
code,代码
name,名称
cf_sales,经营现金净流量对销售收入比率
rateofreturn,资产的经营现金流量回报率
cf_nm,经营现金净流量与净利润的比率
cf_liabilities,经营现金净流量对负债比率
cashflowratio,现金流量比率 | 625941c6167d2b6e31218bb8 |
def build_members(self): <NEW_LINE> <INDENT> targets = [] <NEW_LINE> def get_value(value, attributes): <NEW_LINE> <INDENT> if attributes: <NEW_LINE> <INDENT> if hasattr(value, attributes[0]): <NEW_LINE> <INDENT> value = getattr(value, attributes[0]) <NEW_LINE> if len(attributes) > 1: <NEW_LINE> <INDENT> attributes = at... | Determine group members. | 625941c69c8ee82313fbb796 |
def get_index(config): <NEW_LINE> <INDENT> return get_path(config, "index.mustache") | Returns index page | 625941c6f9cc0f698b14061e |
def unflatten_vector(value, inner_structure, batch_shape): <NEW_LINE> <INDENT> batch_shape = util.as_shape(batch_shape) <NEW_LINE> inner_shape = util.as_shape(inner_structure) <NEW_LINE> flat_inner_shape = tf.nest.flatten(inner_shape) <NEW_LINE> assert value.shape.rank == 2 <NEW_LINE> batch_size = value.shape[0] <NEW_L... | Unflattens a batch of vectors (batch, inner_size) into a nested structure | 625941c6b830903b967e992e |
def description(self, obj): <NEW_LINE> <INDENT> return obj.description_html or _('Latest articles in category "%s"') % obj.name | Return the description of the category.
:param obj: The feed object. | 625941c638b623060ff0ae0f |
def isSelfDividing(num, debug=False): <NEW_LINE> <INDENT> n = num <NEW_LINE> if n < 0: <NEW_LINE> <INDENT> n = -n <NEW_LINE> <DEDENT> d = math.log10(n) <NEW_LINE> d = math.ceil(d) <NEW_LINE> digits = d <NEW_LINE> del d, n <NEW_LINE> if debug: <NEW_LINE> <INDENT> print('DEBUG isSelfDividing: ' '{} has {} digits'.format(... | :type n: integer
:return Boolean | 625941c6eab8aa0e5d26db7a |
def __init__(self, movie_name): <NEW_LINE> <INDENT> self.CLOUD_URL = "http://tv.myhack58.com/?jk=http://www.vipjiexi.com/yun.php?url=&url=" <NEW_LINE> self.pool = Pool() <NEW_LINE> self.FILE_SAVE = f"E:\迅雷下载\{movie_name}" <NEW_LINE> self.movie_name = movie_name <NEW_LINE> self.headers = { 'Accept': 'text/html,applicati... | 从主站获取信息,所以CLOUD_URL定死,如果有变动,直接修改此处就行 | 625941c6bd1bec0571d90651 |
def make_problem_specific_metric_fn(metric_fn, problem_idx, weights_fn): <NEW_LINE> <INDENT> def problem_metric_fn(predictions, features, feature_name='targets'): <NEW_LINE> <INDENT> labels = features.get(feature_name, None) <NEW_LINE> while len(labels.shape) < len(predictions.shape)-1: <NEW_LINE> <INDENT> labels = tf.... | Create a metric fn conditioned on problem_idx. | 625941c673bcbd0ca4b2c098 |
def update_webhook_with_http_info(self, app_id, webhook_id, webhook_update_body, **kwargs): <NEW_LINE> <INDENT> all_params = ['app_id', 'webhook_id', 'webhook_update_body'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <N... | Update the specified webhook.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_webhook_with_http_info(app... | 625941c68e7ae83300e4afee |
def replay(self, snapshot, update=False): <NEW_LINE> <INDENT> if not update: <NEW_LINE> <INDENT> self._cache = snapshot['data'] <NEW_LINE> self._expiration = snapshot['expiration'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._cache.update(snapshot['data']) <NEW_LINE> self._expiration.update(snapshot['expiration'... | Replays the output of a snapshot into this cache.
:param update: The default behaviour is to entirely override the
current data (which should be None in normal cases). If you want
to update the data, set this to True. | 625941c645492302aab5e2e4 |
def to_primitive_stream_t(t: HdlType): <NEW_LINE> <INDENT> if isinstance(t, HStruct) and len(t.fields) == 1: <NEW_LINE> <INDENT> return to_primitive_stream_t(t.fields[0].dtype) <NEW_LINE> <DEDENT> frame_len = (1, 1) <NEW_LINE> start_offsets = [0, ] <NEW_LINE> if isinstance(t, HStream): <NEW_LINE> <INDENT> e_t = t.eleme... | Convert type to a HStream of Bits
With proper frame len, offset etc. | 625941c6cc40096d61595973 |
def teamToConference( nflTeam ): <NEW_LINE> <INDENT> if( hasattr( nflTeam, 'team_name' ) ): <NEW_LINE> <INDENT> team = nflTeam.team_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> team = nflTeam <NEW_LINE> <DEDENT> for teamAbbr in TEAMS_TO_CONFERENCES: <NEW_LINE> <INDENT> if( teamAbbr[0] == team ): <NEW_LINE> <INDEN... | Receives an NFLteam object or abbreviation and returns a Conference | 625941c6a05bb46b383ec845 |
def softmax_loss_naive(W, X, y, reg): <NEW_LINE> <INDENT> loss = 0.0 <NEW_LINE> dW = np.zeros_like(W) <NEW_LINE> num_train = X.shape[0] <NEW_LINE> num_classes = W.shape[1] <NEW_LINE> pred = np.dot(X, W) <NEW_LINE> for i in range(num_train): <NEW_LINE> <INDENT> f = pred[i] <NEW_LINE> f -= np.max(f) <NEW_LINE> p = np.exp... | Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) contain... | 625941c63d592f4c4ed1d093 |
def parse_h5xml(self): <NEW_LINE> <INDENT> for line in self.h5xml_file.readlines(): <NEW_LINE> <INDENT> if line.startswith(' '*8+'<size>'): <NEW_LINE> <INDENT> values = line.strip(' <size>/\n').split() <NEW_LINE> self.settings['width'] = int(values[0]) <NEW_LINE> self.settings['height'] = int(values[1]) <NEW_LINE> self... | Parse H5/XML file line by line and extract image and scan data. | 625941c6507cdc57c6306cfa |
@array <NEW_LINE> def calc_relative_errors(detections, annotations, matches=None): <NEW_LINE> <INDENT> if len(detections) == 0: <NEW_LINE> <INDENT> return np.zeros(0, dtype=float) <NEW_LINE> <DEDENT> if len(annotations) < 2: <NEW_LINE> <INDENT> raise BeatIntervalError <NEW_LINE> <DEDENT> if matches is None: <NEW_LINE> ... | Errors of the detections relative to the closest annotated interval.
Parameters
----------
detections : list or numpy array
Detected beats.
annotations : list or numpy array
Annotated beats.
matches : list or numpy array
Indices of the closest beats.
Returns
-------
numpy array
Errors relative to the ... | 625941c65fcc89381b1e16e0 |
def create_beverage(json_beverage): <NEW_LINE> <INDENT> beverage = Beverage(is_active=False) <NEW_LINE> for field in ['name', 'brewery', 'type', 'style', 'abv', 'year', 'description', 'availability', 'price', 'volume', 'volume_units', 'scraped_value']: <NEW_LINE> <INDENT> if field in json_beverage: <NEW_LINE> <INDENT> ... | :param json_beverage:
:type json_beverage: dict
:return:
:rtype: Beverage | 625941c63346ee7daa2b2d8c |
def _get_test_time(test_case_lines): <NEW_LINE> <INDENT> time_line_idx = _find_line( test_case_lines, '[Elapsed time to compile and execute all versions of "') <NEW_LINE> if time_line_idx == -1: <NEW_LINE> <INDENT> msg = 'Could not find elapsed time line in: {0}'.format( test_case_lines) <NEW_LINE> logging.warn(msg) <N... | Return the total compile and execution time in seconds for single test
case. Finds the "[Elapsed time to compile and execute all versions of ..." line
and extracts the time from it.
:type test_case_lines: list
:arg test_case_lines: lines for a single test case from start_test logfile
:rtype: float
:returns: time to r... | 625941c6a219f33f3462898d |
def set_value(self, vm_jid, variable): <NEW_LINE> <INDENT> self.__send__(self.set_value_packet(vm_jid, variable)) | Use the Linked Process <manage_bindings/> to set a variable's value. 'variable' must be a dictionary. You can set multiple variables at once. | 625941c6498bea3a759b9ad1 |
def _decrement_counters(self, msg): <NEW_LINE> <INDENT> pass | Decrement counters for roomba we should have seen | 625941c61b99ca400220aad3 |
def getDisp(self,img_d=None): <NEW_LINE> <INDENT> self.debug(3,"Calling main routine") <NEW_LINE> self.mul = 3 <NEW_LINE> if not self.__ready: <NEW_LINE> <INDENT> self.debug(2,"Wasn't ready ! Preparing...") <NEW_LINE> self.prepare() <NEW_LINE> <DEDENT> if img_d is not None: <NEW_LINE> <INDENT> self.setImage(img_d) <NEW... | The method that actually computes the weight of the fields. | 625941c6d58c6744b4257c82 |
def iter_lineage(self): <NEW_LINE> <INDENT> node = self <NEW_LINE> while node.parent: <NEW_LINE> <INDENT> yield node.parent <NEW_LINE> node = node.parent | An iterator over a node's ancestors | 625941c623849d37ff7b30b2 |
def test_module_manage(self): <NEW_LINE> <INDENT> self.assertIn("模块测试", self.driver.page_source) <NEW_LINE> self.assertIn("模块的描述", self.driver.page_source) | 模块管理测试 | 625941c6e64d504609d74862 |
def replace(self): <NEW_LINE> <INDENT> status_search = IDE.get_service("status_search") <NEW_LINE> s = 0 if not status_search.sensitive_checked else QTextDocument.FindCaseSensitively <NEW_LINE> w = 0 if not status_search.wholeword_checked else QTextDocument.FindWholeWords <NEW_LINE> flags = 0 + s ... | Replace one occurrence of the word. | 625941c6be383301e01b54ab |
def _load_episodes(self, sub): <NEW_LINE> <INDENT> name = sub.name <NEW_LINE> data = self._load_episode_index(name) <NEW_LINE> return [ Episode.from_dict(sub, sub.supported_content, d) for d in data ] | Load all episodes for the given subscription. | 625941c60fa83653e4656fde |
def resume(self): <NEW_LINE> <INDENT> pass | Resume this synchronization. | 625941c657b8e32f524834bc |
def commit_and_tag(opts, *files): <NEW_LINE> <INDENT> do_push = not opts.no_remote <NEW_LINE> commit_files_optional_push( opts.repo, "git cirrus package init", do_push, *files ) <NEW_LINE> tags = get_tags(opts.repo) <NEW_LINE> if opts.version not in tags: <NEW_LINE> <INDENT> msg = ( "tag {} not found, tagging {}..." ).... | add files, commit changes and verify that initial tag
exists | 625941c6f8510a7c17cf971e |
def __init__(self, version, response, solution): <NEW_LINE> <INDENT> super(UserChannelPage, self).__init__(version, response) <NEW_LINE> self._solution = solution | Initialize the UserChannelPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param service_sid: The service_sid
:param user_sid: The sid
:returns: twilio_code.rest.ip_messaging.v1.service.user.user_channel.UserChannelPage
:rtype: twilio.rest.ip_messaging.v... | 625941c6be7bc26dc91cd624 |
def __init__(self, server_manager: ServerManager): <NEW_LINE> <INDENT> def query_handler(client_id, data): <NEW_LINE> <INDENT> return self._query_handler(client_id, data) <NEW_LINE> <DEDENT> server = server_manager.server <NEW_LINE> server.set_query_handler(4, query_handler) <NEW_LINE> self.listeners = set() <NEW_LINE>... | Creates waiting room manager.
:param server_manager: ServerManager using this class
:return: | 625941c6627d3e7fe0d68e71 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, CreatePlacementGroupRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941c630dc7b766590198a |
def __call__(self, img, target): <NEW_LINE> <INDENT> if self.padding > 0: <NEW_LINE> <INDENT> img = ImageOps.expand(img, border=self.padding, fill=0) <NEW_LINE> <DEDENT> w, h = img.size <NEW_LINE> th, tw = self.size <NEW_LINE> if w == tw and h == th: <NEW_LINE> <INDENT> return img, target <NEW_LINE> <DEDENT> x1 = rando... | Args:
img (PIL.Image): Image to be cropped.
Returns:
PIL.Image: Cropped image. | 625941c63617ad0b5ed67f1a |
def creat_Customer(conf): <NEW_LINE> <INDENT> post.request(interfaceURL.add_customer, conf=conf) | 创建客户
:return: Customer_ID | 625941c68e05c05ec3eea396 |
def test_index_view_basic(self): <NEW_LINE> <INDENT> request = self.factory.get('/') <NEW_LINE> with self.assertTemplateUsed('solos/index.html'): <NEW_LINE> <INDENT> response = index(request) <NEW_LINE> self.assertEqual(response.status_code, 200) | Test that index view returns a 200 response and uses
correct template | 625941c610dbd63aa1bd2bc6 |
def __init__(self, datasets=None): <NEW_LINE> <INDENT> self._circles = None <NEW_LINE> self._collections = None <NEW_LINE> self._dataset_name_index = None <NEW_LINE> self.registry = {} <NEW_LINE> self.registry_id = {} <NEW_LINE> self.datasets = [] <NEW_LINE> if datasets: <NEW_LINE> <INDENT> self.add_datasets(datasets) | User-convenient access to dataset search results
Parameters
----------
datasets: list
List of CKAN package dictionaries | 625941c6851cf427c661a533 |
def pc_input_buffers_full_avg(self, *args): <NEW_LINE> <INDENT> return _blocks_swig0.message_burst_source_sptr_pc_input_buffers_full_avg(self, *args) | pc_input_buffers_full_avg(message_burst_source_sptr self, int which) -> float
pc_input_buffers_full_avg(message_burst_source_sptr self) -> pmt_vector_float | 625941c6cad5886f8bd26ffc |
def ajouter_obstacle(self, coordonnees, obstacle): <NEW_LINE> <INDENT> coordonnees = self.convertir_coordonnees(coordonnees) <NEW_LINE> if coordonnees in self.points.keys(): <NEW_LINE> <INDENT> raise ValueError( "un point de coordonnées {} existe déjà".format( coordonnees)) <NEW_LINE> <DEDENT> self.obstacles[coordonnee... | Ajoute l'obstacle. | 625941c694891a1f4081bacb |
def find_target_indra(self, stmts): <NEW_LINE> <INDENT> objs = set() <NEW_LINE> for stmt in stmts: <NEW_LINE> <INDENT> obj = stmt.obj <NEW_LINE> if obj is not None: <NEW_LINE> <INDENT> objs.add(obj.name) <NEW_LINE> <DEDENT> <DEDENT> genes = objs.intersection(hgnc_genes_set) <NEW_LINE> return genes | stmts: indra statements
return the list of genes from the object of the stmts | 625941c615fb5d323cde0b30 |
def MakeChart(self, metric, seed, mu, sigma, n, keys=None): <NEW_LINE> <INDENT> chart_name, trace_name = metric <NEW_LINE> random.seed(seed) <NEW_LINE> values = [random.gauss(mu, sigma) for _ in range(n)] <NEW_LINE> charts = { 'charts': { chart_name: { trace_name: { 'type': 'list_of_scalar_values', 'values': values} } ... | Creates a normally distributed pseudo-random sample. (continuous).
This function creates a deterministic pseudo-random sample and stores it in
chartjson format to facilitate the testing of the sample comparison logic.
Args:
metric (str pair): name of chart, name of the trace.
seed (hashable obj): to make the sequ... | 625941c6b7558d58953c4f39 |
def build_preprocessor(self): <NEW_LINE> <INDENT> noop = lambda x: x <NEW_LINE> if not self.strip_accents: <NEW_LINE> <INDENT> strip_accents = noop <NEW_LINE> <DEDENT> elif hasattr(self.strip_accents, '__call__'): <NEW_LINE> <INDENT> strip_accents = self.strip_accents <NEW_LINE> <DEDENT> elif self.strip_accents == 'asc... | Return a function to preprocess the text before tokenization | 625941c64f88993c3716c08b |
def user_has_view_permissions(function): <NEW_LINE> <INDENT> @wraps(function) <NEW_LINE> def wrap(request, *args, **kwargs): <NEW_LINE> <INDENT> print(request) <NEW_LINE> if hasattr(request, "user"): <NEW_LINE> <INDENT> if any( request.user.groups.filter(permissions__group__name__exact=group) for group in ALLOWED_GROUP... | example code for group-based access control for the REST API calls. | 625941c6046cf37aa974cd6b |
def setup(viewtype="CLIView"): <NEW_LINE> <INDENT> global view <NEW_LINE> if not isdir(user_path): <NEW_LINE> <INDENT> mkdir(user_path) <NEW_LINE> if not isdir(user_path): <NEW_LINE> <INDENT> raise OSError("Could not create the user_path directory") <NEW_LINE> <DEDENT> <DEDENT> view = ViewFactory().make_view(viewtype) | Code that should only run once when the program is launched.
Check the raspberry pi connections.
Check that the relevant libraries have been installed.
Check that the user_path 'user' folder exists | 625941c6009cb60464c633d5 |
def calculate_advantage(self, returns, observations): <NEW_LINE> <INDENT> if self.config.use_baseline: <NEW_LINE> <INDENT> advantages = self.baseline_network.calculate_advantage(returns, observations) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> advantages = returns <NEW_LINE> <DEDENT> if self.config.normalize_advanta... | Calculates the advantage for each of the observations
Args:
returns: the returns
observations: the observations
Returns:
advantage: the advantage | 625941c6796e427e537b05e7 |
def get_profile_for_user(user): <NEW_LINE> <INDENT> if not hasattr(user, '_mezzanine_profile'): <NEW_LINE> <INDENT> profile_model = get_profile_model() <NEW_LINE> profile_manager = profile_model._default_manager.using(user._state.db) <NEW_LINE> user_field = get_profile_user_fieldname(profile_model, user.__class__) <NEW... | Returns site-specific profile for this user. Raises
``ProfileNotConfigured`` if ``settings.AUTH_PROFILE_MODULE`` is not
set, and ``ImproperlyConfigured`` if the corresponding model can't
be found. | 625941c666673b3332b920b3 |
def commit(self): <NEW_LINE> <INDENT> sdf = self.get_sdf() <NEW_LINE> if ': null' in sdf: <NEW_LINE> <INDENT> boto.log.error('null value in sdf detected. This will probably ' 'raise 500 error.') <NEW_LINE> index = sdf.index(': null') <NEW_LINE> boto.log.error(sdf[index - 100:index + 100]) <NEW_LINE> <DEDENT> api_versio... | Actually send an SDF to CloudSearch for processing
If an SDF file has been explicitly loaded it will be used. Otherwise,
documents added through :func:`add` and :func:`delete` will be used.
:rtype: :class:`CommitResponse`
:returns: A summary of documents added and deleted | 625941c6d58c6744b4257c83 |
def url(self): <NEW_LINE> <INDENT> if self.image: <NEW_LINE> <INDENT> return self.image.url <NEW_LINE> <DEDENT> return self.image_url | Return image_url if image doesn't exist | 625941c682261d6c526ab4c0 |
def difference_with(array, *others, **kwargs): <NEW_LINE> <INDENT> array = array[:] <NEW_LINE> if not others: <NEW_LINE> <INDENT> return array <NEW_LINE> <DEDENT> comparator = kwargs.get("comparator") <NEW_LINE> last_other = others[-1] <NEW_LINE> if comparator is None and (callable(last_other) or last_other is None): <... | This method is like :func:`difference` except that it accepts a comparator which is invoked to
compare the elements of all arrays. The order and references of result values are determined by
the first array. The comparator is invoked with two arguments: ``(arr_val, oth_val)``.
Args:
array (list): The array to find... | 625941c650485f2cf553cdbc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.