code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_channels(self): <NEW_LINE> <INDENT> bus_name = self.telepathy_conn.requested_bus_name <NEW_LINE> connection_path = self.telepathy_conn.object_path <NEW_LINE> channels = [self.telepathy_text_chan.object_path, self.telepathy_tubes_chan.object_path] <NEW_LINE> _logger.debug('%r: bus name is %s, connection is %s, c...
Retrieve communications channel descriptions for the activity Returns a tuple containing: - the D-Bus well-known service name of the connection (FIXME: this is redundant; in Telepathy it can be derived from that of the connection) - the D-Bus object path of the connection - a list of D-Bus obje...
625941cd287bf620b61d3b69
def getRowsCols(paperW, paperH, W, H): <NEW_LINE> <INDENT> rows1, cols1 = int(paperH//H), int(paperW//W) <NEW_LINE> rows2, cols2 = int(paperW//H), int(paperH//W) <NEW_LINE> if rows1*cols1 >= rows2*cols2: <NEW_LINE> <INDENT> return paperW, paperH, rows1, cols1 <NEW_LINE> <DEDENT> return paperH, paperW, rows2, cols2
Input : int paper_width, int paper_height, int image_width, int image_height Rerurns paper width, paper height, rows, cols
625941cd596a897236089bc6
def _create_vm(self, method, *args, **kwargs): <NEW_LINE> <INDENT> config_spec = kwargs.get("config") <NEW_LINE> ds = _db_content["Datastore"][_db_content["Datastore"].keys()[0]] <NEW_LINE> vm_dict = {"name": config_spec.name, "ds": ds, "powerstate": "poweredOff", "vmPathName": config_spec.files.vmPathName, "numCpu": c...
Creates and registers a VM object with the Host System.
625941cd5166f23b2e1a525e
def test_validate_age_is_false_negative_num(self): <NEW_LINE> <INDENT> v = Validator() <NEW_LINE> result = v.validate_item('-20', 'age') <NEW_LINE> self.assertFalse(result, 'invalid AGE')
Test the validate age function :return:
625941cd30bbd722463cbecb
def edit_game_configuration(self, _button): <NEW_LINE> <INDENT> game = Game(self.view.selected_game) <NEW_LINE> if game.is_installed: <NEW_LINE> <INDENT> EditGameConfigDialog(self, self.view.selected_game)
Edit game preferences.
625941cd4527f215b584c55c
def plot_stacked_bar_chart_from_dataframe(data, figsize=(16,6), bar_width=0.2, title=None, grid=True, xticks_rotation='horizontal'): <NEW_LINE> <INDENT> fig = plt.figure(figsize=figsize) <NEW_LINE> X = np.arange(len(data)) <NEW_LINE> bottoms = pd.Series([0 for _ in range(len(data))], index=data.index) <NEW_LINE> for c ...
Create a stacked bar chart from a pandas dataframe using the index as the bar labels (x) and the values per column as the bar heights (y), with the first column on the bottom
625941cd01c39578d7e74f41
def parse_bam_index_stats(fn): <NEW_LINE> <INDENT> with open(fn) as f: <NEW_LINE> <INDENT> lines = [x.strip().split() for x in f.readlines()] <NEW_LINE> <DEDENT> no_counts = int(lines[-1][-1]) <NEW_LINE> lines = lines[:-1] <NEW_LINE> chrom = [x[0] for x in lines] <NEW_LINE> length = [int(x[2]) for x in lines] <NEW_LINE...
Parse the output from Picard's BamIndexStast and return as pandas Dataframe. Parameters ---------- filename : str of filename or file handle Filename of the Picard output you want to parse. Returns ------- df : pandas.DataFrame Data from output file.
625941cd796e427e537b06cb
def get_features(model, images, params_dict): <NEW_LINE> <INDENT> fe_function = get_feature_extraction_function(model, **params_dict) <NEW_LINE> return fe_function([images])[0]
Create and run feature_extraction function using params_dict
625941cdd8ef3951e3243643
@app.route('/categories/new', methods=['GET', 'POST']) <NEW_LINE> def createCategory(): <NEW_LINE> <INDENT> if 'username' not in login_session: <NEW_LINE> <INDENT> return redirect('/login') <NEW_LINE> <DEDENT> if request.method == 'POST': <NEW_LINE> <INDENT> category = Category(name=request.form['name']) <NEW_LINE> ses...
Create a new category.
625941cd50485f2cf553ce9f
def load_available_properties(terms_dict): <NEW_LINE> <INDENT> property_list = [] <NEW_LINE> for label,property_dict in terms_dict.items(): <NEW_LINE> <INDENT> for property, value in property_dict.items(): <NEW_LINE> <INDENT> if (property not in property_list) and (property != "@type") and (property != "@context"): <NE...
Takes union of all properties available for current BIDS terms :return: list of available properites
625941cde1aae11d1e749dbd
def underlineNodeHandler(self, topnode): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> underline_nodes = topnode.getElementsByTagName('underline') <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> for item in topnode: <NEW_LINE> <INDENT> self.underlineNodeHandler(item) <NEW_LINE> <DEDENT> <DEDENT> else: <NE...
Handles proper conversion of <underline> tags under the provided topnode. Also handles NodeLists by calling itself on each Node in the NodeList
625941cd0383005118ecf6e8
def get_devices_list(self, custom_params=None): <NEW_LINE> <INDENT> logger.info("Getting SecureTrack devices list.") <NEW_LINE> if custom_params: <NEW_LINE> <INDENT> params = '&'.join('{}={}'.format(k, v) for k, v in custom_params.items()) <NEW_LINE> params = '?' + params <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p...
Get the list of currently configured devices in SecureTrack. :param custom_params: Dictionary from param name to value, eg {'vendor': 'Cisco} :type custom_params: dict :return: List of currently configured devices in SecureTrack. :rtype: Devices_List :raise IOError: If there was a communication error while getting the...
625941cd566aa707497f466e
def is_role(self, role): <NEW_LINE> <INDENT> log.debug("is_role %s", role) <NEW_LINE> roles = self.session['roles'].split(',') <NEW_LINE> if role in LTI_ROLES: <NEW_LINE> <INDENT> role_list = LTI_ROLES[role] <NEW_LINE> roles = set(role_list) & set(roles) <NEW_LINE> is_user_role_there = len(roles) >= 1 <NEW_LINE> log.de...
Verify if user is in role :param: role: role to verify against :return: if user is in role :exception: LTIException if role is unknown
625941cdd268445f265b4f74
def check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y): <NEW_LINE> <INDENT> button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y) <NEW_LINE> if button_clicked and not stats.game_active: <NEW_LINE> <INDENT> ai_settings.initialize_dynamic_settings() <NEW_LIN...
Start a new game when player clicks Play button
625941cdf548e778e58cd683
def __key2str(key): <NEW_LINE> <INDENT> if type(key) is tuple: <NEW_LINE> <INDENT> return " ".join(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return key
Take a key and return in string format.
625941cd8e7ae83300e4b0d2
def shuffle(input, output: TextIO, memory=MEMORY): <NEW_LINE> <INDENT> files = [] <NEW_LINE> files.append(tempfile.NamedTemporaryFile(mode="w", delete=False)) <NEW_LINE> total_bytes = 0 <NEW_LINE> total_lines = 0 <NEW_LINE> buf = [] <NEW_LINE> bytes_used = 0 <NEW_LINE> for line in input: <NEW_LINE> <INDENT> bytes_used ...
Shuffle using temporary file
625941cdac7a0e7691ed41d2
def CalMccCenterByThreePoints(mcc): <NEW_LINE> <INDENT> center = list() <NEW_LINE> ma = (EventDict[mcc[1]]["Lat"] - EventDict[mcc[0]]["Lat"]) / (EventDict[mcc[1]]["Lon"] - EventDict[mcc[0]]["Lon"]) <NEW_LINE> mb = (EventDict[mcc[2]]["Lat"] - EventDict[mcc[1]]["Lat"]) / (EventDict[mcc[2]]["Lon"] - ...
Calculate Mcc Center By Three Points
625941cd9f2886367277a993
def theano_expr(self, targets): <NEW_LINE> <INDENT> if targets.ndim != 1: <NEW_LINE> <INDENT> raise ValueError("targets tensor must be 1-dimensional") <NEW_LINE> <DEDENT> if 'int' not in str(targets.dtype): <NEW_LINE> <INDENT> raise TypeError("need an integer tensor for targets") <NEW_LINE> <DEDENT> one_hot_flat = tens...
Return the one-hot transformation as a symbolic expression. Parameters ---------- targets : tensor_like, 1-dimensional, integer dtype A symbolic tensor representing labels as integers between 0 and `max_labels` - 1, `max_labels` supplied at formatter construction. Returns ------- one_hot : TensorVariable,...
625941cd090684286d50edeb
def test_noncenter_threat_threat(self): <NEW_LINE> <INDENT> moves = ['1', '4', '3', '8', '9'] <NEW_LINE> moves.reverse() <NEW_LINE> self.run_game(moves) <NEW_LINE> self.assertEquals(self.grid.test_win(), 'Draw')
Game where the first player does not fill the center, then follows with two threats
625941cd07d97122c4178991
def ReleaseUnmanagedResources(self,*args): <NEW_LINE> <INDENT> pass
ReleaseUnmanagedResources(self: FailureDefinition,disposing: bool)
625941cd956e5f7376d70f73
def data(self, *args): <NEW_LINE> <INDENT> return _IO.AHRecord_data(self, *args)
data(AHRecord self) -> Array data(AHRecord self) -> Array
625941cd3eb6a72ae02ec5e3
@app.route('/subscriptions/<subscription_id>/change', methods=['PUT']) <NEW_LINE> def change_subscription(subscription_id): <NEW_LINE> <INDENT> change_request = build_change_params(request.json) <NEW_LINE> client.put(f'/subscriptions/{subscription_id}/change', change_request) <NEW_LINE> bs_request_data = bsl_data(reque...
Called when a subscription is applied holiday pause Request body looks like: { subscription: Subscription Object From Ordway, changes: input, charge: Charge Object inside Subscription object that is extending, billing_schedule: BillingSchedule Object From Ordway }
625941cd377c676e912722ae
def node_finder(grid, i, flowdirs, drain_area): <NEW_LINE> <INDENT> receiver = flowdirs[i] <NEW_LINE> inflow = np.where(flowdirs == i) <NEW_LINE> if len(inflow[0]) > 1: <NEW_LINE> <INDENT> drin = drain_area[inflow] <NEW_LINE> drmax = max(drin) <NEW_LINE> maxinfl = inflow[0][np.where(drin == drmax)] <NEW_LINE> if len(ma...
Find lateral neighbor node of the primary node for straight, 45 degree, and 90 degree channel segments. Parameters ---------- grid : ModelGrid A Landlab grid object i : int node ID of primary node flowdirs : array Flow direction array drain_area : array drainage area array Returns ------- lat_node : i...
625941cd29b78933be1e57b2
def usb_connected(self): <NEW_LINE> <INDENT> self.processor_programmer.connected() <NEW_LINE> pass
Called when the USB device is connected
625941cd796e427e537b06cc
def checkMonotonic(self, *args): <NEW_LINE> <INDENT> return _ParaMEDMEM.DataArrayDouble_checkMonotonic(self, *args)
checkMonotonic(self, bool increasing, double eps) 1
625941cda219f33f34628a6f
def check(self): <NEW_LINE> <INDENT> if super(SeqTaxonFile, self).check(): <NEW_LINE> <INDENT> self.get_info() <NEW_LINE> if self.prop['form']: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise FileError(u"文件格式错误") <NEW_LINE> <DEDENT> <DEDENT> return True
检测文件是否满足要求 :return:
625941cd56ac1b37e62642d5
def reduce_bless(bless, vocabulary, minimum=40): <NEW_LINE> <INDENT> to_delete = [] <NEW_LINE> for ii in range(len(bless)): <NEW_LINE> <INDENT> if bless.iloc[ii]['root'] not in vocabulary.keys() or vocabulary[bless.iloc[ii]['root']][0]< minimum or bless.iloc[ii]['word'] not in vocabulary.keys(): to_delete.append(ii) <N...
reduce_bless: given a BLESS test DataFrame and a vocabulary, remove root words that occurr less than the minimum allowed number of times and comparison tokens that are OOV
625941cd91f36d47f21ac5f9
def p_DefaultBool(self, p): <NEW_LINE> <INDENT> if p[1] is None: <NEW_LINE> <INDENT> p[0] = p[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = p[2]
DefaultBool : empty | EQUAL Boolean | EQUAL NO_DEFAULT | EQUAL AUTO
625941cd711fe17d82542471
def cal_port_delta(self, deltaInd, allocs): <NEW_LINE> <INDENT> totalChange = 0.0 <NEW_LINE> for tkr in self.reg_coefficients.columns: <NEW_LINE> <INDENT> beta = self.reg_coefficients[tkr].loc[self.indexticker] <NEW_LINE> alpha = self.reg_coefficients[tkr].loc['const'] <NEW_LINE> totalChange += alpha + allocs[tkr].ix[0...
Computed the change of the portfolio value given a change in index :param deltaInd: change in index :return: change in portfolio value
625941cd82261d6c526ab5a5
def cancel(self, event): <NEW_LINE> <INDENT> self.queue.remove(event) <NEW_LINE> heapq.heapify(self.queue)
Remove an event from the queue. This must be presented the ID as returned by enter(). If the event is not in the queue, this raises RuntimeError.
625941cd6e29344779a62717
def _make_api_request(self, request_term_and_type, page=1): <NEW_LINE> <INDENT> api_request = self._format_api_request(request_term_and_type, page=page) <NEW_LINE> request = Request(api_request) <NEW_LINE> request.add_header("Authorization", self._HEADER_AUTHORIZATION) <NEW_LINE> request.add_header("User-Agent","") <NE...
Send a request (song, artist, or search) to the Genius API, returning a json object INPUT: request_term_and_type: (tuple) (request_term, request_type) *request term* is a string. If *request_type* is 'search', then *request_term* is just what you'd type into the search box on Genius.com. If you have an song ID or...
625941cd31939e2706e4cf70
@pytest.fixture <NEW_LINE> def manager_bypass_login(opp, store, provider_bypass_login): <NEW_LINE> <INDENT> return auth.AuthManager( opp, store, {(provider_bypass_login.type, provider_bypass_login.id): provider_bypass_login}, {}, )
Mock manager with allow bypass login.
625941cdff9c53063f47c2f9
def risk_inspect(self, token): <NEW_LINE> <INDENT> url = 'https://ic.ctrip.com/captcha/v4/risk_inspect' <NEW_LINE> self.ep = extend_param() <NEW_LINE> self.dim = dimensions(token) <NEW_LINE> _sign = 'appid=' + '100009556' + "&business_site=" + 'search_airticketscivil_online_pic' + "&version=" + '2.0.4' +...
获取 携程滑块图片 :param token: :return:
625941cd8e05c05ec3eea47a
def select( self, question: str, options: Union[dict, list, tuple], default: Optional[str] = None, custom_key: Optional[Union[str, int]] = None, fmt=[None, None, None, None, None], fmt_question=None, fmt_option=None, fmt_options_end=None, fmt_default=None, fmt_prompt=None, fmt_custom=[None, None, None], fmt_custom_ques...
Prompt the user to select an option from a list of options. :param question: Question to ask. :param options: The options which the user can choose from. :param default: Add default value. :param custom_key: If the user selects this key, s/he can type in a custom value. :param fmt_question: Define a template for displ...
625941cddd821e528d63b2af
def _onPrimsChanged(self, primsChange, propertiesChange): <NEW_LINE> <INDENT> from .rootDataModel import ChangeNotice <NEW_LINE> self._updateForStageChanges( hasPrimResync=(primsChange==ChangeNotice.RESYNC))
Called when prims in the USD stage have changed.
625941cdbf627c535bc132d5
def process_row(sm, row, options): <NEW_LINE> <INDENT> for f in options.foreign: <NEW_LINE> <INDENT> foreign_obj = get_deep(row, f) <NEW_LINE> if foreign_obj is not None: <NEW_LINE> <INDENT> sm.process_foreign_object(f, foreign_obj) <NEW_LINE> <DEDENT> <DEDENT> obj = get_deep(row, options.source) <NEW_LINE> if obj is N...
Process row from the log sm: RedShiftSchemaMaker object row: a dict representing a log line options: command line options
625941cd21a7993f00bc7df5
def test_status(self): <NEW_LINE> <INDENT> resp = self.app.get('/service/v1/status.json') <NEW_LINE> assert resp.content_type == 'application/json' <NEW_LINE> result = json.loads(resp.data) <NEW_LINE> import datetime <NEW_LINE> from victims_web.blueprints.service_v1 import EOL <NEW_LINE> assert result['version'] == '1'...
Verifies the status data is correct.
625941cd6aa9bd52df036eaa
def exec_next(ins): <NEW_LINE> <INDENT> if flow.loop_iterate(ins): <NEW_LINE> <INDENT> util.skip_to(ins, util.end_statement+(',',)) <NEW_LINE> if util.skip_white_read_if(ins, (',')): <NEW_LINE> <INDENT> return exec_next(ins)
NEXT: iterate for-loop.
625941cdec188e330fd5a8a5
def download_preview_files_from_another_instance(project=None): <NEW_LINE> <INDENT> if project: <NEW_LINE> <INDENT> project_dict = gazu.project.get_project_by_name(project) <NEW_LINE> preview_files = ( PreviewFile.query.join(Task) .filter(Task.project_id == project_dict["id"]) .all() ) <NEW_LINE> <DEDENT> else: <NEW_LI...
Download all preview files and related (thumbnails and low def included).
625941cdd4950a0f3b08c455
@login_required <NEW_LINE> def new_entry(request, topic_id): <NEW_LINE> <INDENT> topic = Topic.objects.get(id=topic_id) <NEW_LINE> if request.method != 'POST': <NEW_LINE> <INDENT> form = EntryForm() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> form = EntryForm(data=request.POST) <NEW_LINE> if form.is_valid(): <NEW_LIN...
Dodanie nowego wpisu dla określonego tematu.
625941cd8c3a8732951584c1
def store_file(self, file_path, content_hash=None): <NEW_LINE> <INDENT> return storage.archive_file(file_path, content_hash=content_hash)
Put a file into permanent storage so it can be visible to other stages.
625941cd0c0af96317bb82ee
def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore): <NEW_LINE> <INDENT> for index, pair in enumerate(zip(param_arrays, grad_arrays)): <NEW_LINE> <INDENT> arg_list, grad_list = pair <NEW_LINE> if grad_list[0] is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> kvstore.push(index, grad_list, priority...
Perform update of param_arrays from grad_arrays on kvstore.
625941cde8904600ed9f2032
@cli.group('nic', options_metavar=COMMAND_OPTIONS_METAVAR) <NEW_LINE> def nic_group(): <NEW_LINE> <INDENT> pass
Command group for managing NICs. In addition to the command-specific options shown in this help text, the general options (see 'zhmc --help') can also be specified right after the 'zhmc' command name.
625941cde8904600ed9f2033
def __setitem__(self, key, value): <NEW_LINE> <INDENT> key = str(key) <NEW_LINE> if self.lower: <NEW_LINE> <INDENT> key = key.lower() <NEW_LINE> <DEDENT> self.freq[key] = int(value) <NEW_LINE> self.add_token(key)
Set the frequency for a word to a value. If the key is not in the dictionary, add it to the dictionary and set its frequency to value.
625941cdaad79263cf390b47
def test_initial(dispatcher, cls): <NEW_LINE> <INDENT> instance = cls() <NEW_LINE> assert instance.mykeyword == "SomeValue" <NEW_LINE> instance.bind(dispatcher) <NEW_LINE> assert instance.mykeyword == "SomeValue"
Test the integrity checking for keywords.
625941cd851cf427c661a615
def treeview_signal_safe_toggler(func): <NEW_LINE> <INDENT> def wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> treeSelection = self.sidebar.treeview.get_selection() <NEW_LINE> treeSelection.disconnect(self.sidebar.select_signal) <NEW_LINE> func_return = func(self, *args, **kwargs) <NEW_LINE> self.sidebar.select_si...
Gtk.TreeView() :changed: signal should be disable before new selection is added, if connect it will trigger the change.
625941cd091ae35668667064
def _get_text_size(self): <NEW_LINE> <INDENT> if self._text_size is None: <NEW_LINE> <INDENT> self._text_size = self.control.GetFullTextExtent( self._get_text() or 'M') <NEW_LINE> <DEDENT> return self._text_size
Returns the text size information for the window.
625941cdbe383301e01b558b
def test_two_mint_in_between(cp, share, cptime): <NEW_LINE> <INDENT> cp.newCheckpoint(share, cptime, {"from": accounts[0]}) <NEW_LINE> cp.newCheckpoint(share, cptime + 100, {"from": accounts[0]}) <NEW_LINE> _sleep(110) <NEW_LINE> assert cp.totalSupplyAt(share, cptime) == 100000 <NEW_LINE> share.mint(accounts[1], 100000...
two checkpoints - mint in between
625941cd5e10d32532c5f02d
def update_syslog_settings_with_http_info(self, syslog_settings, **kwargs): <NEW_LINE> <INDENT> all_params = ['syslog_settings', 'ids', 'names'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('...
Update Syslog settings This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_syslog_settings_with_http_info(sy...
625941cdbe383301e01b558c
def review_network(net, use_symbol=False, timing=True, num_rep=1, dir_out='', print_model_size=False): <NEW_LINE> <INDENT> shape = (6, 4, 16, 160, 160) <NEW_LINE> if use_symbol: <NEW_LINE> <INDENT> x1 = symbol.Variable('x1') <NEW_LINE> x2 = symbol.Variable('x2') <NEW_LINE> y = net(x1, x2) <NEW_LINE> if print_model_size...
inspect the network architecture & input - output use_symbol: set True to inspect the network in details timing: set True to estimate inference time of the network num_rep: number of inference
625941cd63f4b57ef0001220
def area(self): <NEW_LINE> <INDENT> return (self.width * self.height)
return the value of an area
625941cd4d74a7450ccd42ca
@cpython_api([PyObject, CONST_STRING], PyObject) <NEW_LINE> def PySequence_Fast(space, w_obj, m): <NEW_LINE> <INDENT> if isinstance(w_obj, W_ListObject): <NEW_LINE> <INDENT> w_obj.convert_to_cpy_strategy(space) <NEW_LINE> return w_obj <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return W_ListObject.newlist_cpyext(space...
Returns the sequence o as a tuple, unless it is already a tuple or list, in which case o is returned. Use PySequence_Fast_GET_ITEM() to access the members of the result. Returns NULL on failure. If the object cannot be converted to a sequence, and raises a TypeError, raise a new TypeError with m as the message text....
625941cd99fddb7c1c9de497
def test_member_creation_email(self): <NEW_LINE> <INDENT> self.assertEqual(self.member.email_address, u"ignucius@example.org")
The member constructor must set the email right
625941cd3cc13d1c6d3c7480
def generate_data_stream(models, event_num=100): <NEW_LINE> <INDENT> instance_num = len(models) <NEW_LINE> data_stream = [] <NEW_LINE> for _ in range(event_num): <NEW_LINE> <INDENT> random_model = models[randint(0, instance_num - 1)] <NEW_LINE> data_stream.append(random_model.params) <NEW_LINE> <DEDENT> return data_str...
Generates a list of events. :param models: :param event_num: number of events to generate :type event_num: int :return: list of generated events :rtype: list
625941cda934411ee375179a
def load_embeddings(path, vocab, source_domain, target_domain, emb_name): <NEW_LINE> <INDENT> pkl = './work/embeddings/%s_%s_%s.pkl' % (source_domain, target_domain, emb_name) <NEW_LINE> if os.path.exists(pkl): <NEW_LINE> <INDENT> print("Load embeddings from existing pkl file %s..." % pkl) <NEW_LINE> embeddings = pickl...
load pre-trained word embeddings from the disk :param path: absolute path of the embedding files :param vocab: vocabulary :param ds_name: name of dataset :param emb_name: name of word embedding :return:
625941cd57b8e32f524835a1
def __str__(self): <NEW_LINE> <INDENT> return self.get_bit_string() + '=' + str(self.dec_rep)
Readable representation of self Returns ------- str
625941cdd99f1b3c44c67695
def set_favorited_scene(self, sceneId, prevSceneId=None): <NEW_LINE> <INDENT> with self.__fav_lock: <NEW_LINE> <INDENT> if not self.__sceneController.has(sceneId): <NEW_LINE> <INDENT> raise AutomationException(11092, "sceneId does not belongs to any scene - sceneId provided: " + str(sceneId)) <NEW_LINE> <DEDENT> nextSc...
sceneId - can be either favorited/non-favorited scene, but must be a valid scene id. prevSceneId - must be another favorited scene or error is raised. Both updating and executing doesn't blocks a scene from adding to/removing from favorited list.
625941cdad47b63b2c50a085
def write_psf(self, filename, type=XPLOR): <NEW_LINE> <INDENT> _psfgen.write_psf(psfstate=self._data, filename=filename, type=type)
Writes the current molecule state out as a psf file Args: filename (str): Filename to write to type (str): Type of psf file to write, in ["charmm", "x-plor"]
625941cdcad5886f8bd270e0
def check_token(token): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return is_valid_token(get_remote(), token.access_token) <NEW_LINE> <DEDENT> except ConnectionError: <NEW_LINE> <INDENT> return True
Check validity of a GitHub access token.
625941cdcc0a2c11143dcf97
def test_06_upload_remote_rpms(self): <NEW_LINE> <INDENT> RHUIManagerCLI.packages_remote(RHUA, CUSTOM_REPOS[1], self.remote_content["rpm"]) <NEW_LINE> RHUIManagerCLI.packages_remote(RHUA, CUSTOM_REPOS[1], self.remote_content["ftp"]) <NEW_LINE> RHUIManagerCLI.packages_remote(RHUA, CUSTOM_REPOS[2], self.remote_content["h...
upload content from remote servers to the custom repos
625941cd627d3e7fe0d68f56
def fetchPrimeKey(self): <NEW_LINE> <INDENT> print(gogo.timestamp() + 'Loading representative key') <NEW_LINE> k = self.ui.tableKey.currentIndex().row() <NEW_LINE> self.K = algo.load_rgba(self.settings['keyframes'][k]) <NEW_LINE> self.gridX, self.gridY = algo.grid(self.K)
Load representative key bitmap, and set up mesh grid. Keeping these things in memory saves a bit of precious time.
625941cd16aa5153ce36257f
def processbytes(rawdata): <NEW_LINE> <INDENT> def _method1(rawdata): <NEW_LINE> <INDENT> step1 = rawdata.decode("utf-8") <NEW_LINE> step2 = step1.encode("raw_unicode_escape") <NEW_LINE> try: <NEW_LINE> <INDENT> doubledecoded = step2.decode("utf-8") <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> ret...
# Scenario good data: >>> s = "jürgen" gooddata = s.encode('utf-8') gooddata b'jürgen' >>> rawdata = gooddata >>> step1 = rawdata.decode("utf-8") step1 'jürgen' >>> step2 = step1.encode("raw_unicode_escape") step2 b'jürgen' # code >>> point U+00FC is the Ü, that is why. But is this byte sequence >>> meaningful? >...
625941cdbd1bec0571d90736
def to_example(dictionary): <NEW_LINE> <INDENT> features = {} <NEW_LINE> for (k, v) in six.iteritems(dictionary): <NEW_LINE> <INDENT> if not v: <NEW_LINE> <INDENT> raise ValueError("Empty generated field: %s", str((k, v))) <NEW_LINE> <DEDENT> if isinstance(v[0], six.integer_types): <NEW_LINE> <INDENT> int64_list = tf.t...
Convert python dictionary to tf.train.Example
625941cd8c0ade5d55d3eac1
def get_window_titles(): <NEW_LINE> <INDENT> execution.logger.debug('Get window titles') <NEW_LINE> return get_browser().get_window_titles()
Return a list with the titles of all the open windows/tabs
625941cdcb5e8a47e48b7bb1
def draw_spirograph(radii, speeds, pos=[], canvas_size=(600, 600), draw_color=(200, 125, 150), circle_color=(150, 100, 200)): <NEW_LINE> <INDENT> canvas = np.zeros(canvas_size + (3,), dtype='uint8') + 50 <NEW_LINE> cx = canvas_size[1] // 2 <NEW_LINE> cy = canvas_size[0] // 2 <NEW_LINE> parent_x = parent_y = parent_radi...
Draw a spirograph animation The spirograph will be made up of bordering circles rotating at given angular speeds :param radii: a list of radii of to specify the size of each circle :param speeds: a list of angular velocities to be applied to each circle. len(speeds) == len(radii) - 1; th...
625941cd31939e2706e4cf71
@blueprint.route('/entry/<int:oid>', methods=['PUT']) <NEW_LINE> @login_required <NEW_LINE> def put_handler(oid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> body = request.json <NEW_LINE> title = body.pop('title', None) <NEW_LINE> completed = body.pop('completed', None) <NEW_LINE> description = body.pop('description'...
Update specific todo entry for logged in user
625941cdd6c5a10208144152
@pytest.mark.manual <NEW_LINE> @pytest.mark.tier(2) <NEW_LINE> def test_add_multiple_iso_datastore(): <NEW_LINE> <INDENT> pass
Add two RHEV providers. Under Infrastructure- PXE -ISO datastore - add ISO datastore for first provider Add new datastore button should not be disabled once the datastore was added and second datastore can be added. Polarion: assignee: jhenner casecomponent: Services initialEstimate: 1/8h startsin: 5.5
625941cd435de62698dfdd53
def disable(): <NEW_LINE> <INDENT> global _logging_handler <NEW_LINE> if _logging_handler: <NEW_LINE> <INDENT> root_logger = logging.getLogger() <NEW_LINE> root_logger.handlers.remove(_logging_handler) <NEW_LINE> _logging_handler = None
Disables logging to FreeCAD console (or STDOUT). Note, logging may be enabled by another imported module, so this isn't a guarentee; this function undoes logging_enable(), nothing more.
625941cd94891a1f4081bbb0
def gcd(a, b): <NEW_LINE> <INDENT> while b: <NEW_LINE> <INDENT> b, a = a%b, b <NEW_LINE> <DEDENT> return a
Computes greatest common divisor of positive integers a and b using the Euclidean algorithm.
625941cd1f5feb6acb0c4c57
def create_constraint(self, parent_body, parent_link_id=-1, child_body=-1, child_link_id=-1, joint_type=Simulator.JOINT_FIXED, joint_axis=(0., 0., 0.), parent_frame_position=(0., 0., 0.), child_frame_position=(0., 0., 0.), parent_frame_orientation=(0., 0., 0., 1.), child_frame_orientation=(0., 0., 0., 1.)): <NEW_LINE> ...
Create a constraint between two links belonging to the same body or two different bodies. You can also create a constraint between a body/link and a world frame. Args: parent_body (int, Body): parent body (or its unique id) parent_link_id (int): parent link index (or -1 for the base) child_body (int, Body)...
625941cd925a0f43d2549f7e
def try_load(obj, description): <NEW_LINE> <INDENT> return obj(**description)
Load the object, as-is.
625941cd3d592f4c4ed1d174
def __fetch_item(self, filtered, verbose): <NEW_LINE> <INDENT> items = [] <NEW_LINE> if not isinstance(filtered, QuerySet): <NEW_LINE> <INDENT> filtered = [filtered] <NEW_LINE> <DEDENT> for cur_filtered in filtered: <NEW_LINE> <INDENT> can_append = True <NEW_LINE> if self.__fetch_type == 'developers': <NEW_LINE> <INDEN...
Fetch the given timeline item
625941cde64d504609d74946
def resolve_path_or_url(path_or_url, backend_config=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return resolve_url(path_or_url, backend_config=None) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> if os.path.isfile(path_or_url): <NEW_LINE> <INDENT> native_path = pathlib.Path(path_or_url) <NEW_LINE> r...
Given either a path (absolute or relative), or a URL, attempt to resolve it. Returns a tuple consisting of: a :py:class:`slicedimage.backends._base.Backend`, the basename of the object, and the baseurl of the object.
625941cd67a9b606de4a7fc1
def runProcess(self, env, request, qargs=[]): <NEW_LINE> <INDENT> p = CGIProcessProtocol(request) <NEW_LINE> self._reactor.spawnProcess(p, self.filename, [self.filename] + qargs, env, os.path.dirname(self.filename))
Run the cgi script. @type env: A C{dict} of C{str}, or L{None} @param env: The environment variables to pass to the process that will get spawned. See L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for more information about environments and process creation. @type request: L{twisted.web.http...
625941cde64d504609d74947
def get_price_list(prod_id=0): <NEW_LINE> <INDENT> prod_id = cleanRecordID(prod_id) <NEW_LINE> prod_list = [] <NEW_LINE> where = '' <NEW_LINE> if prod_id > 0: <NEW_LINE> <INDENT> where = "p.id = {}".format(prod_id,) <NEW_LINE> <DEDENT> products = Product(g.db).select_active(where=where) <NEW_LINE> if products: <NEW_LIN...
Return a list of dicts with product and model for price list
625941cd3d592f4c4ed1d175
def depaginate(api, result): <NEW_LINE> <INDENT> meta = result['meta'] <NEW_LINE> if meta['next'] is None: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> ret_meta = meta.copy() <NEW_LINE> ret_objects = result['objects'] <NEW_LINE> while meta['next']: <NEW_LINE> <INDENT> next_url = urlparse.urlparse(meta['next'])...
Depaginate the first (or only) page of a paginated result
625941cdb830903b967e9a12
def isWall(mapObj, x, y): <NEW_LINE> <INDENT> if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif mapObj[x][y] in ('#', 'x'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
判断当前坐标是否为墙
625941cd009cb60464c634b8
def main(): <NEW_LINE> <INDENT> n_input = int(input()) <NEW_LINE> i = 1 <NEW_LINE> for i in range(n_input): <NEW_LINE> <INDENT> print(i) <NEW_LINE> if (i%3) == 0: <NEW_LINE> <INDENT> print("Fizz") <NEW_LINE> <DEDENT> if(i%5) == 0: <NEW_LINE> <INDENT> print("Buzz") <NEW_LINE> <DEDENT> if (i%3) == 0 and (i%5) == 0: <NEW_...
@author : Mounika2010 Read number from the input, store it in variable num.
625941cd91af0d3eaac9bb20
def getRadioEpisodes() -> list: <NEW_LINE> <INDENT> global radioURL <NEW_LINE> e = requests.get(radioURL, timeout=2).json()['Episodes'] <NEW_LINE> for i in e: <NEW_LINE> <INDENT> e[e.index(i)]['url'] = makeRadioURL(transformDate(e[e.index(i)]['Date'])) <NEW_LINE> <DEDENT> e = sorted(e, key=lambda x: dateValue(x['Date']...
Returns radio episodes as a list of dicts, each with an additional parameter, 'url', which is a link to the audio on fotfproxy.tk
625941cd5fc7496912cc3a85
def extract_regbase(bedfile, outpath, summarize='max'): <NEW_LINE> <INDENT> if os.path.exists(outpath): <NEW_LINE> <INDENT> os.remove(outpath) <NEW_LINE> <DEDENT> head_file = REGBASE_DIR / REGBASE <NEW_LINE> header = pd.read_csv(head_file, sep=r'\s+', nrows=3).columns <NEW_LINE> header = header.values.tolist() <NEW_LIN...
Extract rows from regBase file corresponding to variants in input bedfile.
625941cdcc40096d61595a57
def load_sf_from_file(c,s,t, cf, ct, cd=sf_count_duration, ifPN=True): <NEW_LINE> <INDENT> if ifPN: <NEW_LINE> <INDENT> NN_number=PN_number <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> NN_number=LN_number <NEW_LINE> <DEDENT> sf_sum = zeros(NN_number) <NEW_LINE> count_num = int(floor(1.0*(ct-cf)/cd)) <NEW_LINE> if cf <...
This func reads spike freq files generated by generate_sf_file() c, s, and t are couple, shift, and trial, as above cf and ct are count from and count to ... return an array of PN_number size, item of which is spike freq of each PN ... # an example of using this a=load_sf_from_file(0,0,0, 1100,3500) b=load_sf_from_...
625941cd99fddb7c1c9de498
def parameter(self, parameter): <NEW_LINE> <INDENT> if isinstance(parameter, sa.Column): <NEW_LINE> <INDENT> table = self.parent_class.metadata.tables[ parameter.table.name + '_history' ] <NEW_LINE> if self.parent and table == self.parent.__table__: <NEW_LINE> <INDENT> return getattr(self.parent, parameter.name) <NEW_L...
Parses SQLAlchemy BindParameter
625941cd23e79379d52ee66b
def return_max_profit(prices): <NEW_LINE> <INDENT> if len(prices) < 2: <NEW_LINE> <INDENT> raise IndexError('There must be at least two prices to compare.') <NEW_LINE> <DEDENT> max_profit = prices[1] - prices[0] <NEW_LINE> min_price = prices[0] <NEW_LINE> max_price = prices[0] <NEW_LINE> for price in prices: <NEW_LINE>...
This function returns the max profit from a hypothetical list of stock prices set out in chronological order. ---Arguments--- prices (list): a list of hypothetical stock prices
625941cdaad79263cf390b48
def lowpass(self, y_new): <NEW_LINE> <INDENT> if not self.mvsig: <NEW_LINE> <INDENT> y_new = y_new <NEW_LINE> self.y_t = self.alpha*y_new + (1-self.alpha)*self.y_inertia <NEW_LINE> self.y_inertia = self.y_t <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y_new = array(y_new) <NEW_LINE> self.y_...
Low-pass filter y_new := new measurement contribution y_inertia := inertia from pervious sensor outputs alpha := filtering factor, (heavy filter) 0 <= a <= 1 (no filter)
625941cd566aa707497f466f
def _send_messages( self, messages: List[bytes], sender: Union[socket.socket, asyncio.DatagramTransport], destination: Tuple[str, int], ) -> None: <NEW_LINE> <INDENT> for idx, message in enumerate(messages): <NEW_LINE> <INDENT> self._send_message(sender, destination, message) <NEW_LINE> if idx != len(messages): <NEW_LI...
Send messages with a short delay between them.
625941cdb5575c28eb68e107
@click.command("init-db") <NEW_LINE> @with_appcontext <NEW_LINE> def init_db_command() -> None: <NEW_LINE> <INDENT> init_db() <NEW_LINE> click.echo("Initialized the database.")
Clear existing data and create new tables.
625941cd7047854f462a1511
def logout(): <NEW_LINE> <INDENT> for host in HOST: <NEW_LINE> <INDENT> request(host + LOGOUT_PATH)
logout NKU_WLAN. 注销网关尝试host列表的所有网关记录,一一注销
625941cd9f2886367277a994
def lucky_numbers(n): <NEW_LINE> <INDENT> assert n >= 1 <NEW_LINE> if n < 3: <NEW_LINE> <INDENT> return [1] <NEW_LINE> <DEDENT> sieve = list(range(1, n + 1, 2)) <NEW_LINE> sieve_index = 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> sieve_len = len(sieve) <NEW_LINE> if (sieve_index + 1) > sieve_len: <NEW_LINE> <INDENT>...
Lucky numbers from 1 up-to n http://en.wikipedia.org/wiki/Lucky_number
625941cdcc40096d61595a58
def torrent_historical_ip(self, ip): <NEW_LINE> <INDENT> return self._get('query/torrent/historical/' + self._is_ip(ip))
Details about torrents transferred by an Host, with data up to 6 months List of torrent events for the specified host, with events for each time that a new transfer was detected on the DHT. https://docs.binaryedge.io/api-v2/#v2querytorrenthistoricaltarget Args: ip: IPv4 address Returns: A dict created from th...
625941cd3eb6a72ae02ec5e4
def test_metrics_agent_adminrouter_nginx_drop_requests_seconds(dcos_api_session: DcosApiSession) -> None: <NEW_LINE> <INDENT> state_response = dcos_api_session.get('/state', host=dcos_api_session.masters[0], port=5050) <NEW_LINE> assert state_response.status_code == 200 <NEW_LINE> state = state_response.json() <NEW_LIN...
nginx_vts_*_request_seconds* metrics are not present.
625941cdd7e4931a7ee9e025
def scheduled(self): <NEW_LINE> <INDENT> if self.schedule_sync: <NEW_LINE> <INDENT> self.schedule_sync.notify()
Notify the message of being scheduled. Called internally by the message queue.
625941cd287bf620b61d3b6b
@filters.i18n('org.innoscript.desktop.strings.resources') <NEW_LINE> @webmethods.quixui(of_type=RootFolder, template='../ui.Dlg_UserSettings.quix', template_engine='normal_template') <NEW_LINE> def user_settings(self): <NEW_LINE> <INDENT> settings = context.user.settings <NEW_LINE> taskbar_pos = settings.value.setdefau...
Displays the user settings dialog
625941cd5166f23b2e1a5260
def plot_fft(x, style='b'): <NEW_LINE> <INDENT> pylab.plot(numpy.arange(len(x))/float(len(x)), numpy.abs(numpy.fft.fft(x)) , style)
Convenience routine for plotting fft's of signal with normalised frequency axis.
625941cd30bbd722463cbecd
def load_factor(self) -> float: <NEW_LINE> <INDENT> return self.elements_added / (self.capacity * self.bucket_size)
float: How full the Cuckoo Filter is currently
625941cdbe8e80087fb20d4a
def _handle_event(self, image, name, code): <NEW_LINE> <INDENT> image.button_is_down = code == 1 <NEW_LINE> if code == 1: <NEW_LINE> <INDENT> if self._show_down_key(name): <NEW_LINE> <INDENT> logging.debug('Switch to %s, code %s' % (name, code)) <NEW_LINE> image.switch_to(name) <NEW_LINE> <DEDENT> return <NEW_LINE> <DE...
Handle an event given image and code.
625941cd26238365f5f0ef75
def move(self, abs_time, clear=True): <NEW_LINE> <INDENT> if clear: <NEW_LINE> <INDENT> self.clear_transformation() <NEW_LINE> <DEDENT> abs_time = abs_time.simplified <NEW_LINE> p_0 = self.trajectory.get_point(abs_time).simplified <NEW_LINE> self.translate(p_0) <NEW_LINE> rot_ax, angle = self._find_next_rotation_time(a...
Move to a position of the body in time *abs_time*. If *clear* is true clear the transformation matrix first.
625941cd4527f215b584c55e
def example_params(): <NEW_LINE> <INDENT> config = tf.contrib.training.HParams( init_mean_factor=0.1, init_logstd=0.1, policy_layers=(100, 100), value_layers=(100, 100), num_agents=30, clipping_coef=0.2, gae_gamma=0.99, gae_lambda=0.95, entropy_loss_coef=0.01, value_loss_coef=1, optimizer=tf.train.AdamOptimizer, learni...
Example hyperparameters.
625941cd01c39578d7e74f43
def sampleFull(self,vis,steps): <NEW_LINE> <INDENT> for i in xrange(steps): <NEW_LINE> <INDENT> state = self.sampleHidden(vis,4) <NEW_LINE> vis = self.sampleVisible(state) <NEW_LINE> <DEDENT> state[0] = vis <NEW_LINE> return state
Sample from P(h,v) of the DBM using Gibbs sampling. Parameters ---------- vis : array-like, shape (n_units) Visible data to initially condition on during Gibbs sampling steps : int Number of steps to gibbs sample
625941cd3346ee7daa2b2e73
def _resetAll(self): <NEW_LINE> <INDENT> self._resetCurrentPage() <NEW_LINE> self._resetPageCount() <NEW_LINE> self.resetPerPage() <NEW_LINE> self.resetRequiredPage() <NEW_LINE> self.resetCurrentPageHeader() <NEW_LINE> self.resetPageCountHeader()
Переопределяет соответствующий родительский метод.
625941cd15baa723493c407d
def promotion_check(self, thought): <NEW_LINE> <INDENT> rv = None <NEW_LINE> if not thought._blogged and thought.mindset and thought.mindset.kind == "mindspace": <NEW_LINE> <INDENT> if thought.upvote_count() >= self.required_votes(): <NEW_LINE> <INDENT> logger.info("Promoting {} to {} blog".format(though...
Promote a Thought to this movement's blog if it has enough upvotes Args: thought (Thought): The thought to be promoted Returns: None: If no promotion was done Thought: The new blog post
625941cde1aae11d1e749dbe