code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def HMC(current_q, encoder, decoder, epsilon, L, x, beta): <NEW_LINE> <INDENT> current_q.requires_grad_(False) <NEW_LINE> current_p = torch.randn_like(current_q) <NEW_LINE> q = current_q.clone().detach() <NEW_LINE> p = current_p.clone().detach() <NEW_LINE> U, grad_U, _, _ = calc_energy(q, encoder, decoder, x, beta) <NE... | Hamiltonian Monte Carlo (HMC) Algorithm
| 625941ec4428ac0f6e5bacff |
def pickIndex(self): <NEW_LINE> <INDENT> total = self.sums[-1] <NEW_LINE> randomNum = random.randint(1, total) <NEW_LINE> left, right = 0, len(self.sums)-1 <NEW_LINE> while left <= right: <NEW_LINE> <INDENT> mid = (left+right)/2 <NEW_LINE> if self.sums[mid] >= randomNum: <NEW_LINE> <INDENT> right = mid - 1 <NEW_LINE> <... | :rtype: int | 625941ec3317a56b8693a154 |
def load_and_inherit_package(profile, package_name, parameters, encountered=None): <NEW_LINE> <INDENT> if encountered is None: <NEW_LINE> <INDENT> encountered = set() <NEW_LINE> <DEDENT> if package_name in encountered: <NEW_LINE> <INDENT> raise ProfileError(package_name, 'Diamond-pattern inheritance not yet supported, ... | Loads a package from the given profile, and transforms the package spec to
include the parts of the spec inherited through the `extends` section.
The `extends` section is removed.
Returns ``(spec_doc, hook_files)``. `hook_files` is a list of
Python hooks to load; max. one per package/proto-package involved | 625941ec07d97122c4178da0 |
def test_Correct_heapify_up(self): <NEW_LINE> <INDENT> input = [14, 17, 13, 15, 16, 18, 10, 19, 11, 12] <NEW_LINE> swaps = [(4, 9), (1, 4), (0, 1), (3, 8), (1, 3), (0, 1), (2, 6), (0, 2)] <NEW_LINE> m = self.__class__.matcher <NEW_LINE> main_loop = m.loop_variants[0][2] <NEW_LINE> heapify = m.heapify_up <NEW_LINE> (sta... | Correct loop, Heapify-Up | 625941ecec188e330fd5ac9d |
@blueprint.route('/authorize/<provider>') <NEW_LINE> def oauth_authorize(provider): <NEW_LINE> <INDENT> if current_user.is_authenticated: <NEW_LINE> <INDENT> current_app.logger.debug("Redirect authenticated user to main page.") <NEW_LINE> return redirect(url_for('index')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> o... | OAUTH authorization flow. | 625941ec293b9510aa2c3799 |
def on_server_status(self, request): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> return Response('OK', status=200) <NEW_LINE> <DEDENT> return Response('', status=400) | Returns an OK on a GET. This is to support health checks by any
monitoring software on this application | 625941ec99fddb7c1c9de897 |
@add_common_docstring(append=PARAMETER_DOCS) <NEW_LINE> def true_longitude(t='now'): <NEW_LINE> <INDENT> result = equation_of_center(t) + geometric_mean_longitude(t) <NEW_LINE> return Longitude(result) | Returns the Sun's true geometric longitude (in degrees).
(Referred to the mean equinox of date. Question: Should the higher
accuracy terms from which app_long is derived be added to true_long?) | 625941ec5166f23b2e1a5662 |
def rvs(self, size=1, **kwds): <NEW_LINE> <INDENT> dtype = [(p, float) for p in self.params] <NEW_LINE> arr = numpy.zeros(size, dtype=dtype) <NEW_LINE> draw = {} <NEW_LINE> for param in self.params: <NEW_LINE> <INDENT> draw[param] = numpy.random.uniform(0, 1, size=size) <NEW_LINE> <DEDENT> exp = self.cdfinv(**draw) <NE... | Draw random value | 625941ec099cdd3c635f1161 |
def get_absolute_name(obj: T) -> str: <NEW_LINE> <INDENT> if not hasattr(obj, '__name__') and isinstance(obj, _GenericAlias): <NEW_LINE> <INDENT> name = repr(obj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = obj.__name__ <NEW_LINE> <DEDENT> full_name = getattr(obj, '__qualname__', '').replace('<locals>.', '') <... | Used to create interlinks | 625941ec63f4b57ef0001613 |
def value(self, value): <NEW_LINE> <INDENT> pass | Get or set the digital logic level of the pin. | 625941ec8e05c05ec3eea882 |
def gencode_mirror(mapping, py=True): <NEW_LINE> <INDENT> cycles = [["uFr", "uFl"], ["uBr", "uBl"], ["ufR", "ufL"], ["ubR", "ubL"], ["ul", "ur"], ["dFr", "dFl"], ["dBr", "dBl"], ["dfR", "dfL"], ["dbR", "dbL"], ["dl", "dr"], ["fl", "fr"], ["bl", "br"], ["ru", "lu"], ["rf", "lf"], ["rd", "ld"], ["rb", "lb"], ["Dfr", "Dfl... | Generate code for the single needed cube reflection. | 625941ec6aa9bd52df0372b0 |
@pytest.fixture(scope="module") <NEW_LINE> def user_restricted(appliance, group_with_tag, new_credential): <NEW_LINE> <INDENT> user = appliance.collections.users.create( name=fauxfactory.gen_alphanumeric(start="user_"), credential=new_credential, email='xyz@redhat.com', groups=[group_with_tag], cost_center='Workload', ... | Returns restricted user object assigned
to group with tag filter used in test module | 625941ecb5575c28eb68e50e |
def seedSponsor(sponsor_id=None, **kwargs): <NEW_LINE> <INDENT> sponsor_id = sponsor_id or string_provider.UniqueIDProvider().getValue() <NEW_LINE> properties = { 'description': TEST_SPONSOR_DESCRIPTION, 'email': TEST_SPONSOR_EMIAL, 'home_page': TEST_SPONSOR_HOME_PAGE, 'key_name': sponsor_id, 'link_id': sponsor_id, 'or... | Seeds a new sponsor entity.
Args:
sponsor_id: Identifier of the new sponsor.
Returns:
Newly seeded Sponsor entity. | 625941ec293b9510aa2c379a |
def db_link_tables(dataset: dict) -> None: <NEW_LINE> <INDENT> words_dataset = dataset[Word.__name__][0] <NEW_LINE> log.info("Start to link tables data") <NEW_LINE> db_link_authors(words_dataset) <NEW_LINE> db_link_complexes(words_dataset) <NEW_LINE> db_link_affixes(words_dataset) <NEW_LINE> db_link_keys() <NEW_LINE> l... | Link existing data between tables. For example,
connect Word objects with Author object(s)
connect primitives with their complexes (Word with Word)
connect primitives with their affixes (Word with Word)
connect Definitions object with their Key object(s)
These links locate in according tables, like
... | 625941ecde87d2750b8602a1 |
def __repr__(self): <NEW_LINE> <INDENT> return 'Heap([{0}])'.format(','.join(str(item) for item in self)) | A string representation of this heap
:return: | 625941ec56b00c62f0f14b66 |
def _record_title_info(self, title, title_leve): <NEW_LINE> <INDENT> if len(title) > 0 and (title_leve >= 1 and title_leve <= 6): <NEW_LINE> <INDENT> if len(title.strip()) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> title_dic = {'title': title, 'level': title_leve} <NEW_LINE> self.title_info.append(title_... | 记录找到的标题信息
每调用一次记录一行传递过来的标题信息到self.toc列表中
:param title: str
标题内容,未过滤处理
:param title_leve: int
标题级别,范围[1, 6]
:return: None | 625941ec66673b3332b9259a |
def __init__(self, incoming_road_lane_by_coord: Dict[Coord, RoadLane], outgoing_road_lane_by_coord: Dict[Coord, RoadLane], lanes: Tuple[IntersectionLane, ...], lanes_by_endpoints: Dict[Tuple[Coord, Coord], IntersectionLane], tiling_type: Type[Tiling], tiling_spec: Dict[str, Any], misc_spec: Dict[str, Any] = {} ) -> Non... | Create a new traffic signal intersection manager. | 625941ecc4546d3d9de72f42 |
def _iter_supp(self): <NEW_LINE> <INDENT> return self._get_json_pile(self.fn[1], SuppEntry) | Iterate over SupplementalRecord entries. | 625941ecf9cc0f698b140b00 |
def categories_learn_post_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = ['body'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = local... | Improve transaction categorization # noqa: E501
Your customers can change the category of some of their transactions, thus improving the categorization accuracy. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.ca... | 625941ec85dfad0860c3b365 |
def average(self, select_f=None): <NEW_LINE> <INDENT> return self.select(select_f).sum() / float(self.count()) | Return average of ``select_f(item)``.
>>> Linq([1, 2, 3, 4, 5]).average()
3.0
>>> persons = Linq([
... {'name': 'yassu', 'age': 25},
... {'name': 'person2', 'age': 3}
... ])
>>> persons.average(select_f=lambda x: x['age'])
14.0 | 625941ec099cdd3c635f1162 |
def __init__(self, queue, config): <NEW_LINE> <INDENT> nine_config = config["ninepicture"] <NEW_LINE> super(NineBuilder, self).__init__(queue, nine_config, selector=NineSelector, picture_info=NinePictureInfo) <NEW_LINE> self.nrow = self.config["nrow"] <NEW_LINE> self.ncol = self.config["ncol"] <NEW_LINE> se... | embedding word selector into builder, setting default porperties | 625941ec9b70327d1c4e12e1 |
def build_defconfig(self): <NEW_LINE> <INDENT> self.log.info('making defconfig: ' + self.kernel.defconfig) <NEW_LINE> self.kernel.make_defconfig() | Build a defconfig. | 625941ec8e71fb1e9831dcb0 |
def arithmetic(self, poly, out_raster, raster_or_constant, operation=RASTER_MULTIPLY, envelope=False, imageSR='', **kwargs): <NEW_LINE> <INDENT> ren = { "rasterFunction" : "Arithmetic", "rasterFunctionArguments" : { "Raster" : "$$", "Raster2": raster_or_constant, "Operation" : operation } } <NEW_LINE> self.exportImage(... | perform arithmetic operations against a raster
Required:
poly -- input polygon or JSON polygon object
out_raster -- full path to output raster
raster_or_constant -- raster to perform opertion against or constant value
Optional:
operation -- arithmetic operation to use, default is multiply (3) all opti... | 625941ec0c0af96317bb86f1 |
def test_generate_history(self): <NEW_LINE> <INDENT> sb = History() <NEW_LINE> sb.player_guesses.append([1, 2, 3, 4]) <NEW_LINE> sb.player_scores.append({"correct_colors": 1, "correct_positions": 3}) <NEW_LINE> res = sb.generate_history() <NEW_LINE> self.assertTrue(len(res), 1) <NEW_LINE> sb.player_guesses.append([5, 6... | Test test_generate_history() for correct return values. | 625941ec21bff66bcd684e57 |
def world_to_pixel(self, x, y): <NEW_LINE> <INDENT> return world_to_pixel(self.get_geotransform(), x, y) | Transform world to pixel coordinates
:param x:
:param y:
:return: pixel coordinates of (x, y)
:rtype: list of int | 625941ecbf627c535bc136d9 |
def set_ClientSecret(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ClientSecret', value) | Set the value of the ClientSecret input for this Choreo. ((required, string) The Client Secret provided by Foursquare after registering your application.) | 625941ec4c3428357757c82e |
def store(self): <NEW_LINE> <INDENT> open(self.path, 'wb').write(self.key) | store currently active key into file at self.path | 625941ec8c0ade5d55d3eec9 |
def isPast(): <NEW_LINE> <INDENT> pass | Return true if this object represents a date/time earlier
than the time of the call | 625941ec50812a4eaa59c826 |
def max_depth(self, root: Optional[TreeNode]) -> int: <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> q, depth = deque([root]), 0 <NEW_LINE> while q: <NEW_LINE> <INDENT> depth += 1 <NEW_LINE> for _ in range(len(q)): <NEW_LINE> <INDENT> node = q.popleft() <NEW_LINE> if node.left: <NEW_L... | 解法二:迭代(BFS版本)
时间复杂度:O(n)
空间复杂度:O(n)
:param root: TreeNode, the root of the binary tree
:return: the maximum depth of the binary tree | 625941ec596a897236089fc3 |
def store(self, payload): <NEW_LINE> <INDENT> raise NotImplementedError("PayloadDispatcher failed to implement store method") | Send payload to persistence layer. | 625941ec97e22403b379d4a5 |
def validate(self): <NEW_LINE> <INDENT> self.validate_chaste() <NEW_LINE> self.validate_max_n() <NEW_LINE> self.validate_avg_base_quality() <NEW_LINE> self.validate_min_base_quality() <NEW_LINE> return self | Validate all attributes. Overrides parent method. | 625941ec656771135c3ebd7e |
def get_spot_price_triggered_order(self, order_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_spot_price_triggered_order_with_http_info(order_id, **kwargs) | Get a single order # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_spot_price_triggered_order(order_id, async_req=True)
>>> result = thread.get()
:param bool async_req: execute request asynchronously
:param st... | 625941ecadb09d7d5db6cc96 |
def test_create_search_space(): <NEW_LINE> <INDENT> from random import random <NEW_LINE> from tensorflow.keras.utils import plot_model <NEW_LINE> import tensorflow as tf <NEW_LINE> search_space = create_search_space() <NEW_LINE> ops = [0, 13, 7, 0, 0] <NEW_LINE> print(f"This search_space needs {len(ops)} choices to gen... | Generate a random neural network from the search_space definition.
| 625941ec50485f2cf553d2a5 |
def __str__(self): <NEW_LINE> <INDENT> if six.PY2: <NEW_LINE> <INDENT> return self.__unicode__().encode('utf-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__unicode__() | get an xml string representation | 625941ecfbf16365ca6f66d8 |
def __init__(self, pos=np.zeros(2, dtype=np.float32), rot_theata=0.0): <NEW_LINE> <INDENT> self.logger = logging.getLogger(__name__) <NEW_LINE> self.logger.setLevel(logging.WARNING) <NEW_LINE> super().__init__(pos, r=my_car_obj.radius) <NEW_LINE> self.rot_theata = rot_theata <NEW_LINE> self.ray = np.empty((2,my_car_obj... | 第1引数 2つの要素を持つnumpyの配列。円の中心の座標 | 625941ec7d43ff24873a31ae |
def momentum_density(u): <NEW_LINE> <INDENT> return abs(u)**2 / (4*np.pi) | Radial momentum distribution
FIXME: this assumes 1s wavefunction
Parameters:
u: radial momentum-space wavefunction | 625941ecd58c6744b4258167 |
def set_RefreshToken(self, value): <NEW_LINE> <INDENT> super(DeleteDiskInputSet, self)._set_input('RefreshToken', value) | Set the value of the RefreshToken input for this Choreo. ((conditional, string) An OAuth refresh token used to generate a new access token when the original token is expired. Required unless providing a valid AccessToken.) | 625941ecec188e330fd5ac9e |
def __init__(self, table_data, title=None): <NEW_LINE> <INDENT> self.table_data = table_data <NEW_LINE> self.title = title <NEW_LINE> self.inner_column_border = True <NEW_LINE> self.inner_footing_row_border = False <NEW_LINE> self.inner_heading_row_border = True <NEW_LINE> self.inner_row_border = False <NEW_LINE> self.... | Constructor.
:param iter table_data: List (empty or list of lists of strings) representing the table.
:param title: Optional title to show within the top border of the table. | 625941eccc0a2c11143dd39b |
def commit_rheader(r): <NEW_LINE> <INDENT> if r.representation == "html": <NEW_LINE> <INDENT> record = r.record <NEW_LINE> if record and r.name == "commit": <NEW_LINE> <INDENT> s3_date_represent = s3base.S3DateTime.date_represent <NEW_LINE> tabs = [(T("Edit Details"), None)] <NEW_LINE> type = record.type and int(record... | Resource Header for Commitments | 625941ec442bda511e8be91a |
def __init__(self, connection_pool, worker_id, topic, processing_queue): <NEW_LINE> <INDENT> self.topic = topic <NEW_LINE> self.processing_queue = processing_queue <NEW_LINE> self.r = _connect_to_redis(connection_pool) <NEW_LINE> self.worker_id = worker_id | message format timestamp(unix epoch);message
Args:
connection_pool: explicit connection pool to use
topic: topic of messages
processing_queue: temporary queue for messages which are in processing | 625941eccc40096d61595e58 |
def __init__(self, xml_path): <NEW_LINE> <INDENT> self.race_types = [] <NEW_LINE> self.race_times = [] <NEW_LINE> self.segments = [] <NEW_LINE> self.segments_lookup = {} <NEW_LINE> self.reference_race = None <NEW_LINE> self.segments_paces = [] <NEW_LINE> self.plan_instructions = [] <NEW_LINE> root = ET.parse(source=xml... | Constructor
:param xml_path: path to xml database
:type xml_path: str
:return: instance of FirstData
:rtype: FirstData | 625941ec26238365f5f0f37f |
def test_additional_rice_post_processor(self): <NEW_LINE> <INDENT> impact_layer = load_test_vector_layer( 'impact', 'indivisible_polygon_impact.geojson', clone_to_memory=True) <NEW_LINE> self.assertIsNotNone(impact_layer) <NEW_LINE> result, message = run_single_post_processor( impact_layer, post_processor_female) <NEW_... | Test weekly hygiene post processor. | 625941ec6e29344779a62b1a |
def configure(config_path=_CONFIG_PATH, key = _CONSUL_KEY): <NEW_LINE> <INDENT> from cloudify.exceptions import NonRecoverableError <NEW_LINE> try: <NEW_LINE> <INDENT> import configparser <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> import ConfigParser as configparser <NEW_LINE> <DEDENT> from k8splugin i... | Get configuration information from local file and Consul.
Note that the Cloudify context ("ctx") isn't available at
module load time. | 625941ec656771135c3ebd7f |
def exportAttr(self, data): <NEW_LINE> <INDENT> return data | By default do nothing, but expect that this function could be overwritten | 625941ec30c21e258bdfa9ad |
def response(self, mode=1): <NEW_LINE> <INDENT> if mode: <NEW_LINE> <INDENT> self.__check_response_before() <NEW_LINE> self.push_cookies() <NEW_LINE> self.__check_response_after() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.push_cookies() <NEW_LINE> <DEDENT> self.__track() <NEW_LINE> return self.__response | 返回一个response,该过程中会
有两个模式:
1 带返回前判断和返回后判断。
其他 不判断直接返回
:param mode:
:return: | 625941ec55399d3f05588bc1 |
def render(self, cr, uid, id, object, reference, currency, amount, context=None, **kwargs): <NEW_LINE> <INDENT> if not isinstance(id, (int,long)): <NEW_LINE> <INDENT> id = id[0] <NEW_LINE> <DEDENT> this = self.browse(cr, uid, id) <NEW_LINE> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> try: <... | Renders the form template of the given acquirer as a mako template | 625941ec046cf37aa974d24c |
def __SetSensorTemperatureSetPoint(self,temperature): <NEW_LINE> <INDENT> param_name = "PicamParameter_SensorTemperatureSetPoint" <NEW_LINE> return self.set_parameter(parameter_name=param_name,parameter_value=temperature) | Do not use this method if you want to wait for temperature to stabilize, use SetTemperatureWithLock | 625941ec8da39b475bd65484 |
def __init__(self,popSize=200,offspringPopSize=50,mutOffspring=50, mutBit=25,indivWorld="world1.txt"): <NEW_LINE> <INDENT> print ("Initializing Genetic Algorithm...",) <NEW_LINE> self.population = [Individual(indivWorld) for i in range(popSize)] <NEW_LINE> self.__popSize = popSize <NEW_LINE> self.__offs... | Create a new GA population simulation. popSize=Size of population,
offspringPopSize=Size of offspring population,mutOffspring=Percent
of offspring to mutate,mutBit=Percent of genes to mutate during
mutation,indivWorld=Name of txt file that contains world data. | 625941ec5fdd1c0f98dc073f |
def get_vovnet(blocks, slim=False, model_name=None, pretrained=False, root=os.path.join("~", ".tensorflow", "models"), **kwargs): <NEW_LINE> <INDENT> if blocks == 27: <NEW_LINE> <INDENT> layers = [1, 1, 1, 1] <NEW_LINE> <DEDENT> elif blocks == 39: <NEW_LINE> <INDENT> layers = [1, 1, 2, 2] <NEW_LINE> <DEDENT> elif block... | Create ResNet model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
slim : bool, default False
Whether to use a slim model.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained wei... | 625941eccdde0d52a9e53541 |
def move(self, distance): <NEW_LINE> <INDENT> return f"{self.animal_type} {self.way_of_moving}s {distance} meters" | Moves the mammal by a certain distance.
Args:
distance (int): the distance in meters
Returns:
str: a sentence describing the mammal's movement | 625941ec097d151d1a223361 |
def parse_configuration_and_cli( self, cfg: configparser.RawConfigParser, cfg_dir: str, argv: List[str], ) -> None: <NEW_LINE> <INDENT> assert self.option_manager is not None <NEW_LINE> assert self.plugins is not None <NEW_LINE> self.options = aggregator.aggregate_options( self.option_manager, cfg, cfg_dir, argv, ) <NE... | Parse configuration files and the CLI options. | 625941ecd58c6744b4258168 |
def __init__(self, viewer): <NEW_LINE> <INDENT> self.viewer = viewer <NEW_LINE> self.logger = viewer.get_logger() <NEW_LINE> self.limit_cutout = 5000 | Constructor for a ViewerImageProxy object.
Parameters
----------
viewer : `~ginga.ImageView` (or subclass thereof)
Ginga viewer object | 625941ec57b8e32f524839a8 |
def _build_url(self, path): <NEW_LINE> <INDENT> if absolute_http_url_regexp.match(path): <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f"{self.base_url}{path}" | prepend url with hostname unless it's already an absolute URL | 625941ecb5575c28eb68e50f |
def test_demo_create_success(self): <NEW_LINE> <INDENT> demo_name = datetime.now().isoformat("T") <NEW_LINE> demo = demo_service.create_demo(demo_name) <NEW_LINE> demo_json = loads(demo) <NEW_LINE> self.assertTrue(demo_json.get('id')) <NEW_LINE> self.assertTrue(demo_json.get('guid')) <NEW_LINE> self.assertTrue(demo_jso... | With correct values, is a valid demo returned? | 625941ec796e427e537b0ad4 |
def wait_for_publishers(self): <NEW_LINE> <INDENT> r = rospy.Rate(10) <NEW_LINE> while not rospy.is_shutdown(): <NEW_LINE> <INDENT> if self._subscriber.get_num_connections() != 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r.sleep() <NEW_LINE> <DEDENT> <DEDENT> raise rospy.exceptions.ROSIn... | Blocks until publishers are seen.
@raise rospy.exceptions.ROSInterruptException if we are in shutdown. | 625941ecd53ae8145f87a770 |
def test_cylinder_area_of_base(self): <NEW_LINE> <INDENT> cylinder = Cylinder(radius=2, height=7) <NEW_LINE> area = cylinder.area_of_base() <NEW_LINE> self.assertAlmostEqual(area, 12.6, places=1) | Test that we can calculate the area of a cylinder's base | 625941ecbe8e80087fb21145 |
def creditplan_delete_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ 'id', 'body' ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iteritems(local_var_params['... | Deletes a credit plan # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.creditplan_delete_with_http_info(id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str... | 625941ec1f5feb6acb0c5053 |
def make_proc_atom(atomDict, eqivDict, xyzDict, gij, UijDict, sUijDict): <NEW_LINE> <INDENT> def proc_atom(atName): <NEW_LINE> <INDENT> if atName not in atomDict.keys(): <NEW_LINE> <INDENT> atomDict[atName] = atom_lib.Atom(atName, eqivDict, xyzDict, gij, UijDict, sUijDict) <NEW_LINE> <DEDENT> return atomDict[atName] <N... | This is a closure to lock in all the dict names so they don't have
to be passed as arguments every time you process an atom. | 625941ec01c39578d7e75345 |
def __init__(self): <NEW_LINE> <INDENT> self.InstanceId = None | :param InstanceId: 实例ID,格式如:mssql-c1nl9rpv或者mssqlro-c1nl9rpv,与云数据库控制台页面中显示的实例ID相同。
:type InstanceId: str | 625941ec0383005118ecfaeb |
def randoutput(self, input_p = None): <NEW_LINE> <INDENT> if input_p is None: <NEW_LINE> <INDENT> input_p = uniform_p(self.n_inputs()) <NEW_LINE> <DEDENT> input_ = np.random.choice(range(self.n_inputs()), p=input_p) <NEW_LINE> return np.random.choice(range(self.n_outputs()), p=self.matrix[input_, :]) | Returns a randomly-chosen output (as a column index) the system
chooses when responding to a specific randomly-chosen input (the probability
distribution over the inputs can be given as an argument, but by default it is
uniform). | 625941ecb7558d58953c5413 |
def __parse_trailer(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> line = self.__get_next_line() <NEW_LINE> if line and line.token != TOKEN_TRLR: <NEW_LINE> <INDENT> state = CurrentState() <NEW_LINE> self.__not_recognized(line, 0, state) <NEW_LINE> self.__check_msgs(_("TRLR (trailer)"), state, None) <NEW_LINE> <DE... | Looks for the expected TRLR token | 625941ec4c3428357757c82f |
def add_config(self, name, value): <NEW_LINE> <INDENT> self.add_config_dict[name] = value | Append value to configuration entry.
Requires broker version with KIP-248 support and alter_configs(.., incremental=True).
:param str name: Configuration property name
:param str value: Configuration value | 625941ec57b8e32f524839a9 |
def __get_optimal_scaling(self, q, includeAll=False): <NEW_LINE> <INDENT> if self.printInfo: print('FluidVisualiser: Finding optimal scaling ...') <NEW_LINE> q_max = [np.max(q())] <NEW_LINE> q_min = [np.min(q())] <NEW_LINE> skips = self.Nt//100 <NEW_LINE> if skips == 0: skips = 1 <NEW_LINE> for i in range(1, self.Nt, s... | Advances the simulation a given time and examines
the resulting values of a given quantity to determine the
optimal limit values to use in the animation. The simulation
is then reset. | 625941ec97e22403b379d4a6 |
def test_nexus_extended_vlan_range_failure(self): <NEW_LINE> <INDENT> def mock_edit_config_a(target, config): <NEW_LINE> <INDENT> if all(word in config for word in ['state', 'active']): <NEW_LINE> <INDENT> raise Exception("Can't modify state for extended") <NEW_LINE> <DEDENT> <DEDENT> with self._patch_ncclient( 'manage... | Test that extended VLAN range config errors are ignored.
Some versions of Nexus switch do not allow state changes for
the extended VLAN range (1006-4094), but these errors can be
ignored (default values are appropriate). Test that such errors
are ignored by the Nexus plugin. | 625941ec7cff6e4e81117e90 |
def parse(self, part, index): <NEW_LINE> <INDENT> if index == 0: <NEW_LINE> <INDENT> if part == 'x': <NEW_LINE> <INDENT> self.complete = True <NEW_LINE> <DEDENT> elif re.search(self._PRIORITY_REGEX, part): <NEW_LINE> <INDENT> self.priority = part[1] <NEW_LINE> <DEDENT> elif re.search(self._DATE_REGEX, part): <NEW_LINE>... | Parse each single part of the text line. | 625941ece1aae11d1e74a1c7 |
def end(self): <NEW_LINE> <INDENT> return f"</{self._name}>" | Closes the XML element. | 625941ec3346ee7daa2b327a |
def find_best_options(self, url_option): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.driver.get(url_option) <NEW_LINE> time.sleep(2) <NEW_LINE> _begin_day = True <NEW_LINE> _table_options = self.driver.find_element_by_id('options-table').text <NEW_LINE> _max_business = 0 <NEW_LINE> _best_option = '' <NEW_LINE> fo... | :param _option:
:param _type:
:return: | 625941ec5f7d997b87174fa7 |
def gens(endpoint, values): <NEW_LINE> <INDENT> if self._enabled and ((endpoint, values) not in self.calls): <NEW_LINE> <INDENT> self.calls.append((endpoint, values.copy())) | url processors can automatically inject values into a call for url_for() automatically.
http://flask.pocoo.org/docs/0.11/patterns/urlprocessors/ | 625941ec56ac1b37e62646cf |
def policySpecificChecks(self, upload): <NEW_LINE> <INDENT> pass | Nothing, let it go. | 625941ecf8510a7c17cf9c0a |
def extension_available(extension): <NEW_LINE> <INDENT> def test_wrapper(test): <NEW_LINE> <INDENT> @functools.wraps(test) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> from . import extensions <NEW_LINE> if extension in extensions(): <NEW_LINE> <INDENT> return test(*args, **kwargs) <NEW_LINE> <DEDENT> e... | Decorator to check if a extension is available before enabling a test | 625941ecfff4ab517eb2f94a |
def test_group_start_end_by_weekday(self): <NEW_LINE> <INDENT> fake_data = { datetime.date(2019, 3, 4): { 'start': datetime.time(9, 0, 0), 'end': datetime.time(17, 30, 0), }, datetime.date(2019, 3, 5): { 'start': datetime.time(8, 30, 0), 'end': datetime.time(16, 45, 0), }, datetime.date(2019, 3, 11): { 'start': datetim... | Test assigning mean start and end time to weekdays. | 625941ec38b623060ff0b2f7 |
def initialize_parameters(self, n_x, n_h, n_y): <NEW_LINE> <INDENT> np.random.seed(2) <NEW_LINE> W1 = np.random.randn(n_h,n_x) * 0.01 <NEW_LINE> b1 = np.zeros((n_h,1)) <NEW_LINE> W2 = np.random.randn(n_y,n_h) * 0.01 <NEW_LINE> b2 = np.zeros((n_y,1)) <NEW_LINE> assert (W1.shape == (n_h, n_x)) <NEW_LINE> assert (b1.shape... | 初始化参数 | 625941ecd10714528d6001f3 |
@courses.route("/course/<int:cid>/<string:uid>", methods=["POST"]) <NEW_LINE> @authorize <NEW_LINE> def rating_create(cid, uid) -> Tuple[str, int]: <NEW_LINE> <INDENT> params = request.form <NEW_LINE> quality = params.get("quality") <NEW_LINE> difficulty = params.get("difficulty") <NEW_LINE> time_spent = params.get("ti... | Creates rows in various metric tables
:return: | 625941ec99cbb53fe67930ef |
def random_index(self, start=0, end=-1): <NEW_LINE> <INDENT> count = len(self) <NEW_LINE> if not count: <NEW_LINE> <INDENT> raise IndexError('no items to choose from') <NEW_LINE> <DEDENT> if start < 0: <NEW_LINE> <INDENT> start += count <NEW_LINE> <DEDENT> if end < 0: <NEW_LINE> <INDENT> end += count <NEW_LINE> <DEDENT... | Return a random index. | 625941ec3346ee7daa2b327b |
def forward(self, x_tilde, y, w): <NEW_LINE> <INDENT> y = y + self.sigma * self.forward_grad.forward(x_tilde, w) <NEW_LINE> return y | :param x_tilde: PyTorch Variable, [1xMxN]
:param y: PyTorch Variable, [2xMxN]
:param w: PyTorch Variable, [2xMxN]
:return: PyTorch Variable, [2xMxN] | 625941ecd8ef3951e3243a48 |
def load(self): <NEW_LINE> <INDENT> x = XmlTester(Util.GETPATH("../xsd")) <NEW_LINE> ok = False <NEW_LINE> if (os.path.exists(self.path)): <NEW_LINE> <INDENT> ok, doc, errors = x.checkIsReports(self.path) <NEW_LINE> if not ok: <NEW_LINE> <INDENT> print("old file is invalid! " + str(errors)) <NEW_LINE> <DEDENT> <DEDENT>... | loads old reports from xml file
first checks via XSD if the old file is valid
if not, it is backed up and a new one is created | 625941ec0c0af96317bb86f2 |
def get_empirical_semivariogram(X, Y, Z, max_distance, bandwidth): <NEW_LINE> <INDENT> if np.issubdtype(X.dtype, np.datetime64): <NEW_LINE> <INDENT> assert len(X.shape) == 1, "dimension for dtype array greater than 1 not supported" <NEW_LINE> T0 = X[0] <NEW_LINE> X = np.array(X - T0, dtype=(float)) / (1e9 * 60 * 60 * 2... | Experimental variogram for a collection of lags | 625941ecdc8b845886cb5a41 |
def xl_rowcol_to_cell_fast(row, col): <NEW_LINE> <INDENT> if col in COL_NAMES: <NEW_LINE> <INDENT> col_str = COL_NAMES[col] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> col_str = xl_col_to_name(col) <NEW_LINE> COL_NAMES[col] = col_str <NEW_LINE> <DEDENT> return col_str + str(row + 1) | Optimised version of the xl_rowcol_to_cell function. Only used internally.
Args:
row: The cell row. Int.
col: The cell column. Int.
Returns:
A1 style string. | 625941ec66656f66f7cbc6b7 |
def inverse_ewma(self): <NEW_LINE> <INDENT> if self.ewma is None: <NEW_LINE> <INDENT> raise ValueError("EWMA was not calculated for te given df") <NEW_LINE> <DEDENT> ewma_values = self.ewma.values <NEW_LINE> columns = self.ewma.columns <NEW_LINE> def apply_inverse(ewma_values): <NEW_LINE> <INDENT> inversed_ewma = np.ze... | Find the original df from the ewma_df
Returns
--------
inversed_ewma: ndarray | 625941ec287bf620b61d3f6b |
def close(self): <NEW_LINE> <INDENT> raise OSError("Simulated I/O problem") | If the raise_counter is set high enough, all data can be read.
In this case closing the stream will raise the OSError instead. | 625941eca219f33f34628e6c |
def zip_entry_rollup(zipfile): <NEW_LINE> <INDENT> files = dirs = 0 <NEW_LINE> total_c = total_u = 0 <NEW_LINE> for i in zipfile.infolist(): <NEW_LINE> <INDENT> if i.filename[-1] == '/': <NEW_LINE> <INDENT> dirs += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> files += 1 <NEW_LINE> total_c += i.compress_size <NEW_LIN... | returns a tuple of (files, dirs, size_uncompressed,
size_compressed). files+dirs will equal len(zipfile.infolist) | 625941ecd7e4931a7ee9e42a |
def _decode_step(self, sequences: mx.nd.NDArray, t: int, source_length: int, max_output_length: int, states: List[ModelState], models_output_layer_w: List[mx.nd.NDArray], models_output_layer_b: List[mx.nd.NDArray]) -> Tuple[mx.nd.NDArray, mx.nd.NDArray, List[ModelState]]: <NEW_LINE> <INDENT> bucket_key = (so... | Returns decoder predictions (combined from all models), attention scores, and updated states.
:param sequences: Sequences of current hypotheses. Shape: (batch_size * beam_size, max_output_length).
:param t: Beam search iteration.
:param source_length: Length of the input sequence.
:param max_output_length: Maximum out... | 625941ecf8510a7c17cf9c0b |
def _resolve_doc_or_fig_url( self, doc_or_fig_obj, src_records=(), only_new=False, ): <NEW_LINE> <INDENT> doc_or_fig_obj = deepcopy(doc_or_fig_obj) <NEW_LINE> key = doc_or_fig_obj['key'] <NEW_LINE> src_record_file = next( ( rec.files[key].file.uri for rec in src_records if key in rec.files ), None, ) <NEW_LINE> def _sh... | Resolves the given document url according to the current record.
It will fill it up with the local url in case it's found in the given
src_records.
Returns:
dict: with the medatada of the given ``doc_or_fig_obj`` updated as
follows:
* In the case it has to be downloaded: the url is set to
... | 625941ecd164cc617578325a |
@api.route('/delete', methods=['POST']) <NEW_LINE> @resource.require_oauth('agentstats') <NEW_LINE> @perms.require_perm('agentstats', 'edit_agent') <NEW_LINE> def delete_account(): <NEW_LINE> <INDENT> params = { 'account_number': fields.Integer(required=True) } <NEW_LINE> json_data = parser.parse(params) <NEW_LINE> que... | Delete an account
:return: | 625941ec4428ac0f6e5bad01 |
def get_longitude(self, **kwargs): <NEW_LINE> <INDENT> keys = [ 'download', 'environment', 'location', 'lon' ] <NEW_LINE> return self._get_nested_dict(self.tests, keys) | Returns 'longitude' value from download test environment location data | 625941ec10dbd63aa1bd30ad |
def prompt(self): <NEW_LINE> <INDENT> isreading = self.reader.isreading <NEW_LINE> skip = False <NEW_LINE> if isreading: <NEW_LINE> <INDENT> prompt = str(sys.ps3) <NEW_LINE> <DEDENT> elif self.more: <NEW_LINE> <INDENT> prompt = str(sys.ps2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prompt = str(sys.ps1) <NEW_LINE> ... | Display proper prompt for the context: ps1, ps2 or ps3.
If this is a continuation line, autoindent as necessary. | 625941ec8a349b6b435e867d |
def get_user_token(): <NEW_LINE> <INDENT> if not hasattr(stack.top, 'current_user'): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> current_user = stack.top.current_user <NEW_LINE> return current_user.get('token', '') | Return the authenticated user's auth token | 625941ec2eb69b55b151cdc2 |
def test_insert_content(self): <NEW_LINE> <INDENT> self.request.path = "/non_ascii_request/" <NEW_LINE> response = self.panel.process_request(self.request) <NEW_LINE> self.assertNotIn("nôt åscíì", self.panel.content) <NEW_LINE> self.panel.generate_stats(self.request, response) <NEW_LINE> content = self.panel.content <N... | Test that the panel only inserts content after generate_stats and
not the process_request. | 625941ec5166f23b2e1a5664 |
def name(self): <NEW_LINE> <INDENT> return 'createnetworknodes' | Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters. | 625941ec498bea3a759b9fb8 |
def __init__(self, ecu_id, sim_env, ecu_authenticator, monitor_lst=[], jitter=1): <NEW_LINE> <INDENT> self.sim_env = sim_env <NEW_LINE> self.ecu_id = ecu_id <NEW_LINE> self._sync = simpy.Store(self.sim_env, capacity=1) <NEW_LINE> self.comm_mod = None <NEW_LINE> self.ecu_auth = ecu_authenticator <NEW_LINE> self.session_... | Constructor
Input: ecu_id string id of the corresponding AbstractECU
sim_env simpy.Environment environment of this component
ecu_authenticator ECUAuthenticator ECUAuthenticator that was ran before the Stream authorization
mon... | 625941ec3d592f4c4ed1d56a |
def __init__( self, name=None, sleep=None, interval=None, max_rps=None, calculate=None, db=None, ): <NEW_LINE> <INDENT> self.updates = 0 <NEW_LINE> self.sum_updates = 0 <NEW_LINE> self.date_last_modified = None <NEW_LINE> self.db = db or DB() <NEW_LINE> self.name = name or self.DEF_NAME <NEW_LINE> if sleep is None: <NE... | :param name: throttle name, used for storage
:param sleep: sleep value
:param interval: storage update interval
:param max_rps: limit requests / second
:param calculate: method to calculate sleep value
:return: | 625941ecb7558d58953c5414 |
def MfRhoIDeriv(self, u, v, adjoint=False): <NEW_LINE> <INDENT> dMfRhoI_dI = -self.MfRhoI**2 <NEW_LINE> if self.storeInnerProduct: <NEW_LINE> <INDENT> if adjoint: <NEW_LINE> <INDENT> return self.MfRhoDerivMat.T * ( Utils.sdiag(u) * (dMfRhoI_dI.T * v) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dMfRhoI_dI * (... | Derivative of :code:`MfRhoI` with respect to the model. | 625941ec16aa5153ce362983 |
def process_request(self, request, spider): <NEW_LINE> <INDENT> fake = faker.Faker() <NEW_LINE> request.headers.update({ 'user-agent': fake.user_agent(), 'origin': 'https://www.lagou.com', 'referer': 'https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=', }) <NEW_LINE> return None | 可以拿到请求体 | 625941ec7b180e01f3dc4cfd |
def sample(f, coordinates, boundary_mode='edge'): <NEW_LINE> <INDENT> assert isinstance(f, (ScalarFunction, VectorField)) and isinstance(coordinates, VectorField) <NEW_LINE> assert f.dim == coordinates.dim <NEW_LINE> coordinates = np.einsum("...i->i...", coordinates.to_numpy()) <NEW_LINE> if isinstance(f, VectorField):... | Function to sample a given `ScalarFunction` or `VectorField` at given coordinates.
Remark: The coordinates at which to sample have to be givenas a `VectorField`.
Parameters
----------
f
`ScalarFunction` or `VectorField` to transform.
coordinates
`VectorField` containing the coordinates to sample at.
Returns
... | 625941ec435de62698dfe158 |
def get_years(ddate): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> years = [x for x in os.listdir(ddate) if is_year(x)] <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> years = [] <NEW_LINE> <DEDENT> return years | trova elenco anni definiti | 625941ec63b5f9789fde75f1 |
def lookup(self, row_labels, col_labels): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for row, col in zip(row_labels, col_labels): <NEW_LINE> <INDENT> data.append(self.get_value(row, col)) <NEW_LINE> <DEDENT> types = set([type(x) for x in data]) <NEW_LINE> out = None <NEW_LINE> if len(types) == 1: <NEW_LINE> <INDENT> try:... | Retrieve values indicated by row_labels, col_labels positions | 625941ece64d504609d74d4b |
def add_point(chart_id, x_coord, y_coord): <NEW_LINE> <INDENT> if not type(chart_id) is str: <NEW_LINE> <INDENT> return message("Python function add_point called with wrong chart_id " "type.") <NEW_LINE> <DEDENT> if chart_id == "": <NEW_LINE> <INDENT> return message("Python function add_point called with empty chart_id... | Create message that adds point to graph in dashboard | 625941eca17c0f6771cbe55a |
def build(self, session=None): <NEW_LINE> <INDENT> if not session: <NEW_LINE> <INDENT> if not self.server: <NEW_LINE> <INDENT> raise exc.TmuxpException( 'WorkspaceBuilder.build requires server to be passed ' + 'on initialization, or pass in session object to here.' ) <NEW_LINE> <DEDENT> if self.server.has_session(self.... | Build tmux workspace in session.
Optionally accepts ``session`` to build with only session object.
Without ``session``, it will use :class:`Server` at ``self.server``
passed in on initialization to create a new Session object.
:param session: - session to build workspace in
:type session: :class:`Session` | 625941ec8e05c05ec3eea884 |
def _write_permutations(permutations, out_stream): <NEW_LINE> <INDENT> for perm in permutations: <NEW_LINE> <INDENT> out_stream.write(">" + perm.chr_name + "\n") <NEW_LINE> for block in perm.blocks: <NEW_LINE> <INDENT> out_stream.write("{0:+} ".format(block.signed_id())) <NEW_LINE> <DEDENT> out_stream.write("$\n") | Outputs permutations | 625941ec498bea3a759b9fb9 |
def calculate(self, film, substrate, elasticity_tensor=None, film_millers=None, substrate_millers=None, ground_state_energy=0, lowest=False): <NEW_LINE> <INDENT> self.film = film <NEW_LINE> self.substrate = substrate <NEW_LINE> if film_millers is None: <NEW_LINE> <INDENT> film_millers = sorted(get_symmetrically_distinc... | Finds all topological matches for the substrate and calculates elastic
strain energy and total energy for the film if elasticity tensor and
ground state energy are provided:
Args:
film(Structure): conventional standard structure for the film
substrate(Structure): conventional standard structure for the
... | 625941ec94891a1f4081bfb7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.