code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _apply_styles(self, style_dict, date_dict): <NEW_LINE> <INDENT> if not style_dict or not date_dict: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for groupname, dates in date_dict.items(): <NEW_LINE> <INDENT> cellformat = style_dict.get(groupname, None) <NEW_LINE> if not cellformat: <NEW_LINE> <INDENT> continue <N... | Applies the proper style out of style_dict to every (name,date_list)
in date_dict. | 625941e2ab23a570cc25054d |
def signature_check(key: str, provider: str, http_header_name: str): <NEW_LINE> <INDENT> def decorator(view: Callable): <NEW_LINE> <INDENT> @wraps(view) <NEW_LINE> def _view_wrapper(request: Request, *args, **kwargs): <NEW_LINE> <INDENT> if not key: <NEW_LINE> <INDENT> logger = get_logger('celery.worker') <NEW_LINE> lo... | Decorator for views that checks if the signature from request header
matches the one registered for webhooks.
:param key: The client key used to verify the hash.
:param provider: The provider for which hash is to be verified.
:param http_header_name: Name of HTTP request header which cont... | 625941e263d6d428bbe448b8 |
def set_metadata( self, key: str, metadata: Dict[str, Any], update: bool = False ) -> None: <NEW_LINE> <INDENT> if key not in self.keys(): <NEW_LINE> <INDENT> raise KeyError(f"{self.__class__.__name__} does not contain key '{key}'") <NEW_LINE> <DEDENT> if not isinstance(metadata, Mapping): <NEW_LINE> <INDENT> raise Typ... | Sets the metadata of the data frame located at key with the supplied
key-value pairs.
Parameters
----------
key: str
The key to access.
metadata : Dict[str, Any]
The metadata to store.
update : bool
Update the metadata instead of replacing it. Default False.
Raises
------
KeyError
If any key is not in... | 625941e297e22403b379d363 |
def add_new_power_measurement(self, meter_created, last_measurement, timestamp, **kwargs): <NEW_LINE> <INDENT> if meter_created or not last_measurement or last_measurement.timestamp + self.minimum_store_duration < timestamp: <NEW_LINE> <INDENT> return self.create( timestamp=timestamp, actual_import=kwarg... | Adds a new power measurement to the meter
:param meter_created: if the meter was initially created, if it was, it will always add the power measurement
:param last_measurement: timestamp of last power measurement
:param timestamp: timestamp of new measurement
:param kwargs: other power measurement data
:return: | 625941e2711fe17d8254272a |
def next_frame(self): <NEW_LINE> <INDENT> if self.frame_index < self.num_frames: <NEW_LINE> <INDENT> frame = self.list_frames[self.frame_index] <NEW_LINE> self.frame_index += 1 <NEW_LINE> return frame <NEW_LINE> <DEDENT> return None | retorna next frame, retorno None si ya no hay mas frames | 625941e27d847024c06be687 |
def check_extensions_actually_extend(self): <NEW_LINE> <INDENT> for name in self.__extensions__: <NEW_LINE> <INDENT> assert not hasattr(self.stdlib_module, name) | Check that the module actually defines new entries in __extensions__ | 625941e2f548e778e58cd947 |
def test_nested_data_list_of_dict_with_list_keys(): <NEW_LINE> <INDENT> expect = [{'key': [np.array(0)]}] <NEW_LINE> actual = roundtrip(expect) <NEW_LINE> npt.assert_array_equal(expect[0]['key'][0], actual[0]['key'][0]) <NEW_LINE> expect = [{'key': [np.array([1.0])]}] <NEW_LINE> actual = roundtrip(expect) <NEW_LINE> np... | Ensure we can handle numpy arrays within a nested structure | 625941e244b2445a3393245b |
def _update_environment_config(self, env): <NEW_LINE> <INDENT> return CONSTANTS.ENVIRONMENT_DICT[env] | Helper to return environment config based on env name | 625941e28e7ae83300e4b395 |
def get_version_data(session, url): <NEW_LINE> <INDENT> headers = {'Accept': 'application/json'} <NEW_LINE> resp = session.get(url, headers=headers) <NEW_LINE> try: <NEW_LINE> <INDENT> body_resp = resp.json() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t... | Retrieve raw version data from a url. | 625941e2dd821e528d63b56e |
def permissions(self, user, inherited=None): <NEW_LINE> <INDENT> if inherited is not None: <NEW_LINE> <INDENT> return set(inherited) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return set() | Return permissions available to the given user on this object | 625941e2ac7a0e7691ed448d |
def skew_matrix_from_vector(self, vec): <NEW_LINE> <INDENT> vec = gs.to_ndarray(vec, to_ndim=2) <NEW_LINE> n_vecs = vec.shape[0] <NEW_LINE> vec_dim = gs.shape(vec)[1] <NEW_LINE> if self.n == 2: <NEW_LINE> <INDENT> id_skew = gs.array([[[0., 1.], [-1., 0.]]] * n_vecs) <NEW_LINE> skew_mat = gs.einsum('nij,ni->nij', gs.cas... | In 3D, compute the skew-symmetric matrix,
known as the cross-product of a vector,
associated to the vector vec.
In nD, fill a skew-symmetric matrix with
the values of the vector. | 625941e2566aa707497f492b |
def domname(dom_id_or_uuid, **dargs): <NEW_LINE> <INDENT> return command("domname --domain %s" % dom_id_or_uuid, **dargs) | Convert a domain id or UUID to domain name
:param dom_id_or_uuid: a domain id or UUID.
:param dargs: standardized virsh function API keywords
:return: CmdResult object | 625941e2a4f1c619b28b03f8 |
def __init__(self, ReqI=0, UDPPort=0, Flags=0, Prefix='\x00', Interval=0, Admin='', IName='pyinsim'): <NEW_LINE> <INDENT> self.Size = 44 <NEW_LINE> self.Type = ISP_ISI <NEW_LINE> self.ReqI = ReqI <NEW_LINE> self.Zero = 0 <NEW_LINE> self.UDPPort = UDPPort <NEW_LINE> self.Flags = Flags <NEW_LINE> self.InSimVer = INSIM_VE... | Create a new IS_ISI packet.
Args:
ReqI : If non-zero LFS will send an ``IS_VER`` packet
UDPPort : Port for UDP replies from LFS (0 to 65535)
Flags : ``ISF_`` bit flags for options
Prefix : Special host message prefix character
Interval : Time in ms between ``IS_NLP`` or ``IS_MCI`` packets... | 625941e2442bda511e8be7db |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, GroupType): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941e2d99f1b3c44c67951 |
def run(self): <NEW_LINE> <INDENT> if not os.path.isdir(self.tensor_folder): <NEW_LINE> <INDENT> os.mkdir(self.tensor_folder) <NEW_LINE> <DEDENT> export_number = Tools.getExportNumber(self.tensor_folder) <NEW_LINE> export_path = str(self.tensor_folder) + "/export_" + str(export_number) <NEW_LINE> os.mkdir(export_path) ... | Retrain the tensorflow model using JPG images | 625941e2a934411ee3751a5c |
def full2Dcorr2(self): <NEW_LINE> <INDENT> self.totcorrs = {tt:dict() for tt in self.jumpcorrs} <NEW_LINE> for tt in self.aveY2.keys(): <NEW_LINE> <INDENT> for res in self.aveY2[tt].keys(): <NEW_LINE> <INDENT> beta = self.aveb[tt][res]*np.pi/180. <NEW_LINE> all_corrs = [] <NEW_LINE> for k in range(-2, 3): <NEW_LINE> <I... | See Bremi Bruschweiler Ernst JACS 1997.
the difference between this and v1 is that here we use the ensemble averages of Y2m and beta | 625941e263f4b57ef00014d6 |
def adjusted_prec(p, prec): <NEW_LINE> <INDENT> defect = floor(Integer(2 * prec - 3).log(p)) <NEW_LINE> if prec <= 2: <NEW_LINE> <INDENT> adjusted = 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> adjusted = prec + defect - 1 <NEW_LINE> <DEDENT> while adjusted - defect - 1 < prec: <NEW_LINE> <INDENT> adjusted += 1 <NEW... | Compute how much precision is required in ``matrix_of_frobenius`` to
get an answer correct to ``prec`` `p`-adic digits.
The issue is that the algorithm used in
:func:`matrix_of_frobenius` sometimes performs divisions by `p`,
so precision is lost during the algorithm.
The estimate returned by this function is based on... | 625941e299cbb53fe6792fad |
def sum_response(self): <NEW_LINE> <INDENT> half = len(self.points)/2 <NEW_LINE> quarter = half/2 <NEW_LINE> E = 0 <NEW_LINE> for n in range(quarter): <NEW_LINE> <INDENT> E += fabs( (self.I(n) + self.I(n + half)) - (self.I(n + quarter) + self.I(n + quarter + half)) ) <NEW_LINE> <DEDENT> return E | Returns the ``sum response'' of this sample, as described in ``ChESS:
Quick and Robust Detection of Chess-board Features'' (Bennett & Lasenby). | 625941e2cc40096d61595d17 |
def _pop_task(self): <NEW_LINE> <INDENT> for q in self.queues: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return q.pop() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return None | Pop and return the highest-priority queued Task. | 625941e2507cdc57c63070ab |
def __init__(self, quantifier, max=default_best_N): <NEW_LINE> <INDENT> assert quantifier <NEW_LINE> assert type(max) is type(3) <NEW_LINE> assert max > 0 <NEW_LINE> assert max <= 10000 <NEW_LINE> self._items = [] <NEW_LINE> self.quantifier = quantifier <NEW_LINE> self._sorted = False <NEW_LINE> self.max = max <NEW_LIN... | Define a quantifier func that will be used to get numeric values for
items in the list. By default, the quantifier should return numbers that
are bigger if better; to sort ascending, make the quantifier return
such a sequence times -1. Set max size of list. | 625941e285dfad0860c3b223 |
def test_check_captcha(self): <NEW_LINE> <INDENT> self.test.start_driver(driver_type='Chrome') <NEW_LINE> self.test.maximize_window() <NEW_LINE> self.test.visit_page('http://lits.com.ua/') <NEW_LINE> self.test.click(class_='icon-mail') <NEW_LINE> self.test.should_be_text_on_page('Captcha *') <NEW_LINE> element = self.t... | ! Test that enter valid info in Contact form and submit it. | 625941e23eb6a72ae02ec8af |
def test_denglu(self): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> driver.get("http://localhost/index.php?m=user&c=public&a=login") <NEW_LINE> driver.find_element_by_id("username").send_keys("shm") <NEW_LINE> driver.find_element_by_id("password").send_keys("123456") <NEW_LINE> driver.find_element_by_class_name(... | 登录测试正常情况测试用例 | 625941e2b57a9660fec33c51 |
def was_removed(self): <NEW_LINE> <INDENT> if self.grad_year <= datetime.now().year - 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for team in self.teams: <NEW_LINE> <INDENT> if team.year == datetime.now().year: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | was runner previously deleted from a team but not yet graduated | 625941e257b8e32f52483866 |
def setup(self, parent_params_vec, params_dict, srcvec, my_params, connections, relevance, var_of_interest=None, store_byobjs=False, shared_vec=None, alloc_complex=False): <NEW_LINE> <INDENT> super(PetscTgtVecWrapper, self).setup(parent_params_vec, params_dict, srcvec, my_params, connections, relevance=relevance, var_o... | Configure this vector to store a flattened array of the variables
in params_dict. Variable shape and value are retrieved from srcvec.
Args
----
parent_params_vec : `VecWrapper` or None
`VecWrapper` of parameters from the parent `System`.
params_dict : `OrderedDict`
Dictionary of parameter absolute name mapped... | 625941e2236d856c2ad44ba7 |
def scrape(trackers, hashes, udp_timeout=1, tcp_timeout=1, tcp_max_workers=None): <NEW_LINE> <INDENT> trackers = [tracker.lower() for tracker in trackers] <NEW_LINE> parsed_trackers = [(tracker, urlparse(tracker)) for tracker in trackers] <NEW_LINE> udp_parsed_trackers = [tracker for tracker in parsed_trackers if track... | Returns the list of seeds, peers and downloads a torrent info_hash has,
according to the specified trackers
Args:
trackers (list): The announce url for trackers, usually taken directly
from the torrent metadata
hashes (list): A list of torrent info_hash's to query the tracker for
Returns:
A dict o... | 625941e25fc7496912cc3d46 |
def getRelativeLnPDF(self, x): <NEW_LINE> <INDENT> return InverseGammaDistBase.getRelativeLnPDF(self, x) | Evaluates the natural logarithm of the relative probability density
function at the supplied value x. Use this function if speed is
important but normalization is not, say in MCMC calculations. Use
getLnPDF instead if you need to have a correctly normalized density
value (i.e. from a density function that integrates to... | 625941e250812a4eaa59c6e6 |
def make_wordvec_dict(f_name, out_fname, threads): <NEW_LINE> <INDENT> word_list = list(load_pickle(f_name)) <NEW_LINE> per_f = int(len(word_list) / threads) + 1 <NEW_LINE> logging.info('Per Thread {}'.format(per_f)) <NEW_LINE> pool = mp.Pool(processes=threads) <NEW_LINE> processes = [ pool.apply_async(parallel_word_di... | Loads the pickle containing the dictionary gets word vector from
parallel processing it and puts into dict saved in out_fname | 625941e232920d7e50b2859b |
def __iter__(self): <NEW_LINE> <INDENT> return StackIter(self) | Returns an iterator for the stack. | 625941e2b57a9660fec33c52 |
def fileDialog(self): <NEW_LINE> <INDENT> return KFileDialog() | KFileDialog KUrlRequester.fileDialog() | 625941e28e05c05ec3eea740 |
def realmadmin(request=None, action=None): <NEW_LINE> <INDENT> if g.logged_in_user.get("role") == ROLE.ADMIN: <NEW_LINE> <INDENT> params = request.all_data <NEW_LINE> if not "realm" in params: <NEW_LINE> <INDENT> po = Match.admin(g, action=action).policies() <NEW_LINE> if po and po[0].get("realm"): <NEW_LINE> <INDENT> ... | This decorator adds the first REALM to the parameters if the
administrator, calling this API is a realm admin.
This way, if the admin calls e.g. GET /user without realm parameter,
he will not see all users, but only users in one of his realms.
TODO: If a realm admin is allowed to see more than one realm,
this is... | 625941e271ff763f4b549a5a |
def testAddTestPage(self): <NEW_LINE> <INDENT> self.DatabaseDeleteTestPagesAndCategory() <NEW_LINE> ret = add_category(TEST_CATEGORY_NAME) <NEW_LINE> assert ret == "ok", "Can not add TEST category to Database" <NEW_LINE> category_ = models.Category.query.filter_by(name = TEST_CATEGORY_NAME ).first() <NEW_LINE> assert c... | Test: ADD Page
| 625941e276e4537e8c351a3d |
def test_read(self): <NEW_LINE> <INDENT> dataMap = DataMap.DataMap(self.filepath) <NEW_LINE> dataMap.read() <NEW_LINE> self.assertEquals("Bright Field Image", dataMap.imageName) <NEW_LINE> self.assertEquals((100, 100), dataMap.size) <NEW_LINE> self.assertEquals(34.0, dataMap.pixels[50][50]) | Tests for method `read`. | 625941e2bf627c535bc13598 |
def autorun(self): <NEW_LINE> <INDENT> return self.___autorun_default | By default autorun is disabled. | 625941e2c432627299f05011 |
def render_to(template=None): <NEW_LINE> <INDENT> def renderer(func): <NEW_LINE> <INDENT> def wrapper(*args, **kw): <NEW_LINE> <INDENT> request = None <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if isinstance(arg, HttpRequest): <NEW_LINE> <INDENT> request = arg <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not r... | Decorator for Django views that sends returned dict to render_to_response
function with given template and RequestContext as context instance.
If view doesn't return dict then decorator simply returns output.
Additionally view can return two-tuple, which must contain dict as first
element and string with template name... | 625941e296565a6dacc8fa93 |
def migrate(db, package, conf={}): <NEW_LINE> <INDENT> ver = get_version(db) <NEW_LINE> package = importlib.import_module(package) <NEW_LINE> logging.debug('Migration version for %s is %s', package.__package__, ver) <NEW_LINE> mods = get_mods(package) <NEW_LINE> migrations = get_new(mods, ver + 1) <NEW_LINE> for name, ... | Run all migrations that have not been run
Migrations will be run inside a transaction.
:param db: database connection object
:param package: package that contains the migrations
:param conf: application configuration object | 625941e2a4f1c619b28b03f9 |
def prep_score(self): <NEW_LINE> <INDENT> rounder_score = int(round(self.stats.score, -1)) <NEW_LINE> score_str = "{:,}".format(rounder_score) <NEW_LINE> self.score_image = self.font.render(score_str,True,self.text_color,self.ai_settings.bg_color) <NEW_LINE> self.score_rect = self.score_image.get_rect() <NEW_LINE> self... | switch score to img | 625941e273bcbd0ca4b2c43e |
def reshape_vec_in_patch(vec_patches, patch_size): <NEW_LINE> <INDENT> if vec_patches.ndim == 1: <NEW_LINE> <INDENT> patches = vec_patches.reshape((patch_size[0], patch_size[1])) <NEW_LINE> <DEDENT> elif vec_patches.ndim == 2: <NEW_LINE> <INDENT> patches = vec_patches.reshape((patch_size[0], patch_size[1], vec_patches.... | :param vec_patches: array, shape = (patch_height * patch_width, patches_number)
:param patch_size: tuple of ints (patch_height, patch_width)
:return patches: array, shape = (patch_height, patch_width, patches_number) | 625941e26fece00bbac2db0b |
def setUp(self): <NEW_LINE> <INDENT> super(SceneExceptionTestCase, self).setUp() <NEW_LINE> scene_exceptions.retrieve_exceptions() | Set up tests | 625941e25f7d997b87174e64 |
def _create_alg(self): <NEW_LINE> <INDENT> class TestAlgorithm(PythonAlgorithm): <NEW_LINE> <INDENT> def PyInit(self): <NEW_LINE> <INDENT> int_validator = IntArrayOrderedPairsValidator() <NEW_LINE> self.declareProperty(IntArrayProperty("IntInput", int_validator)) <NEW_LINE> float_validator = FloatArrayOrderedPairsValid... | Creates a test algorithm with a ordered pairs validator | 625941e22c8b7c6e89b35b86 |
def build_pxe_config(deployment_id, deployment_key, deployment_iscsi_iqn, deployment_aki_path, deployment_ari_path, aki_path, ari_path, network_info): <NEW_LINE> <INDENT> LOG.debug("Building PXE config for deployment %s.", deployment_id) <NEW_LINE> network_config = None <NEW_LINE> if network_info and CONF.baremetal.pxe... | Build the PXE config file for a node
This method builds the PXE boot configuration file for a node,
given all the required parameters.
The resulting file has both a "deploy" and "boot" label, which correspond
to the two phases of booting. This may be extended later. | 625941e2cdde0d52a9e533fe |
def graphicsPaint(self, p, options, itemId, widget = 0): <NEW_LINE> <INDENT> super().graphicsPaint(p, options, itemId, widget) <NEW_LINE> pen = self.getPen() <NEW_LINE> pen.setWidth(0) <NEW_LINE> pen.setColor(Qt.white) <NEW_LINE> p.setPen(pen) <NEW_LINE> p.drawText(self._rect.bottomLeft(), self.name) | This function is called by the owned TrackGraphicsItem to paint its
painter. | 625941e291af0d3eaac9bde5 |
def regplot_balance_theory(pkl_file): <NEW_LINE> <INDENT> inp_dict = misc.read_file_into_dict(pkl_file) <NEW_LINE> sorted_dates_list = list(sorted(inp_dict.keys())) <NEW_LINE> balance_list = [] <NEW_LINE> for sorted_date in sorted_dates_list: <NEW_LINE> <INDENT> balance_list.append(inp_dict[sorted_date]) <NEW_LINE> <DE... | Reads a pkl file and plots a regplot for balance theory.
Args:
pkl_file : Input
Returns:
None | 625941e276e4537e8c351a3e |
def add_dates(self, dates): <NEW_LINE> <INDENT> if len(dates) == 0: <NEW_LINE> <INDENT> raise SdkException('Use not empty Set') <NEW_LINE> <DEDENT> self.pg_dates = dates | :param dates: Set of sting dates (Dict) | 625941e23317a56b8693a018 |
def test_process16(self): <NEW_LINE> <INDENT> processResult(self.driver).processing_detail("其他申请") <NEW_LINE> self.assertEqual(processResult(self.driver).processing_detailInfo_title(), "其他:陪客户吃饭") <NEW_LINE> print(process(self.driver).returnSystemtime1()) <NEW_LINE> Date1=process(self.driver).returnSystemtime1()-dateti... | 其他假(无结束时间):点击申请中,查看详情并且进行撤销操作 | 625941e24f88993c3716c42c |
def __init__(self, channel): <NEW_LINE> <INDENT> self.List = channel.unary_unary( '/class.ClassController/List', request_serializer=class__pb2.ClassListRequest.SerializeToString, response_deserializer=class__pb2.ClassList.FromString, ) <NEW_LINE> self.GetCommonClasses = channel.unary_unary( '/class.ClassController/GetC... | Constructor.
Args:
channel: A grpc.Channel. | 625941e2d268445f265b5237 |
@bp.route('/topic/<int:uid>/add_child_topic', methods=['POST']) <NEW_LINE> @UserPermission() <NEW_LINE> @jsonify <NEW_LINE> def add_child_topic(uid): <NEW_LINE> <INDENT> topic = Topic.query.get_or_404(uid) <NEW_LINE> child_topic_id = request.form.get('child_topic_id', type=int) <NEW_LINE> name = request.form.get('name'... | 添加直接子话题 | 625941e21d351010ab855ee3 |
def min_edit_distance(s1, s2): <NEW_LINE> <INDENT> matrix = lavenshtein_matrix(s1, s2) <NEW_LINE> print(format_2d_array(matrix, '#' + s1, '#' + s2)) <NEW_LINE> return matrix[-1][-1] | Computes Minimum edit distance for the two strings
:param s1: first string
:param s2: second string
:return: minimum edit distance (lavenshtein value) | 625941e2d164cc6175783118 |
def __GetAuthorizationTokenUsingMasterKey(verb, resource_id, resource_type, headers, master_key): <NEW_LINE> <INDENT> key = master_key.decode('base64') <NEW_LINE> text = '{verb}\n{resource_type}\n{resource_id}\n{x_date}\n{http_date}\n'.format( verb=(verb or ''), resource_type=(resource_type or ''), resource_id=(resourc... | Gets the authorization token using `master_key.
:Parameters:
- `verb`: str
- `resource_id`: str
- `resource_type`: str
- `headers`: dict
- `master_key`: st
:Returns:
dict | 625941e20fa83653e4657381 |
def __call__(self, dataset_dict): <NEW_LINE> <INDENT> dataset_dict = copy.deepcopy(dataset_dict) <NEW_LINE> image = utils.read_image(dataset_dict["file_name"], format=self.img_format) <NEW_LINE> utils.check_image_size(dataset_dict, image) <NEW_LINE> if self.kd_without_label or "annotations" not in dataset_dict: <NEW_LI... | Args:
dataset_dict (dict): Metadata of one image, in centernet Dataset format.
Returns:
dict: a format that builtin models in centernet accept | 625941e2fff4ab517eb2f806 |
def hasCycle(self, head): <NEW_LINE> <INDENT> if head == None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> x = head <NEW_LINE> y = head.next <NEW_LINE> while x != None and y != None and y.next != None : <NEW_LINE> <INDENT> if x == y: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> x = x.next <NEW_LINE> y =... | :type head: ListNode
:rtype: bool | 625941e26e29344779a629d9 |
def test_change_current_level_to_negative_value(self): <NEW_LINE> <INDENT> user = User.objects.get(username='testuser') <NEW_LINE> old = user.profile.current_level <NEW_LINE> new_settings = {'current_level': -1} <NEW_LINE> response = self.change_settings('testuser', '1', new_settings) <NEW_LINE> self.assertEqual(status... | Current level cannot be set to a negative value. | 625941e271ff763f4b549a5b |
def ts_to_datetime_str(ts=None, fmt='%Y-%m-%d %H:%M:%S'): <NEW_LINE> <INDENT> if not ts: <NEW_LINE> <INDENT> ts = get_cur_timestamp() <NEW_LINE> <DEDENT> dt = datetime.datetime.fromtimestamp(int(ts)) <NEW_LINE> return dt.strftime(fmt) | 将时间戳转换为日期时间格式,年-月-日 时:分:秒
@param ts 时间戳,默认None即为当前时间戳
@param fmt 返回的日期字符串格式 | 625941e216aa5153ce362841 |
def get( self, resource_group_name, load_balancer_name, load_balancing_rule_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LI... | Gets the specified load balancer load balancing rule.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param load_balancer_name: The name of the load balancer.
:type load_balancer_name: str
:param load_balancing_rule_name: The name of the load balancing rule.
:type load_balan... | 625941e2c4546d3d9de72e00 |
def has_common_or_proper_concept(edge): <NEW_LINE> <INDENT> if edge.is_atom(): <NEW_LINE> <INDENT> return edge.type()[:2] == 'Cp' or edge.type()[:2] == 'Cc' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for subedge in edge[1:]: <NEW_LINE> <INDENT> if has_proper_concept(subedge): <NEW_LINE> <INDENT> return True <NEW_LIN... | Check if the concept either is a common/proper edge, or contains one. | 625941e23617ad0b5ed682bf |
def visualization_for_radpoint(maps, point_list, color, radias): <NEW_LINE> <INDENT> for point in point_list: <NEW_LINE> <INDENT> if ~np.isnan(point[0]): <NEW_LINE> <INDENT> maps.addradpoint(point[0],point[1],radias,color) | For trip visualization | 625941e24f6381625f114e04 |
def setColor(self, color): <NEW_LINE> <INDENT> if color == None: <NEW_LINE> <INDENT> self.color = (1, 1, 1, .3) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.color = QtGui.QColor(color).getRgbF() | set the color of the Grid
'color' can be any value accepted by QColor | 625941e297e22403b379d364 |
def get_zoombies_floating_ips(self): <NEW_LINE> <INDENT> all_floating_ips = self.neutron.list_floatingips() <NEW_LINE> zoombies = [] <NEW_LINE> for fip in all_floating_ips['floatingips']: <NEW_LINE> <INDENT> if not fip['port_id'] and not fip['router_id']: <NEW_LINE> <INDENT> zoombies.append(fip) <NEW_LINE> <DEDENT> <DE... | get all floating ips and filter by disassociated ips | 625941e224f1403a92600f2b |
def test_syll_constr_heavymaker(self): <NEW_LINE> <INDENT> self.assertTrue(isinstance(Syllable('zeph'), Syllable)) <NEW_LINE> self.assertTrue(isinstance(Syllable('xoe'), Syllable)) <NEW_LINE> self.assertTrue(isinstance(Syllable('hux'), Syllable)) | regular syllable with initial consonant cluster | 625941e20a366e3fb873ebe6 |
def setCompletionMode(self, mode): <NEW_LINE> <INDENT> pass | void KCompletion.setCompletionMode(KGlobalSettings.Completion mode) | 625941e2ad47b63b2c50a347 |
def __enter__(self): <NEW_LINE> <INDENT> if self.ident_level is None: <NEW_LINE> <INDENT> self.ident_level = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ident_level += 1 <NEW_LINE> <DEDENT> padding = self._gen_padding() <NEW_LINE> self._set_logger(padding) <NEW_LINE> return self.logger | Increment the indent level, modify the format accordingly | 625941e2cc0a2c11143dd25a |
def upper_confidence_bound(self, optimizer, x): <NEW_LINE> <INDENT> mu,std = optimizer.predict(np.atleast_2d(x), return_std=True) <NEW_LINE> return (mu+1.96*std)[0] | Calculates the upper confidence bound as an acquisition function.
Args:
optimizer: a fitted gaussian process regressor
x: a numpy array with parameter values
Returns:
a float | 625941e24527f215b584c81c |
def t_EXIT(t): <NEW_LINE> <INDENT> t.value = str(t.value) <NEW_LINE> return t | exit | 625941e26aa9bd52df03716f |
def reverse_complement(seq): <NEW_LINE> <INDENT> compdict = { 'a': 't', 'c': 'g', 'g': 'c', 't': 'a', 'u': 't', 'm': 'k', 'r': 'y', 'w': 'w', 's': 's', 'y': 'r', 'k': 'm', 'v': 'b', 'h': 'd', 'd': 'h', 'b': 'v', 'x': 'x', 'n': 'n', 'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'U': 'T', 'M': 'K', 'R': 'Y', 'W': 'W', 'S': 'S'... | Returns the reverse complement of a DNA sequence as string | 625941e21b99ca400220ae7c |
def __init__(self, shape, orient=Orient.Forward, location=Location()): <NEW_LINE> <INDENT> if not issubclass(type(shape), Shape): <NEW_LINE> <INDENT> raise ParamError("Expected Shape, get: {}.".format(shape)) <NEW_LINE> <DEDENT> assert isinstance(orient, Orient) <NEW_LINE> assert issubclass(type(location), Location) <N... | :param shape: referenced shape
:param orient: orientation of the shape, value is enum Orient
:param location: A Location object. Default is None = identity location. | 625941e2099cdd3c635f1022 |
def is_url_changed(self, current_url, wait_time=60, detect_interval=0.5): <NEW_LINE> <INDENT> changed_time = 0 <NEW_LINE> is_changed = False <NEW_LINE> for i in range(0, wait_time): <NEW_LINE> <INDENT> if not str(self.current_url) == str(current_url): <NEW_LINE> <INDENT> is_changed = True <NEW_LINE> print("Url changed ... | to see whether the url changed in certain time
:param current_url: current url <str>
:param wait_time: the time(in sec) that wait until the url changed, default is 60 <int>
:param detect_interval: time interval that detect whether url is changed
:return: True if url is changed in wait_time ,
False if url is ... | 625941e230c21e258bdfa869 |
def to_decimal(value, ctx): <NEW_LINE> <INDENT> if isinstance(value, bool): <NEW_LINE> <INDENT> return Decimal(1) if value else Decimal(0) <NEW_LINE> <DEDENT> elif isinstance(value, int): <NEW_LINE> <INDENT> return Decimal(value) <NEW_LINE> <DEDENT> elif isinstance(value, Decimal): <NEW_LINE> <INDENT> return value <NEW... | Tries conversion of any value to a decimal | 625941e224f1403a92600f2c |
def get_bundle_accessions(self, description_token=str()): <NEW_LINE> <INDENT> if not description_token: <NEW_LINE> <INDENT> description_token = self.description_token <NEW_LINE> <DEDENT> submission_records = cursor_to_list( Submission().get_collection_handle().find( {"description_token": {"$in": [description_token]}, '... | function returns submission accessions for a bundle
:param description_token:
:return: | 625941e2be8e80087fb21006 |
def new_tx(from_id, to_id, amount): <NEW_LINE> <INDENT> conn = mysql.connect(host='127.0.0.1', port=3306, user='root', password='password', db='tipper') <NEW_LINE> cur = conn.cursor() <NEW_LINE> cur.execute('INSERT INTO transactions (from_id, to_id, state, amount) VALUES (%s, %s, \'new\', %s);', (from_id, to_id, amount... | Adds a new transaction (tip) to the database | 625941e231939e2706e4d22e |
def start(self, result): <NEW_LINE> <INDENT> TestResultChannel.start(self, result) <NEW_LINE> self._progress.start(result) | Signals start of execution of tests. | 625941e23539df3088e2e714 |
def func_and(parser, x, y, *args): <NEW_LINE> <INDENT> if _compute_logic(all, x, y, *args): <NEW_LINE> <INDENT> return "1" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" | Returns true, if both ``x`` and ``y`` are not empty.
Can be used with an arbitrary number of arguments. The result is
true if ALL of the arguments are not empty. | 625941e2ff9c53063f47c5bb |
def clearPoints(self): <NEW_LINE> <INDENT> self.vtkPoints = vtk.vtkPoints() <NEW_LINE> self.vtkCells = vtk.vtkCellArray() <NEW_LINE> self.vtkDepth = vtk.vtkDoubleArray() <NEW_LINE> self.vtkDepth.SetName('DepthArray') <NEW_LINE> self.vtkPolyData.SetPoints(self.vtkPoints) <NEW_LINE> self.vtkPolyData.SetVerts(self.vtkCell... | Clear all points from the point cloud
:return: None | 625941e23eb6a72ae02ec8b0 |
def get_abstract_tokens(cur, cp): <NEW_LINE> <INDENT> cur.execute("SELECT abstract FROM codepoint_abstract WHERE cp = %s AND lang = 'en'", (cp,)) <NEW_LINE> abstract = (cur.fetchone() or {'abstract':None})['abstract'] <NEW_LINE> if abstract: <NEW_LINE> <INDENT> terms = BeautifulSoup(abstract, 'lxml').get_text() <NEW_LI... | Fetch abstract for cp and split it in tokens | 625941e29b70327d1c4e11a0 |
def log_duration(name, logger=None, level=logging.DEBUG): <NEW_LINE> <INDENT> logger = logger or _logger <NEW_LINE> return DurationMeasurement(name, logger, level) | Convenience function to log the duration of a specific event.
:param name: The name of the event.
:param logger: The logger to use.
:param level: The log level to log the final message to. | 625941e2a8370b7717052c67 |
def _proxify(func) -> weakref.ProxyType: <NEW_LINE> <INDENT> _keep_alive.append(func) <NEW_LINE> return weakref.proxy(func) | Create a weakref.proxy to a function.
stores a strong reference to keep methods etc.
alive.
`func`: Function to be proxied.
`return`: weakref.proxy to the function. | 625941e297e22403b379d365 |
def wait_element(self, locator): <NEW_LINE> <INDENT> by = locator[0] <NEW_LINE> value = locator[1] <NEW_LINE> print("正在定位元素信息:定位方式->%s, value值->%s" % (locator[0], locator[1])) <NEW_LINE> if by == "id": <NEW_LINE> <INDENT> a = WebDriverWait(self.driver, self.timeout,self.t).until(EC.presence_of_element_located(locator))... | 等待元素在指定的时间类出现
:param element: 元素的定位表达式
:param seconds: 等待的时间
:return: | 625941e2711fe17d8254272c |
def update_cerebrate_record(cerebrate_record): <NEW_LINE> <INDENT> mac = cerebrate_record.get(Record.MAC, None) <NEW_LINE> if not mac: <NEW_LINE> <INDENT> logging.warning('No MAC address provided in record:') <NEW_LINE> logging.info(''.join(("record: ", str(cerebrate_record)))) <NEW_LINE> return False <NEW_LINE> <DEDEN... | Overwrites the appropriate cerebrate record with the given record.
Creates a new one if the given cerebrate does not exist.
Returns False if no MAC is given in record. | 625941e2de87d2750b86015f |
def plot(x, y, xlabel=None, ylabel=None, title=None, figsize=(4,2.8), logx=False, logy=False, xmin=None, xmax=None, ymin=None, ymax=None, savefig=None): <NEW_LINE> <INDENT> plt.figure(figsize=figsize, dpi=100, facecolor='white') <NEW_LINE> if not logx and not logy: plt.plot(x, y) <NEW_LINE> if not logx and logy: ... | Plot function
| 625941e2ad47b63b2c50a348 |
def unsubscribe(self, subscription_url) -> dict: <NEW_LINE> <INDENT> return requests.delete(subscription_url, headers=self.headers).json() | Unsubscribe a profile from a service via the subscription url | 625941e2462c4b4f79d1da99 |
def test_is_open_sea2(): <NEW_LINE> <INDENT> fleet = [(2, 3, False, 2, set()), (0, 0, True, 1, set()), (9, 1, True, 4, set()), (1, 5, False, 2, set()), (5, 6, True, 3, set()), (0, 7, False, 3, set()), (1, 9, False, 2, set()), (7, 3, True, 1, set()), (7, 8, False, 1, set()), (6, 0, False, 1, set())] <NEW_LINE> assert is... | Test to see if a valid location in an unoccupied or adjacent position is accepted | 625941e2f548e778e58cd949 |
def reverseBetween(self, head, m, n): <NEW_LINE> <INDENT> dummy = ListNode(0) <NEW_LINE> dummy.next = head <NEW_LINE> cur = dummy <NEW_LINE> for i in range(1, m): <NEW_LINE> <INDENT> cur = cur.next <NEW_LINE> <DEDENT> tail = cur.next <NEW_LINE> for i in range(m, n): <NEW_LINE> <INDENT> if tail is None: <NEW_LINE> <INDE... | :type head: ListNode
:type m: int
:type n: int
:rtype: ListNode | 625941e24e4d5625662d479c |
def verify_donestamp(ud, d, origud=None): <NEW_LINE> <INDENT> if not os.path.exists(ud.donestamp): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if (not ud.method.supports_checksum(ud) or (origud and not origud.method.supports_checksum(origud))): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if not os.path... | Check whether the done stamp file has the right checksums (if the fetch
method supports them). If it doesn't, delete the done stamp and force
a re-download.
Returns True, if the donestamp exists and is valid, False otherwise. When
returning False, any existing done stamps are removed. | 625941e24e696a04525c9816 |
def force_required(area_sqm, Nm=True): <NEW_LINE> <INDENT> if area_sqm: <NEW_LINE> <INDENT> result = ( (6 * u_("lbf")).to(u_("newton")) * (u_("inch").to(u_("m")) * area_sqm.to(u_("ft^2")).magnitude) ).to(u_("Nm")) <NEW_LINE> if Nm: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return r... | 6 force_pound * inch for a 1 square_foot surface | 625941e23617ad0b5ed682c0 |
def crosspower(self, column_a, power_a, column_b, power_b, lag_a=None, lag_b=None, vector='column' ): <NEW_LINE> <INDENT> NoneSet = {None, ''} <NEW_LINE> if lag_a in NoneSet: <NEW_LINE> <INDENT> lag_a = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lag_a = int( lag_a ) <NEW_LINE> <DEDENT> if lag_b in NoneSet: <NEW_LI... | Returns the product of two columns, each raised to the specified
power. Makes use of precalculated columns if applicable. | 625941e2eab8aa0e5d26df23 |
def calculateHandlen(hand): <NEW_LINE> <INDENT> handlength = 0 <NEW_LINE> for letter in hand.keys(): <NEW_LINE> <INDENT> for j in range(hand[letter]): <NEW_LINE> <INDENT> handlength += 1 <NEW_LINE> <DEDENT> <DEDENT> return handlength | Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer | 625941e25e10d32532c5f2ef |
def quote(string): <NEW_LINE> <INDENT> return '"{string}"'.format(string=string.replace('"', '\\"')) | Quote
This function will quote a string:
eg: A String -> "A String"
Arguments:
string {str} -- The string to quote
Returns:
str -- The quoted string | 625941e20383005118ecf9ab |
def display(b): <NEW_LINE> <INDENT> def f(s): <NEW_LINE> <INDENT> if b[s] in singles: <NEW_LINE> <INDENT> return str(int(math.log(b[s], 2) + 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '+' <NEW_LINE> <DEDENT> <DEDENT> return ''.join([f(s) for s in squares]) | Returns a string representation of the board in a single line. Blanks are filled with '+'. | 625941e2656771135c3ebc3d |
def create_masks(inputs, target): <NEW_LINE> <INDENT> enc_mask = tf.cast(tf.math.equal(inputs, 0), tf.float32) <NEW_LINE> enc_mask = enc_mask[:, tf.newaxis, tf.newaxis, :] <NEW_LINE> dec_mask = tf.cast(tf.math.equal(inputs, 0), tf.float32) <NEW_LINE> dec_mask = dec_mask[:, tf.newaxis, tf.newaxis, :] <NEW_LINE> la_size ... | Creates 3 mask | 625941e256ac1b37e6264592 |
@task <NEW_LINE> def resetdb(): <NEW_LINE> <INDENT> print_msg('Reset database') <NEW_LINE> manage('reset_db') <NEW_LINE> migrate() <NEW_LINE> createsuperuser() | Reset database to initial state. | 625941e21f5feb6acb0c4f14 |
def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> count = request.user.addresses.count() <NEW_LINE> if count > constants.USER_ADDRESS_COUNTS_LIMIT: <NEW_LINE> <INDENT> return Response({'message': '地址数量已达到上限'}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> return super().create(request, *args, **... | 修改用户地址 | 625941e2ac7a0e7691ed448f |
def __repr__(self): <NEW_LINE> <INDENT> return f"<Question({self.testset}/{self.area}/{self.name}:{self.version})>" | Represent instance as a unique string. | 625941e2283ffb24f3c55cc7 |
def check_files_match(self, result, correct, count=None): <NEW_LINE> <INDENT> if count != None: <NEW_LINE> <INDENT> errs = 0 <NEW_LINE> for i in range(count): <NEW_LINE> <INDENT> errs += self.check_files_match(result%i, correct) <NEW_LINE> <DEDENT> return errs <NEW_LINE> <DEDENT> return check_files_match(self.dir(resul... | if COUNT is specified then [0,COUNT) is mapped onto the %d in RESULT | 625941e2442bda511e8be7dd |
@run_as('root') <NEW_LINE> def apache_stop(): <NEW_LINE> <INDENT> run('invoke-rc.d apache2 stop') | Stops apache using init.d script. | 625941e229b78933be1e5a71 |
def exportSVG(self, element, fileOut): <NEW_LINE> <INDENT> document = inkex.etree.fromstring(blankSVG) <NEW_LINE> elem_tmp = deepcopy(element) <NEW_LINE> defs_tmp = deepcopy(self.getDefinitions()) <NEW_LINE> document.append(defs_tmp) <NEW_LINE> if isinstance(elem_tmp, list): <NEW_LINE> <INDENT> for e in elem_tmp: <NEW_... | Export the elements in a new svgfile
This function will export the element in a new SVG file. If a list of elements is passed as argument. All elements in the list will be exported to the same file.
:param element: element or list of elements to be exported
:param fileOut: file path, including the extension.
:type el... | 625941e27d43ff24873a306d |
def _verify_resolved(self): <NEW_LINE> <INDENT> if ( self.resolved and self.resolved is RefreshableCredentials and self.resolved.refresh_needed() ): <NEW_LINE> <INDENT> self._resolve() | Verify or update resolved credentials. | 625941e245492302aab5e691 |
def scrape_first_img(browser, url=img_url): <NEW_LINE> <INDENT> first_img = '' <NEW_LINE> print('Scraping most recent Mars image...') <NEW_LINE> try: <NEW_LINE> <INDENT> browser.visit(img_url) <NEW_LINE> browser.is_element_present_by_css('section a.group', wait_time=1) <NEW_LINE> browser.links.find_by_partial_href('ima... | Scrape the most recent image in the Mars category of the NASA website.
Parameters
----------
browser : Splinter WebDriver
Automated browser for scraping
url : str, optional
Website to scrape, by default
'https://www.jpl.nasa.gov/images?search=&category=Mars'
Returns
-------
str
URL of the featured Ma... | 625941e2f7d966606f6aa3d3 |
def insert(self, id_empleado, tipo, fecha, hora): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> database = Database() <NEW_LINE> connection = database.getConnection() <NEW_LINE> query = 'INSERT INTO movimientos (empleado_id, tipo, fecha, hora) VALUES (%s, %s, %s, %s)' <NEW_LINE> values = (id_empleado, tipo, fecha, hora)... | Agrega un movimento en la DB
Recibe id_empleado, tipo, fecha, hora
Devuelve True si fue realizado con exito | 625941e2498bea3a759b9e78 |
def psi_ft(self, f): <NEW_LINE> <INDENT> return (pi ** -.25) * exp(-0.5 * (f - self.f0) ** 2.) | Fourier transform of the approximate Morlet wavelet. | 625941e221a7993f00bc80c0 |
def TrigReduce(i): <NEW_LINE> <INDENT> if SumQ(i): <NEW_LINE> <INDENT> t = 0 <NEW_LINE> for k in i.args: <NEW_LINE> <INDENT> t += TrigReduce(k) <NEW_LINE> <DEDENT> return t <NEW_LINE> <DEDENT> if ProductQ(i): <NEW_LINE> <INDENT> if any(PowerQ(k) for k in i.args): <NEW_LINE> <INDENT> if (i.rewrite(sin, exp).rewrite(cos,... | TrigReduce(expr) rewrites products and powers of trigonometric functions in expr in terms of trigonometric functions with combined arguments.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.integrals.rubi.utility_function import TrigReduce
>>> from sympy.abc import x
>>> TrigReduce(cos(x)**2)
cos(2*x)... | 625941e25f7d997b87174e65 |
@click.command(context_settings=CONTEXT_SETTINGS) <NEW_LINE> @click.version_option(version=__version__) <NEW_LINE> @click.option('-f', '--fastq', required=True, type=click.Path(), help="The fastq input") <NEW_LINE> @click.option('-t', '--type', required=True, type=click.Choice(['1', '2']), help="Read1 or Read2") <NEW_L... | Rename the input fastq.gz file's id
As the id in fq1 and fq2 file download from sra sometime,
This script is to rename the fq's id to numbers so both
id's are same | 625941e2627d3e7fe0d6921b |
def commandItemsQuery(self, con, iq_obj): <NEW_LINE> <INDENT> jid = helpers.get_full_jid_from_iq(iq_obj) <NEW_LINE> node = iq_obj.getTagAttr('query', 'node') <NEW_LINE> if node not in self.__commands: return False <NEW_LINE> cmd = self.__commands[node] <NEW_LINE> if cmd.isVisibleFor(self.isSameJID(jid)): <NEW_LINE> <IN... | Send disco#items result for query for command. Return True if the result
was sent, False if not. | 625941e285dfad0860c3b226 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.