code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@pytest.fixture <NEW_LINE> def single_rectangle_gdf(): <NEW_LINE> <INDENT> poly_inters = Polygon([(0, 0), (0, 10), (10, 10), (10, 0), (0, 0)]) <NEW_LINE> gdf = gpd.GeoDataFrame([1], geometry=[poly_inters], crs="epsg:4326") <NEW_LINE> gdf["attr2"] = "site-boundary" <NEW_LINE> return gdf
Create a single rectangle for clipping.
625941c4c4546d3d9de72a19
def import_tsv_as_phenotype_set_from_staging(self, params, context=None): <NEW_LINE> <INDENT> return self._client.run_job('kb_uploadmethods.import_tsv_as_phenotype_set_from_staging', [params], self._service_ver, context)
:param params: instance of type "FileToPhenotypeSetParams" (required params: staging_file_subdir_path: subdirectory file path e.g. for file: /data/bulk/user_name/file_name staging_file_subdir_path is file_name for file: /data/bulk/user_name/subdir_1/subdir_2/file_name staging_file_subdir_path is subdir_1...
625941c44428ac0f6e5ba7d8
def correct_velo_info(pv, overwrite=True): <NEW_LINE> <INDENT> if isinstance(pv, str): <NEW_LINE> <INDENT> pv_list = [pv] <NEW_LINE> <DEDENT> elif isinstance(pv, (list,tuple)): <NEW_LINE> <INDENT> pv_list = pv <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('Input needs to be a single FITS file or list of...
convert_velo_info: scale the velocity axis in pV diagrams ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CASA position-velocity diagrams are exported in m/s which is inconvenient because the tick labels get very long. This function converts the velocity axis to km/s by changing the header. !!! Note that ap...
625941c4d58c6744b4257c47
@pytest.mark.parametrize( argnames="command_def", argvalues=[ command_definitions.EquipmentCommand.load_labware, command_definitions.EquipmentCommand.load_pipette, command_definitions.PipetteCommand.aspirate, command_definitions.PipetteCommand.dispense, command_definitions.PipetteCommand.drop_tip, command_definitions.P...
Test creation of command requiring data will fail with empty body.
625941c450812a4eaa59c30a
def test_token_should_be_created(self): <NEW_LINE> <INDENT> email = fake.email() <NEW_LINE> form = forms.RegisterForm({ 'email': email }) <NEW_LINE> assert form.is_valid() <NEW_LINE> form.prepare_form() <NEW_LINE> assert form.token.user == form.user <NEW_LINE> assert form.token.is_valid()
With correct user.
625941c410dbd63aa1bd2b8b
def main( problem_number: int = Argument(..., min=0, max=1, help='Selects the problem to solve [0 or 1].'), n: int = Argument(..., help='Grid interval count.'), fv: bool = Option(False, help='Use finite volume discretization instead of finite elements.'), ): <NEW_LINE> <INDENT> rhss = [ExpressionFunction('10', 1), Expr...
Solves the Poisson equation in 1D using pyMOR's builtin discreization toolkit.
625941c471ff763f4b549670
def test_old_timestamp(self): <NEW_LINE> <INDENT> alarm_dict = {"tenantId": "0", "alarmDefinitionId": "0", "alarmId": "1", "alarmName": "test Alarm", "oldState": "OK", "newState": "ALARM", "stateChangeReason": "I am alarming!", "timestamp": 1375346830, "actionsEnabled": 1, "metrics": "cpu_util"} <NEW_LINE> alarm = self...
Should cause the alarm_ttl to fire log a warning and push to finished queue.
625941c4004d5f362079a31b
def process(self, device, results, log): <NEW_LINE> <INDENT> log.info('processing %s for device %s', self.name(), device.id) <NEW_LINE> getdata, tabledata = results <NEW_LINE> rm = self.relMap() <NEW_LINE> contentsTable = tabledata.get('jnxContentsTable') <NEW_LINE> containersTable = tabledata.get('jnxContainersTable')...
collect snmp information from this device
625941c4925a0f43d2549e5d
def do_nothing(self): <NEW_LINE> <INDENT> return self
TBD
625941c430c21e258bdfa483
def open_date_dlg(self): <NEW_LINE> <INDENT> self.custom_num_window = Tk.Toplevel() <NEW_LINE> self.custom_num_window.withdraw() <NEW_LINE> self.custom_num_window.title('{}: Date Selection'.format(self.title)) <NEW_LINE> self.custom_num_window.resizable(width=False, height=False) <NEW_LINE> frame = Tk.Frame(self.custom...
Open a popup for defining a range of dates
625941c4fbf16365ca6f61a8
def randomize(self): <NEW_LINE> <INDENT> coordinates = itertools.product(range(self.size), repeat=2) <NEW_LINE> return {coord : random.random()<0.3 for coord in coordinates}
Generate our map randomly. In the code below their is a 30% chance of a cell containing a wall.
625941c497e22403b379cf80
def enable_mocktime(self): <NEW_LINE> <INDENT> self.mocktime = 1524179366 + (201 * 1 * 60)
Enable mocktime for the script. mocktime may be needed for scripts that use the cached version of the blockchain. If the cached version of the blockchain is used without mocktime then the mempools will not sync due to IBD. For backwared compatibility of the python scripts with previous versions of the cache, this he...
625941c4de87d2750b85fd78
def decorator(cmd): <NEW_LINE> <INDENT> @main_entry_point_wrapper( argument_default=argparse.SUPPRESS, description=description, **kwargs ) <NEW_LINE> @wraps(cmd) <NEW_LINE> def wrap_analysis_main(argv, parser): <NEW_LINE> <INDENT> cmd_args = {} <NEW_LINE> parser.add_argument("soln_file") <NEW_LINE> cmd_parser = cmd_par...
decorator for analyse_main_wrapper
625941c450812a4eaa59c30b
def add_blank_episodes(): <NEW_LINE> <INDENT> partial_data = pd.read_csv('data/alsoagun_episode_data.csv').drop(columns=['Unnamed: 0']) <NEW_LINE> with open('data/episode_list.txt') as f: <NEW_LINE> <INDENT> episodes = [line.strip() for line in f] <NEW_LINE> <DEDENT> full_data = pd.DataFrame(episodes, columns=['episode...
Add all of the blank episodes to the .csv, i.e., those without bullets fired This is necessary since they aren't in the database (because there aren't any bullets) to be recorded. This also only affects the episode data .csv file; blank characters are not adjusted.
625941c415fb5d323cde0af5
def spider_idle(self): <NEW_LINE> <INDENT> self.schedule_next_request() <NEW_LINE> raise DontCloseSpider
Schedules a requests if available, otherwise waits, If there is no request available in the queue so it will not close the spider :return:
625941c4adb09d7d5db6c778
def speed(self, angle): <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> self.board.analog_write(self.pin_num, angle) <NEW_LINE> time.sleep(0.5)
舵机持续转动方法 :param angle: 舵机转动角度 :return:
625941c44d74a7450ccd41ab
def bridge_setdevicestatus( self, isgroup: str, deviceid: str, capids: list[str], values: list[str] ) -> dict[str, str]: <NEW_LINE> <INDENT> req = et.Element('DeviceStatus') <NEW_LINE> et.SubElement(req, 'IsGroupAction').text = isgroup <NEW_LINE> et.SubElement(req, 'DeviceID', available="YES").text = deviceid <NEW_LINE...
Set the status of the bridge's lights.
625941c4711fe17d82542356
def local_dir(self): <NEW_LINE> <INDENT> assert self._local_folder is not None <NEW_LINE> return "{}/{}/{}".format( self._local_folder, self.type.value, platform.machine(), )
Return the directory containing the downloaded artifact.
625941c4956e5f7376d70e55
def unload(self): <NEW_LINE> <INDENT> self.iface.databaseMenu().removeAction(self.action) <NEW_LINE> self.iface.removeWebToolBarIcon(self.action) <NEW_LINE> if Qgis.QGIS_VERSION_INT >= 31000 and self.help_action: <NEW_LINE> <INDENT> self.iface.pluginHelpMenu().removeAction(self.help_action) <NEW_LINE> del self.help_act...
Remove the plugin menu item and icon.
625941c4293b9510aa2c327f
def _test_settings(self, settings, **kwargs): <NEW_LINE> <INDENT> defaults = { 'ACQUIRER': None, 'ACQUIRER_URL': None, 'DEBUG': True, 'EXPIRATION_PERIOD': 'PT15M', 'CERTIFICATES': ['ideal_v3.cer'], 'LANGUAGE': 'nl', 'MERCHANT_ID': '', 'MERCHANT_RETURN_URL': '', 'PRIVATE_CERTIFICATE': 'cert.cer', 'PRIVATE_KEY_FILE': 'pr...
Performs tests to check if the provided ``settings`` object contains the values as provided as ``kwargs``. If an option is not provided in the ``kwargs``, the default is checked. :param settings: The :class:`Settings` object. :param kwargs: List of keyword arguments where they key is the config option, and the value t...
625941c45e10d32532c5ef0e
def post_refresh_uc_metadata_cache(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.post_refresh_uc_metadata_cache_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.post_refresh_uc_metad...
Refresh the uc metadata cache # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_refresh_uc_metadata_cache(async_req=True) >>> result = thread.get() :param async_req bool :return: None If the method is ...
625941c4283ffb24f3c558ea
def getCurrentPlayer(self): <NEW_LINE> <INDENT> return self.currPlayer
Returns the player whose turn is next.
625941c4a05bb46b383ec80b
def qbox_level2(self): <NEW_LINE> <INDENT> idx = self.SetBox.currentIndex() <NEW_LINE> idx = 0 if idx == -1 else idx <NEW_LINE> self.SetBox.clear() <NEW_LINE> subs_sel = True if self.VarBox.currentIndex() == 0 else False <NEW_LINE> self.SetBox.addItems(['Set {}'.format(i + 1) for i in range(len(self.reac_data.AllVar[su...
Display changes stage 2
625941c4e8904600ed9f1f12
def getRowCount(self): <NEW_LINE> <INDENT> rowCount = c_int() <NEW_LINE> result = self.dll.CPhidgetTextLCD_getRowCount(self.handle, byref(rowCount)) <NEW_LINE> if result > 0: <NEW_LINE> <INDENT> raise PhidgetException(result) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return rowCount.value
Returns the number of rows available on the display. Returns: The number of rows <int>. Exceptions: PhidgetException: If this Phidget is not opened and attached.
625941c4dd821e528d63b192
def _configure(self, apikey: str): <NEW_LINE> <INDENT> self.apikey = apikey or settings.APIKEY <NEW_LINE> assert self.apikey, "Missing required apikey." <NEW_LINE> self._params = {"api_key": self.apikey, "out": "json"} <NEW_LINE> endpoint = self.endpoint if self.endpoint.endswith("/") else f"{self.endpoint}/" <NEW_LINE...
Set instance API key, default parameters and base url.
625941c4a17c0f6771cbe039
def publish_survey(context): <NEW_LINE> <INDENT> pc = getToolByName(context, "portal_catalog") <NEW_LINE> wf = getToolByName(context, 'portal_workflow') <NEW_LINE> query = {"object_provides": IOrgnization_annual_survey.__identifier__} <NEW_LINE> bns = pc(query) <NEW_LINE> for bn in bns: <NEW_LINE> <INDENT> if bn.review...
将旧的社会组织年检数据直接发布为published状态
625941c4bde94217f3682dda
def process_article( self, article_IN, coding_user_IN = None, *args, **kwargs ): <NEW_LINE> <INDENT> status_OUT = self.STATUS_SUCCESS <NEW_LINE> me = "process_article" <NEW_LINE> my_logger = None <NEW_LINE> my_exception_helper = None <NEW_LINE> data_store_json_string = "" <NEW_LINE> article_data_id = -1 <NEW_LINE> requ...
purpose: After the ArticleCoder is initialized, this method accepts one article instance and codes it for sourcing. In regards to articles, this class is stateless, so you can process many articles with a single instance of this object without having to reconfigure each time. Accepts: - article_IN - ar...
625941c421a7993f00bc7cd4
def candy(self, ratings): <NEW_LINE> <INDENT> ranks = [1 for _ in range(len(ratings))] <NEW_LINE> for index in range(1, len(ratings)): <NEW_LINE> <INDENT> if ratings[index - 1] < ratings[index]: <NEW_LINE> <INDENT> ranks[index] = 1 + ranks[index - 1] <NEW_LINE> <DEDENT> <DEDENT> for index in range(len(ratings) - 1, 0, ...
:type ratings: List[int] :rtype: int
625941c4956e5f7376d70e56
def init(): <NEW_LINE> <INDENT> if not os.path.exists(config.app_database): <NEW_LINE> <INDENT> print(_('No database found, creating it.')) <NEW_LINE> with SQLite() as db: <NEW_LINE> <INDENT> db.s('CREATE TABLE feeds (id integer NOT NULL PRIMARY KEY ' + 'AUTOINCREMENT, created_at datetime NOT NULL DEFAULT ' + 'CURRENT_...
Init SQLite database, creates tables.
625941c47b25080760e39441
def _forward_word2doc(self, word_embed, batch_x, batch_lens): <NEW_LINE> <INDENT> word_hidden = self.word2doc_nn(word_embed, batch_lens) <NEW_LINE> word_hidden = self.word2doc_dropout(word_hidden) <NEW_LINE> doc_embed = self.word2doc_pooling(word_hidden, batch_lens) <NEW_LINE> return doc_embed
Input: word_embed: tensor (float32) of shape (batch, step, emb) batch_x: tensor (int64) of shape (batch, step) batch_lens: tensor (int64) of shape (batch, ) Return: doc_embed: tensor (float32) of shape (batch, hidden)
625941c47cff6e4e8111796d
def start_output (self): <NEW_LINE> <INDENT> super(GMLLogger, self).start_output() <NEW_LINE> if self.has_part("intro"): <NEW_LINE> <INDENT> self.write_intro() <NEW_LINE> self.writeln() <NEW_LINE> <DEDENT> self.writeln(u"graph [") <NEW_LINE> self.writeln(u" directed 1") <NEW_LINE> self.flush()
Write start of checking info as gml comment.
625941c4baa26c4b54cb1108
def Hk(self, k, m_pred, P_pred): <NEW_LINE> <INDENT> return self.H[:, :, self.index[self.H_time_var_index, k]]
function (k, m, P) return Jacobian of measurement function, it is passed into p_h. k (iteration number), starts at 0 m: point where Jacobian is evaluated P: parameter for Jacobian, usually covariance matrix.
625941c4cdde0d52a9e53019
def send_message(chat_id, text=None, parse_mode = 'Markdown', token=None): <NEW_LINE> <INDENT> URL = f'https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={text}' <NEW_LINE> answer = {'chat_id': chat_id, 'text': text, 'parse_mode': 'Markdown'} <NEW_LINE> r = requests.post(URL, json=answer) <NEW_LINE>...
Sends message in bold mode/Enviar mensagem em negrito. :param chat_id: ID of Telegram account/ID da conta Telgram. :param text: Message/Mensagem. :param parse_mode: Ignore. :param token: ID Telegram bot/ID do bot Telegram.
625941c45f7d997b87174a7e
def get_to_user_directly_query(self, user_or_username): <NEW_LINE> <INDENT> query_user = self._get_query_user(user_or_username) <NEW_LINE> query = Q(target_people=query_user) <NEW_LINE> from reviewboard.accounts.models import Profile <NEW_LINE> try: <NEW_LINE> <INDENT> profile = Profile.objects.get(user=query_user) <NE...
Returns the query targetting a user directly. This will include review requests where the user has been listed as a reviewer, or the user has starred. This is meant to be passed as an extra_query to ReviewRequest.objects.public().
625941c4f7d966606f6a9fea
def create_readme(seq_info, outfile): <NEW_LINE> <INDENT> fh = open(outfile, 'w') <NEW_LINE> fh.write(README_STR.format(**seq_info)) <NEW_LINE> fh.close()
Create `README.md` file Parameters ---------- seq_info : Dict of {str, Object} Sequencing metadata retrieved from directory name outfile : str Output config file to create
625941c4dc8b845886cb551c
def max_abs_diff(array): <NEW_LINE> <INDENT> return _np.max(_np.abs(array))
Return the span of `array` span(array) = max array(s) - min array(s)
625941c4ac7a0e7691ed40b7
def test_ap_nginx_config_entries( self, kube_apis, crd_ingress_controller_with_ap, appprotect_setup, test_namespace ): <NEW_LINE> <INDENT> conf_annotations = [ "app_protect_enable on;", f"app_protect_policy_file /etc/nginx/waf/nac-policies/{test_namespace}_{ap_policy};", "app_protect_security_log_enable on;", f"app_pro...
Test to verify AppProtect annotations in nginx config
625941c4f9cc0f698b1405e5
def trainTopicCreateTopic(self, name): <NEW_LINE> <INDENT> return self._er.jsonRequestAnalytics("/api/v1/trainTopic", { "action": "createTopic", "name": name})
create a new topic to train. The user should remember the "uri" parameter returned in the result @returns object containing the "uri" property that should be used in the follow-up call to trainTopic* methods
625941c43617ad0b5ed67ee1
def __init__(self, prime_idx): <NEW_LINE> <INDENT> self.base = int64(PRIME_VECTOR[prime_idx]) <NEW_LINE> self.idx = int64(0)
Initialize the sequence with the nth prime number
625941c43cc13d1c6d3c7363
def scenarios_misc_get(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.scenarios_misc_get_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.scenarios_misc_get_with_http_info(**kwargs) <N...
GET /scenarios/misc Miscellaneous team scenarios 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.scenarios_misc...
625941c43346ee7daa2b2d53
def get_user_info(devkey, userkey): <NEW_LINE> <INDENT> params = {"api_option": "userdetails", "api_dev_key": devkey, "api_user_key": userkey} <NEW_LINE> params = urlencode(params) <NEW_LINE> response = urlopen("http://pastebin.com/api/api_post.php", params) <NEW_LINE> data = response.read() <NEW_LINE> response.close()...
Gets info about a user.
625941c430bbd722463cbdac
def hermevander3d(x, y, z, deg): <NEW_LINE> <INDENT> return pu._vander3d(hermevander, x, y, z, deg)
Pseudo-Vandermonde matrix of given degrees. Returns the pseudo-Vandermonde matrix of degrees `deg` and sample points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`, then Hehe pseudo-Vandermonde matrix is defined by .. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = He_i(x)*He_j(y)*He_k(z), where `0 <= i <= l...
625941c476e4537e8c351659
def get(self, boxname="outbox"): <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data,outbox = self._get() <NEW_LINE> try: <NEW_LINE> <INDENT> self.temp[outbox].append(data) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.temp[outbox] = [ data ] <NEW_LINE> <DEDENT> <DEDENT> excep...
Return an item of data sent to an outbox of the wrapped component. This method is non blocking and always returns immediately. If there is no data to return, then the exception queue.Empty is thrown Arguments: - boxname -- (optional) the name of the outbox of the wrapped component from which the data should be co...
625941c49c8ee82313fbb75c
def make_sample_generator(components): <NEW_LINE> <INDENT> while(True): <NEW_LINE> <INDENT> failures = sample_failures(components, rnd_random) <NEW_LINE> yield failures | crow_failures(failures, rnd_random)
a generator function that makes samples
625941c455399d3f0558869b
def set_root_mysql_password(node, ssh_user, private_key, new_password): <NEW_LINE> <INDENT> test_node_ssh_availability(node, ssh_user, private_key) <NEW_LINE> ssh = paramiko.SSHClient() <NEW_LINE> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) <NEW_LINE> retry(ssh.connect, 5, (socket.error, SSHException, Aut...
Sets the mysql root password :param node: A node to reformat the drive on :param ssh_user: The user to ssh with :param private_key: The key to ssh with :return:
625941c4fbf16365ca6f61a9
def uniformCostSearch(problem): <NEW_LINE> <INDENT> nodes = util.PriorityQueue() <NEW_LINE> statelist = [] <NEW_LINE> originalstate = problem.getStartState() <NEW_LINE> rootnode = (originalstate, [], 0) <NEW_LINE> nodes.push(rootnode, 0) <NEW_LINE> while nodes.isEmpty() is not True: <NEW_LINE> <INDENT> search = nodes.p...
Search the node of least total cost first.
625941c407f4c71912b11469
def set_environment(self, desired_environment: Environment) -> None: <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> self.desired_environment = desired_environment
This function safely updates the reference to the most recent sensor values from the farm. :param desired_environment: A desired environment to create
625941c46aa9bd52df036d8b
def removeDuplicates(self, nums): <NEW_LINE> <INDENT> if not nums: return 0 <NEW_LINE> j = 0 <NEW_LINE> for i in xrange(len(nums)): <NEW_LINE> <INDENT> if i > 0 and nums[i] == nums[i - 1]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> nums[j] = nums[i] <NEW_LINE> j += 1 <NEW_LINE> <DEDENT> return j
:type nums: List[int] :rtype: int
625941c42eb69b55b151c896
def _get_model(): <NEW_LINE> <INDENT> root = tracking.AutoTrackable() <NEW_LINE> kernel_in = np.array([-2, -1, 1, 2], dtype=np.float32).reshape((2, 2, 1, 1)) <NEW_LINE> @tf.function( input_signature=[tf.TensorSpec(shape=[1, 3, 3, 1], dtype=tf.float32)]) <NEW_LINE> def func(inp): <NEW_LINE> <INDENT> kernel = tf.constant...
Returns somple model with Conv2D and representative dataset gen.
625941c430bbd722463cbdad
def getTasksLinkedToComponent(self, *args): <NEW_LINE> <INDENT> return _pilot.DeploymentTreeOnHeap_getTasksLinkedToComponent(self, *args)
getTasksLinkedToComponent(DeploymentTreeOnHeap self, ComponentInstance comp) -> std::vector< YACS::ENGINE::Task *,std::allocator< YACS::ENGINE::Task * > >
625941c44a966d76dd550ff7
@APP.route('/add_language', methods=['POST']) <NEW_LINE> def add_language(): <NEW_LINE> <INDENT> _language = request.form['language'] <NEW_LINE> user.User(graph, session['email']).add_language(language.Language(graph, _language).find()) <NEW_LINE> return redirect(url_for('profile', username=session['username']))
add language handler
625941c455399d3f0558869c
def decode(self, x): <NEW_LINE> <INDENT> x = F.relu(self.fc5(x)) <NEW_LINE> x = F.relu(self.fc6(x)) <NEW_LINE> x = F.relu(self.fc7(x)) <NEW_LINE> x = torch.sigmoid(self.fc8(x)) <NEW_LINE> return x
Decoder in the WAE architecture Args: x: a Torch tensor, from the latent space. Returns: the reconstruction of x, from the latent space to the original space.
625941c47d847024c06be2a2
def test_api_v1_file_file_id_get(self): <NEW_LINE> <INDENT> pass
Test case for api_v1_file_file_id_get Downloads a file referred by the fileId # noqa: E501
625941c426068e7796caecc4
def github_process(request): <NEW_LINE> <INDENT> config = request.registry.settings <NEW_LINE> code = request.GET.get('code') <NEW_LINE> if not code: <NEW_LINE> <INDENT> reason = request.GET.get('error', 'No reason provided.') <NEW_LINE> return AuthenticationDenied(reason) <NEW_LINE> <DEDENT> access_url = flat_url('htt...
Process the github redirect
625941c44f88993c3716c051
def _pushundo(self, entries): <NEW_LINE> <INDENT> self.undo_buffer.append(entries)
Insert one state into the undo stack
625941c46fece00bbac2d725
def test_activate_with_key(self): <NEW_LINE> <INDENT> self.client.post('/user/register/', self.good_data) <NEW_LINE> ua = UserActivation.objects.get(pk=1) <NEW_LINE> self.assertFalse(ua.user.is_active) <NEW_LINE> response = self.client.get('/user/confirm/%s' % ua.activation_key) <NEW_LINE> self.assertEqual(response.sta...
POST good data and use validation key to confirm
625941c44e696a04525c9434
def _doChildConnect(name, transport): <NEW_LINE> <INDENT> server_config = GlobalObject().json_config.get('servers', {}).get(name, {}) <NEW_LINE> remoteport = server_config.get('remoteport', []) <NEW_LINE> child_host = transport.broker.transport.client[0] <NEW_LINE> root_list = [rootport.get('rootname') for rootport in ...
当server节点连接到master的处理
625941c4d164cc6175782d36
def Patch(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Patch') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params)
Updates a managed instance group using the information that you specify in the request. The field statefulPolicy is updated using PATCH semantics. This operation is marked as DONE when the group is updated even if the instances in the group have not yet been updated. You must separately verify the status of the individ...
625941c4925a0f43d2549e5e
def attributes(obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for n in dir(obj): <NEW_LINE> <INDENT> if n in ('__dict__',): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if obj.__name__ == "__call__" == n: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDE...
Produce a sequence of (name, value), the attributes of `obj`.
625941c407f4c71912b1146a
def compute(self, model, vout, tape, monitor=None): <NEW_LINE> <INDENT> _voutnames = set([var._name for var in model._vout]) <NEW_LINE> for varname in vout: <NEW_LINE> <INDENT> if varname not in _voutnames: <NEW_LINE> <INDENT> raise UnexpectedOutput("Requested vout %s is not defined by the model as an output; available...
compute a model in the current context (self)
625941c4b7558d58953c4f00
def load_doc(filename): <NEW_LINE> <INDENT> with open(filename) as file: <NEW_LINE> <INDENT> text = file.read() <NEW_LINE> <DEDENT> return text
Function for loading various files :param filename: Source Path :return: Caption Text
625941c45fdd1c0f98dc021b
def translation(_, city_data): <NEW_LINE> <INDENT> word = random.choice([ 'helloNN', 'goodbyeNN', 'thanksNN', 'sorryNN', ]) <NEW_LINE> return 'To say "%s" in the %s language, say "%s" (%s)' % ( city_data['dictionary'][word]['translation'], get_latin(city_data['language']['name']), get_latin(city_data['dictionary'][word...
the word for hello is ___
625941c4097d151d1a222e44
def meanpquantilesDNN(Inputs, nclasses, nregclasses, dropoutRate=None, batchNorm=True, splitInputs=False, pfix='', arch=':32x16x4'): <NEW_LINE> <INDENT> x = BatchNormalization(name='bn_0')(Inputs[0]) if batchNorm else Inputs[0] <NEW_LINE> nodesCommon, nodesInd = arch.split(':') <NEW_LINE> archCommon = [] <NEW_LINE> if ...
model for the regression of the recoil scale
625941c48e71fb1e9831d792
def deleteMatches(): <NEW_LINE> <INDENT> db = connect() <NEW_LINE> cursor = db.cursor() <NEW_LINE> query = "delete from matches" <NEW_LINE> cursor.execute(query) <NEW_LINE> db.commit() <NEW_LINE> db.close()
Remove all the match records from the database.
625941c482261d6c526ab485
def sumRange(self, i, j): <NEW_LINE> <INDENT> curnode = self.head <NEW_LINE> def get_sumrange(i, j, curnode): <NEW_LINE> <INDENT> if not curnode: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> l, r = curnode.val <NEW_LINE> if i == l and j == r: <NEW_LINE> <INDENT> return curnode.sumrange <NEW_LINE> <DEDENT> mid = (l ...
:type i: int :type j: int :rtype: int
625941c431939e2706e4ce55
def make_item(res: dict, cls): <NEW_LINE> <INDENT> item = cls() <NEW_LINE> for field in cls.field_names(): <NEW_LINE> <INDENT> item[field] = res.get(field) <NEW_LINE> <DEDENT> return item
构造 Item 实例,并尽可能尝试从 response 里自动读取到目标值,如果读取不到,还需要在外部赋值。 :param res: :param cls: :return:
625941c450485f2cf553cd82
def memcache_results(cache_secs=DEFAULT_CACHE_SECS): <NEW_LINE> <INDENT> def wrap1(method): <NEW_LINE> <INDENT> @functools.wraps(method) <NEW_LINE> def wrap2(self, *args, **kwds): <NEW_LINE> <INDENT> key = _compute_memcache_key(self, method, *args, **kwds) <NEW_LINE> _log.debug('trying to retrieve cached results for %s...
Decorate a method with the memcache pattern. Technically, the memcache_results function isn't a decorator. It's a function that returns a decorator. We have to jump through these hoops because we want to pass an argument to the decorator - how long to cache the results. But a decorator can only accept one argument ...
625941c49c8ee82313fbb75d
def lasso_selector(func=None, trait='selected', **kwargs): <NEW_LINE> <INDENT> return _create_selector(LassoSelector, func, trait, **kwargs)
Creates a `LassoSelector` interaction for the `figure`. Also attaches the function `func` as an event listener for the specified trait. Parameters ---------- func: function The call back function. It should take atleast two arguments. The name of the trait and the value of the trait are passed as arguments. ...
625941c4ab23a570cc25016a
def is_chinese_char(uchar): <NEW_LINE> <INDENT> if uchar >= u'\u3400' and uchar <= u'\u4db5': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif uchar >= u'\u4e00' and uchar <= u'\u9fa5': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif uchar >= u'\u9fa6' and uchar <= u'\u9fbb': <NEW_LINE> <INDENT> return...
Whether is a chinese character. Args: uchar: A utf-8 char. Returns: True/False.
625941c4e1aae11d1e749c9e
def chapter_4_15(): <NEW_LINE> <INDENT> import heapq <NEW_LINE> def test1(): <NEW_LINE> <INDENT> a = [1, 4, 7, 10] <NEW_LINE> b = [2, 5, 6, 11] <NEW_LINE> for c in heapq.merge(a, b): <NEW_LINE> <INDENT> print(c)
合并已排序的序列并输出。
625941c4b545ff76a8913dff
def plotEpsQuarter(self): <NEW_LINE> <INDENT> pass
Generates a log-plot of quarterly EPS data.
625941c4a4f1c619b28b0026
def test_parse_args_update_ca(capsys): <NEW_LINE> <INDENT> args = cli.parse_args(['-n', '--update', '--ca', DEBMONITOR_CLIENT_CA_BUNDLE]) <NEW_LINE> assert args.ca == DEBMONITOR_CLIENT_CA_BUNDLE <NEW_LINE> assert args.verify == DEBMONITOR_CLIENT_CA_BUNDLE
Calling parse_args with --update and --ca should set verify to the ca path.
625941c48da39b475bd64f5b
def make_recommendations(person: str, person_to_friends: Dict[str, List[str]], person_to_networks: Dict[str, List[str]]) -> List[Tuple[str, int]]: <NEW_LINE> <INDENT> potential_friends = [] <NEW_LINE> possible_friends = get_possible_friends(person_to_friends, person) <NEW_LINE> friends_of_friends = [] <NEW_LINE> net...
For the person specified, this makes recommendations about potential friends based on mutual friends, common networks, and last names. It returns a list of tuples containing the potential friend and their score. >>> p2f = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'], 'Claire Dunphy': [...
625941c432920d7e50b281b7
def is_prime(number): <NEW_LINE> <INDENT> if number <= 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if number <= 3: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if number % 2 == 0 or number % 3 == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> idx = 3 <NEW_LINE> while idx * idx <= number: <NE...
function thats return the primality of a number
625941c4656771135c3eb855
def split_eh(self, w): <NEW_LINE> <INDENT> e_idx, h_idx = self.partial_to_eh_subsets() <NEW_LINE> e, h = w[e_idx], w[h_idx] <NEW_LINE> from hedge.flux import FluxVectorPlaceholder as FVP <NEW_LINE> if isinstance(w, FVP): <NEW_LINE> <INDENT> return FVP(scalars=e), FVP(scalars=h) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
Splits an array into E and H components
625941c48e05c05ec3eea35c
def create_alien_group(self, x, y): <NEW_LINE> <INDENT> self.alien_group = AlienGroup(x, y) <NEW_LINE> for alien in self.alien_group: <NEW_LINE> <INDENT> self.add(alien)
Initializes the rows of descending aliens. Creates a new alien group and adds all enemies to the layer as child nodes. :param x: x coordinate :param y: y coordinate :return:
625941c4046cf37aa974cd32
def parse_coordinates(coordinate_str): <NEW_LINE> <INDENT> coords = coordinate_str.split(',') <NEW_LINE> return {'lat': coords[0], 'lon': coords[1]}
Converts the coordinate string "lat,lon" to {'lat':lat, 'lon':lon}.
625941c499cbb53fe6792bd0
def get(self,request,slug,format=None): <NEW_LINE> <INDENT> target = self.get_movie(slug) <NEW_LINE> serializer=ss.MovieSerializer(target) <NEW_LINE> return Response(serializer.data)
get details of a single movie
625941c416aa5153ce362461
def list_apply_rule_multiplier(list_, rule): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> new_generator = (rule(x) for x in list_) <NEW_LINE> yield new_generator
Creates generators iterating through the same list whilst applying a rule to each element of the list. Parameters: list_ ([]) a list or other iterable. rule (callable) : a function operating on the elements of the list. Returns: new_generator (generator) : generator of the list elements. Notes: Do not ...
625941c40383005118ecf5cd
def descargar_actualizacion(self): <NEW_LINE> <INDENT> syslog.syslog(syslog.LOG_DEBUG, "Descargando ultima versión") <NEW_LINE> return self.obtener_servidor(config.NETCOP['url_download'])["clases"]
Descarga la ultima version de firmas y devuelve una lista de todas las clases de trafico.
625941c47d847024c06be2a3
def calculateAngle(self, far, start, end): <NEW_LINE> <INDENT> a = math.sqrt((end[0] - start[0])**2 + (end[1] - start[1])**2) <NEW_LINE> b = math.sqrt((far[0] - start[0])**2 + (far[1] - start[1])**2) <NEW_LINE> c = math.sqrt((end[0] - far[0])**2 + (end[1] - far[1])**2) <NEW_LINE> angle = math.acos((b**2 + c**2 - a**2) ...
Cosine rule
625941c416aa5153ce362462
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): <NEW_LINE> <INDENT> line = clean_lines.elided[linenum] <NEW_LINE> match = Search(pattern, line) <NEW_LINE> if not match: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> context = line[0:match.start(1) - 1] <NEW_LINE> if Match(r'.*\b(?:...
Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or con...
625941c44527f215b584c442
def Rmdir(path, force = False): <NEW_LINE> <INDENT> if force: <NEW_LINE> <INDENT> for file in glob.glob(os.path.join(path, "*")): <NEW_LINE> <INDENT> if Isdir(file): <NEW_LINE> <INDENT> Rmdir(file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Rm(file) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> os.rmdir(path) <NEW_LINE> ret...
Delete the directory at the specified path. Include all of its contents if force is True.
625941c4090684286d50eccd
def plot_numeric_fixed(self, df, var_column, date_column, time_resolution='1d', tw=False, key_column=None, key_ids=None, reference_date=None, offset=None, color=plt.cm.Dark2(0), ax=None): <NEW_LINE> <INDENT> if tw: <NEW_LINE> <INDENT> assert(reference_date) <NEW_LINE> assert(offset) <NEW_LINE> df = df[(df[date_column] ...
Plot numeric time series (enable plotting the averaged time series across keys, if key_column is specified). This function plot time series relative to fixed date (the reference_date) :param df: main (training set) DataFrame :param var_column: String. Numeric column name to plot :param date_column: String. Date column ...
625941c494891a1f4081ba91
def test_get_product_none_in_list(self): <NEW_LINE> <INDENT> server.Product.catalog.remove_all() <NEW_LINE> resp = self.app.get('/products/1') <NEW_LINE> self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND) <NEW_LINE> resp = self.app.get('/products') <NEW_LINE> self.assertEqual(resp.status_code, status.HTTP_20...
Search for a product in a catalog with no products
625941c4b57a9660fec3386c
def ClusterPowerOnVmResult(vim, *args, **kwargs): <NEW_LINE> <INDENT> obj = vim.client.factory.create('{urn:vim25}ClusterPowerOnVmResult') <NEW_LINE> if (len(args) + len(kwargs)) < 0: <NEW_LINE> <INDENT> raise IndexError('Expected at least 1 arguments got: %d' % len(args)) <NEW_LINE> <DEDENT> required = [ ] <NEW_LINE>...
PowerOnVmResult is the base class of the result returned to the PowerOnMultiVM_Task method.
625941c491af0d3eaac9ba00
def get_p (self): <NEW_LINE> <INDENT> prob = 1 <NEW_LINE> for p in self.__param_list: <NEW_LINE> <INDENT> prob *= p.get_p () <NEW_LINE> <DEDENT> return prob
Given the parameters and its distributions (priors), returns the value of the pdf of the joint distribution of parameters on the point represented by this object.
625941c471ff763f4b549672
def next_coord(snake_coords, apple): <NEW_LINE> <INDENT> if len(snake_coords) < HALF: <NEW_LINE> <INDENT> path = a_path_search.cal(snake_coords[0], apple, snake_coords[:-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> path = dfs_path_search.cal(snake_coords[0], apple, snake_coords[:-1]) <NEW_LINE> <DEDENT> if path: <...
计算下一个坐标 :param snake_coords: snake_coords :param apple: apple :return: 下一个坐标
625941c4187af65679ca5107
def delete(self): <NEW_LINE> <INDENT> response = self.session.request("delete:Message", [ self.message_id ]) <NEW_LINE> self.data = response <NEW_LINE> return self
Delete the draft.
625941c4fbf16365ca6f61aa
def test_post_fuzz_req_json_vars(self): <NEW_LINE> <INDENT> req = post_req( "/api/v1/{key:val}/path/{otherkey:val2}", data=test_dict) <NEW_LINE> strings = ["test"] <NEW_LINE> results = [ d for d in fuzz_datagen.fuzz_request(req, strings, "data", "ut") ] <NEW_LINE> req_objs = [r[1] for r in results] <NEW_LINE> for d in ...
Test fuzz_request with a JSON-like dict.
625941c497e22403b379cf82
def configure_cosine_dihedral(self, type1, type2, type3, type4, force_constant=1., multiplicity=1, phi0=0.): <NEW_LINE> <INDENT> force_constant = self._units.convert(force_constant, self._units.energy_unit / (self._units.reg.radians ** 2)) <NEW_LINE> if force_constant <= 0: <NEW_LINE> <INDENT> raise ValueError("The for...
Configures a cosine dihedral angle potential between a particle quadruple with types as given in the arguments. The sequence in which the types can be reversed, so `(type1, type2, type3, type4)` yields the same potential terms as `(type4, type3, type2, type1)`. Angles are internally always expressed in radians. :para...
625941c4de87d2750b85fd7a
def apply(self, source): <NEW_LINE> <INDENT> previous_line_suitable = False <NEW_LINE> result = [] <NEW_LINE> for line in source: <NEW_LINE> <INDENT> if is_line_separate_record(line): <NEW_LINE> <INDENT> for template in self.settings.templates: <NEW_LINE> <INDENT> if template in line: <NEW_LINE> <INDENT> result.append(...
Performs filtration logic @rtype : iter @param source: iterable of strings, that represents content for filtration @return: iterable of strings, result of applying logic of filtration
625941c4d99f1b3c44c6757a
def getSaveAction(self): <NEW_LINE> <INDENT> return self.getOutputToolBar().getSaveAction()
Action to save plot :rtype: actions.PlotAction
625941c4091ae35668666f4a
def laser(self): <NEW_LINE> <INDENT> if self.stop == 0 and self.present == 0: <NEW_LINE> <INDENT> rnd = rd.random()*self.probaLaser <NEW_LINE> if rnd <= 1: <NEW_LINE> <INDENT> self.yLaser = self.y + self.alien.width() <NEW_LINE> self.xLaser = self.x + self.alien.height()/2 <NEW_LINE> self.tir = self.can.create_rectangl...
Role : permet de créer un laser tiré par les aliens aléatoirement Entrée : self.stop et self.present (même que précédemment, lorsque self.present = 1, il y a déjà un tir présent sur le canvas et l'alien ne pourra pas en retirer un nouveau tant que le tir n'est pas détruit), self.yLaser et self.xLaser (qui définissent l...
625941c4cc0a2c11143dce7a
def deallocate_vip(self, loadbalancer, lb_count_subnet): <NEW_LINE> <INDENT> ports = [] <NEW_LINE> sec_grp = None <NEW_LINE> vip_port_id = loadbalancer.vip.port_id <NEW_LINE> fixed_subnets = CONF.a10_controller_worker.amp_boot_network_list[:] <NEW_LINE> subnet = self.get_subnet(loadbalancer.vip.subnet_id) <NEW_LINE> if...
Delete the vrrp_port (instance port) in case nova didn't This can happen if a failover has occurred.
625941c4596a897236089aac
@ClassFactory.register(ClassType.PRETRAINED_HOOK) <NEW_LINE> def pretrained_bert_classifier_hook(state_dict, prefix, local_metadata, *args, **kwargs): <NEW_LINE> <INDENT> org = OrderedDict() <NEW_LINE> for key, value in state_dict.items(): <NEW_LINE> <INDENT> if key.startswith('bert'): <NEW_LINE> <INDENT> org[key] = va...
Convert state_dict name according to prefix.
625941c4e64d504609d74829
def display_option(self, record, k=None): <NEW_LINE> <INDENT> if k is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> print('\n\t\t > {} <'.format(k)) <NEW_LINE> self.display_record(record)
Show an option to user, with optional choice number `k`. Nothing done if no `k`.
625941c4711fe17d82542358
def top_sort_heap(self, K: int) -> int: <NEW_LINE> <INDENT> mink = [] <NEW_LINE> for k, v in self.p2s.items(): <NEW_LINE> <INDENT> heappush(mink, (v, k)) <NEW_LINE> if len(mink) > K: <NEW_LINE> <INDENT> heappop(mink) <NEW_LINE> <DEDENT> <DEDENT> return sum(v for v, k in mink)
Runtime: 112 ms, faster than 17.08% of Python3 online submissions for Design A Leaderboard. T: O(K + NlogK)
625941c46fece00bbac2d726
def _read_default_value(self, field_schema, default_value): <NEW_LINE> <INDENT> if field_schema.type == 'null': <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif field_schema.type == 'boolean': <NEW_LINE> <INDENT> return bool(default_value) <NEW_LINE> <DEDENT> elif field_schema.type == 'int': <NEW_LINE> <INDENT>...
Basically a JSON Decoder?
625941c4d4950a0f3b08c33a
def lookup(self,string): <NEW_LINE> <INDENT> curTrie = self <NEW_LINE> i = 0 <NEW_LINE> while(i < len(string)): <NEW_LINE> <INDENT> if (curTrie.contents[self.bucket(string[i])] != None): <NEW_LINE> <INDENT> curTrie = curTrie.contents[self.bucket(string[i])] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Fal...
>>> t1 = Trie(26, False) >>> t2 = Trie(26, True) >>> t3 = Trie(26, True) >>> t4 = Trie(26, True) >>> t1.setBucket('c', t2) >>> t2.setBucket('a', t3) >>> t1.setBucket('b', t4) >>> t1.lookup("c") True >>> t1.lookup("ca") True >>> t1.lookup("") False >>> t1.lookup("car") False >>> t1.lookup("b") True
625941c4d58c6744b4257c4a