code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def transition(self): <NEW_LINE> <INDENT> assert self.state in range(6) <NEW_LINE> if self.state in [0,3]: <NEW_LINE> <INDENT> self.gen_send() <NEW_LINE> <DEDENT> elif self.state in [1,4]: <NEW_LINE> <INDENT> self.do_send() <NEW_LINE> <DEDENT> elif self.state in [2,5]: <NEW_LINE> <INDENT> if self.rx_queue.empty(): <NEW...
Determine what state we are currently in, and depending on this state, and possibly the ack channel, determine what to do next.
625941e591f36d47f21ac92c
def format_as_html(text): <NEW_LINE> <INDENT> if '<html>' in text or '<body>' in text or '<p>' in text: return text <NEW_LINE> start = u'<html><head></head><body>' <NEW_LINE> end = u'</body></html>' <NEW_LINE> text = text.replace('\r\n', '\n') <NEW_LINE> text = re.sub('^\s*$','', text, flags=re.M) <NEW_LI...
html = format_as_html(text) Format as HTML
625941e5a79ad161976cc57a
def cast(*args): <NEW_LINE> <INDENT> return _itkBinaryStatisticsKeepNObjectsImageFilterPython.itkBinaryStatisticsKeepNObjectsImageFilterIUS3IUS3_cast(*args)
cast(itkLightObject obj) -> itkBinaryStatisticsKeepNObjectsImageFilterIUS3IUS3
625941e5090684286d50f120
def signup(self, request, user): <NEW_LINE> <INDENT> user_institution = self.cleaned_data.get('institution') <NEW_LINE> user_homepage = self.cleaned_data.get('homepage') <NEW_LINE> user_i_devel = self.cleaned_data.get('interest_in_devel') <NEW_LINE> user_i_deploy = self.cleaned_data.get('interest_in_deploy') <NEW_LINE>...
Invoked at signup time to complete the signup of the user.
625941e5236d856c2ad44c15
def getlvl2termnums(energies): <NEW_LINE> <INDENT> energies = energies.split('\n')[1:] <NEW_LINE> terms = {} <NEW_LINE> termnums = [0] <NEW_LINE> for energy in energies: <NEW_LINE> <INDENT> term = energy.split()[-3].strip('(') <NEW_LINE> term = energy.split()[-5] + energy.split()[-4] + term <NEW_LINE> if term not in te...
generates a list whose elements correspond to the term number of a level in the adf04 file. So, the 0th index would correspond to the term number (starting at 1) of the first level.
625941e59b70327d1c4e120c
def updateEntry(job): <NEW_LINE> <INDENT> elixir.metadata.bind = DATABASE_CONNECTION_STR <NEW_LINE> elixir.metadata.bind.echo = False <NEW_LINE> elixir.setup_all() <NEW_LINE> _convertTimeStamps(job) <NEW_LINE> entry = Blackboard.query.filter_by(GlobalJobId=job.GlobalJobId).one() <NEW_LINE> modified = 0 <NEW_LINE> attrs...
Fetch the existing entry for job and update it.
625941e5f548e778e58cd9b5
def test_itemErr(self): <NEW_LINE> <INDENT> user=User() <NEW_LINE> user.username="testuser2" <NEW_LINE> user.first_name="first" <NEW_LINE> user.email="test@example.com" <NEW_LINE> password="secret" <NEW_LINE> self.assertRaises(ldaplib.ldap.LDAPError,ldaplib.save,user) <NEW_LINE> self.assertRaises(Exception,ldaplib.chan...
Test when something is error
625941e523849d37ff7b34c1
def h2_obs_to_liab(h2_obs, P, K): <NEW_LINE> <INDENT> if np.isnan(P) and np.isnan(K): <NEW_LINE> <INDENT> return h2_obs <NEW_LINE> <DEDENT> if K <= 0 or K >= 1: <NEW_LINE> <INDENT> raise ValueError('K must be in the range (0,1)') <NEW_LINE> <DEDENT> if P <= 0 or P >= 1: <NEW_LINE> <INDENT> raise ValueError('P must be i...
Converts heritability on the observed scale in an ascertained sample to heritability on the liability scale in the population. Parameters ---------- h2_obs : float Heritability on the observed scale in an ascertained sample. P : float in (0,1) Prevalence of the phenotype in the sample. K : float in (0,1) P...
625941e52eb69b55b151ccea
@app.route('/searchHome', methods=['GET', 'POST']) <NEW_LINE> def search_home(): <NEW_LINE> <INDENT> address = request.form['address'] <NEW_LINE> citystatezip = request.form['citystatezip'] <NEW_LINE> results = api.search_by_address(address, citystatezip) <NEW_LINE> return render_template('results.html', results=result...
Endpoint for search home form, calls api service
625941e54527f215b584c888
def regenerate_repositories(db_info, repo_info): <NEW_LINE> <INDENT> db = cbdatabase_db.CouchbaseDB(db_info) <NEW_LINE> repo_base_dir = pathlib.Path(repo_info['repo_basedir']) <NEW_LINE> repo_cache = cbutil_git.RepoCache() <NEW_LINE> os.makedirs(repo_base_dir, exist_ok=True) <NEW_LINE> for proj in db.query_documents('p...
Run through all project documents found in build database, extract remote info from each and checkout/update bare repositories for each project
625941e526068e7796caf11a
def initialize(self): <NEW_LINE> <INDENT> pages = [] <NEW_LINE> sects = self.opts.sections() <NEW_LINE> sects.sort() <NEW_LINE> for section in sects: <NEW_LINE> <INDENT> box = gtk.VBox() <NEW_LINE> sectlab = ''.join([section[0].upper(), section[1:]]) <NEW_LINE> tid = self.nb.append_page(box, gtk.Label(sectlab)) <NEW_L...
Load the initial database options into the config editor, and generate the required widgets.
625941e5a17c0f6771cbe484
def create_logger(log_file): <NEW_LINE> <INDENT> global logger <NEW_LINE> logger = logging.getLogger(__name__) <NEW_LINE> if config['LOG']['LEVEL'] == 'DEBUG': <NEW_LINE> <INDENT> logger.setLevel(logging.DEBUG) <NEW_LINE> <DEDENT> elif config['LOG']['LEVEL'] == 'ERROR': <NEW_LINE> <INDENT> logger.setLevel(logging.ERROR...
Logging
625941e55fc7496912cc3db3
def create_action(self, fs_title, **kwargs): <NEW_LINE> <INDENT> return self.__parent.create_action(fs_title, **kwargs)
create action
625941e5cc40096d61595d84
def on_ini_file_close(self): <NEW_LINE> <INDENT> self.flow_ini = None <NEW_LINE> self.material_dict = None <NEW_LINE> self.current_problem = None <NEW_LINE> self.output_dir = None <NEW_LINE> self.mesh = None <NEW_LINE> self.toolBar.removeAction(self.action_solve) <NEW_LINE> self.toolBar.removeAction(self.action_solve_2...
when ini file is closed application has to close all related stuff
625941e5cb5e8a47e48b7ed9
def doctest_init_local_facility(): <NEW_LINE> <INDENT> pass
Initialize Local Facility Encryption disabled: >>> conf_path = tempfile.mktemp() >>> with open(conf_path, 'w') as f: ... f.write(''' ... [encryptingstorage:encryption] ... enabled = false ... ''') >>> encrypt_util.init_local_facility({'__file__': conf_path}) >>> encrypt_util.ENCRYPTION_UTILITY ...
625941e5a8370b7717052cd2
def parseConfigTemplate(self, templatePath, cfg): <NEW_LINE> <INDENT> system = os.path.split(templatePath.rstrip('/'))[1] <NEW_LINE> if system.lower().endswith('system'): <NEW_LINE> <INDENT> system = system[:-len('System')] <NEW_LINE> <DEDENT> templatePath = os.path.join(templatePath, 'ConfigTemplate.cfg') <NEW_LINE> i...
Parse the ConfigTemplate.cfg files. :param str templatePath: path to the folder containing a ConfigTemplate.cfg file :param CFG cfg: cfg to merge with the systems config :returns: CFG object
625941e5498bea3a759b9ee3
def ruch_czlowieka(plansza, czlowiek): <NEW_LINE> <INDENT> legal = prawidlowy_ruch(plansza) <NEW_LINE> ruch = None <NEW_LINE> while ruch not in legal: <NEW_LINE> <INDENT> ruch = podaj_liczbe("Jaki będzie Twój ruch? (0 - 8):", 0, liczba_pol) <NEW_LINE> if ruch not in legal: <NEW_LINE> <INDENT> print("\nTo pole jest już ...
Odczytuje ruch człowieka.
625941e5462c4b4f79d1db05
def parse_call_tree(call_tree_string): <NEW_LINE> <INDENT> call_tree_dicts = [] <NEW_LINE> for match in re.finditer(CALL_TREE_REGEX, call_tree_string): <NEW_LINE> <INDENT> element = match.groupdict() <NEW_LINE> for key in ('index', 'size', 'ref'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> element[key] = int(element[...
Parse the call tree and returns a list of dictionaries of the elements :param call_tree_string: call tree as printed in the map file :return: list of dictionaries for each element with the following keys: - index: index of the element as printed - func_name: name of the function - level: level of indentatio...
625941e58e71fb1e9831dbdd
def _parse_traceback(self, text): <NEW_LINE> <INDENT> file_word_index = text.find('File') <NEW_LINE> comma_min_index = text.find(',') <NEW_LINE> file_name = text[file_word_index + 6:comma_min_index - 1] <NEW_LINE> lineno = text[comma_min_index + 7:].strip() <NEW_LINE> return (file_name, lineno)
Parse a line of python traceback and returns a tuple with (file_name, lineno)
625941e5bf627c535bc13605
def prox_l1(Y, alpha, n_orient): <NEW_LINE> <INDENT> n_positions = Y.shape[0] // n_orient <NEW_LINE> norms = np.sqrt((Y * Y.conj()).real.T.reshape(-1, n_orient).sum(axis=1)) <NEW_LINE> shrink = np.maximum(1.0 - alpha / np.maximum(norms, alpha), 0.0) <NEW_LINE> shrink = shrink.reshape(-1, n_positions).T <NEW_LINE> activ...
Proximity operator for l1 norm with multiple orientation support. Please note that this function computes a soft-thresholding if n_orient == 1 and a block soft-thresholding (L2 over orientation and L1 over position (space + time)) if n_orient == 3. See also :footcite:`GramfortEtAl2013b`. Parameters ---------- Y : arr...
625941e526238365f5f0f2a9
def _get_l1_mlist(n): <NEW_LINE> <INDENT> global _l1_bucket_max <NEW_LINE> if n == 1: <NEW_LINE> <INDENT> mlist = [1] <NEW_LINE> <DEDENT> elif n <= _l1_bucket_max: <NEW_LINE> <INDENT> mlist = [n, 2*n, n*n] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mlist = [n, 2*n] <NEW_LINE> <DEDENT> return mlist
n is the number of keys in the hash function. Guessing a good size for the hash table. Try squaring number of keys but that is too much. if we use n, we get minimal perfect hash functions
625941e5baa26c4b54cb1551
def set_reference_distance(self, dict_bb): <NEW_LINE> <INDENT> df_bb = self.convert_bb_dict_to_df(dict_bb) <NEW_LINE> df_dist_diag_1 = self.get_df_distances(df_bb.iloc[[0]], df_bb.iloc[[1]], mode=self.distance_mode) <NEW_LINE> df_dist_diag_2 = self.get_df_distances(df_bb.iloc[[2]], df_bb.iloc[[3]], mode=self.distance_m...
:param dict_bb: Bounding box dictionary :return: Average length of diagonals of bounding box
625941e550812a4eaa59c753
def bfs_clone_graph(self, node): <NEW_LINE> <INDENT> cg = UndirectedGraphNode(node.label) <NEW_LINE> copy_map = {node: cg} <NEW_LINE> queue = deque([node]) <NEW_LINE> while queue: <NEW_LINE> <INDENT> cur = queue.popleft() <NEW_LINE> for nb in cur.neighbors: <NEW_LINE> <INDENT> if nb not in copy_map: <NEW_LINE> <INDENT>...
Clone graph use BFS
625941e5379a373c97cfaf7c
def remove_single_char(self, string_text): <NEW_LINE> <INDENT> tokens = self.wordTokenizer.tokenize(string_text) <NEW_LINE> no_single_char_string = ' '.join([t for t in tokens if len(t) > 1]) <NEW_LINE> return no_single_char_string
remove single char items from @param string_text
625941e53539df3088e2e781
def qhparse(self, response): <NEW_LINE> <INDENT> item = AmacProductItem() <NEW_LINE> js = json.loads(response.text)[0] <NEW_LINE> configs = [ {'n': '产品名称', 'En': 'pro_name', 't': 'json', 'v': 'MPI_NAME', 'dt': ''}, {'n': '产品编码', 'En': 'pro_No', 't': 'json', 'v': 'MPI_PRODUCT_CODE', 'dt': ''}, {'n': '管理人', 'En': 'manage...
基金业协会-期货资产管理计划
625941e5c432627299f0507f
def gaussian_general(en, en_0=10., w=1.): <NEW_LINE> <INDENT> return 1. / np.sqrt(np.pi * w**2) * np.exp(-(en - en_0)**2 / w**2)
Gaussian number flux spectrum Standard normal distribution with :math:`\mu` = ``en_0`` and :math:`\sigma` = ``w`` / sqrt(2): .. math:: \phi(E, E_0, W) = 1 / \sqrt{\pi}W \cdot \exp\{-(E - E_0)^2 / W^2\} Almost normalized to unit number flux :math:`\int_0^\infty \phi(E) \text{d}E = 1` (ignoring the negative ta...
625941e5a4f1c619b28b0465
def rend(self): <NEW_LINE> <INDENT> return _pypl.DoubleVectorVector_rend(self)
rend(DoubleVectorVector self) -> std::vector< std::vector< double > >::reverse_iterator
625941e54e696a04525c9883
def register_extension(self, ext_cls, configs=None): <NEW_LINE> <INDENT> instance = ext_cls() <NEW_LINE> self._instance.registerExtensions([instance], configs) <NEW_LINE> return ext_cls
This will register an extension class with self._instance. You may pass any additional configs required for your extension It is best to call this when starting your Flask app, ie.:: from .mdx_simpl import SimpleExtension md = Markdown(app) md.register_extension(SimpleExtension) Any additional configuration a...
625941e529b78933be1e5adc
def UKDataRPI(self, indicID='', indicName='', beginDate='', endDate='', field=''): <NEW_LINE> <INDENT> code, result = self.client.getData(vs.UKDATARPI%(indicID, indicName, beginDate, endDate, field)) <NEW_LINE> return _ret_data(code, result)
包含英国零售价格指数(RPI)数据,具体指标可参见API文档;历史数据从1948年开始,按月更新。
625941e59f2886367277acbf
def test_0000_initiate_users( self ): <NEW_LINE> <INDENT> self.logout() <NEW_LINE> self.login( email=common.test_user_1_email, username=common.test_user_1_name ) <NEW_LINE> test_user_1 = test_db_util.get_user( common.test_user_1_email ) <NEW_LINE> assert test_user_1 is not None, 'Problem retrieving user with email %s f...
Create necessary user accounts and login as an admin user.
625941e5d164cc6175783185
def set_dashboard_tags(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.set_dashboard_tags_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.set_dashboard_tags_with_http_info(id,...
Set all tags associated with a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.set_dashboard_tags(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id...
625941e5187af65679ca5556
def get_related_source(): <NEW_LINE> <INDENT> db.refs.delete_many({}) <NEW_LINE> pattern = re.compile('[a-zA-Z]+://(.*?)/(.*?)') <NEW_LINE> items = db.cve_meta.find({}) <NEW_LINE> for item in items: <NEW_LINE> <INDENT> for ref in item['refs']: <NEW_LINE> <INDENT> refs = {} <NEW_LINE> result = re.match(pattern,str(ref['...
获取ref表 :return:
625941e5ad47b63b2c50a3b4
def __init__(self, serial_device: str, baud_rate: int): <NEW_LINE> <INDENT> if baud_rate <= 0: <NEW_LINE> <INDENT> raise ValueError("Argument 'baud_rate' must be > 0.") <NEW_LINE> <DEDENT> if serial_device is None or len(serial_device) == 0: <NEW_LINE> <INDENT> raise ValueError("Argument 'serial_device' is invalid.") <...
Initialize a new serial communication bus. :param serial_device: name of the serial device to connect via. :param baud_rate: communication rate (baud).
625941e50c0af96317bb861d
@nt.raises(NameError) <NEW_LINE> def test_Case_attr_materials_order5(): <NEW_LINE> <INDENT> case2.materials = ['PSu', 'HA', 'dummy'] <NEW_LINE> case2.apply(bdft.geos_sample) <NEW_LINE> for snap, e in zip(case2.snapshots, expected2): <NEW_LINE> <INDENT> actual = snap['matl'].tolist() <NEW_LINE> nt.assert_equal(actual, e...
Check error is thrown if materials are not found inmat_props.
625941e5287bf620b61d3e97
@cli.command(help="Remove interests") <NEW_LINE> @click.pass_obj <NEW_LINE> def rm_interest(fb_: Fbook): <NEW_LINE> <INDENT> log.info("Loading interest list.") <NEW_LINE> interest_list = fb_.get_interest_list() <NEW_LINE> log.info(f"Found '{len(interest_list)}' interest(s).") <NEW_LINE> for interest in interest_list: <...
Remove all interests Args: fb_ (Fbook): Fbook helper obj
625941e557b8e32f524838d3
@innate() <NEW_LINE> def startproject(name): <NEW_LINE> <INDENT> management.call_command("startproject", name, template=PROJECT_TEMPLATE)
Create a new Django project with Charlette's settings.
625941e5d8ef3951e3243973
def setUp(self): <NEW_LINE> <INDENT> self.app = create_app() <NEW_LINE> self.client = self.app.test_client <NEW_LINE> self.database_name = "trivia_test" <NEW_LINE> self.database_path = "postgres://{}@{}/{}".format('john','localhost:5432', self.database_name) <NEW_LINE> setup_db(self.app, self.database_path) <NEW_LINE> ...
Define test variables and initialize app.
625941e5ad47b63b2c50a3b5
def style_doc_files(*files, max_len=119, check_only=False): <NEW_LINE> <INDENT> changed = [] <NEW_LINE> black_errors = [] <NEW_LINE> for file in files: <NEW_LINE> <INDENT> if os.path.isdir(file): <NEW_LINE> <INDENT> files = [os.path.join(file, f) for f in os.listdir(file)] <NEW_LINE> files = [f for f in files if os.pat...
Applies doc styling or checks everything is correct in a list of files. Args: files (several `str` or `os.PathLike`): The files to treat. max_len (`int`): The maximum number of characters per line. check_only (`bool`, *optional*, defaults to `False`): Whether to restyle file or just check if they s...
625941e5cb5e8a47e48b7eda
def vector_angle(a, b): <NEW_LINE> <INDENT> cosine_angle = dot_product(a, b) <NEW_LINE> sine_angle = norm(cross_product(a, b)) <NEW_LINE> return math.degrees(math.atan2(sine_angle, cosine_angle))
This function returns the angle in degrees between 2 3-dimensional vectors.
625941e58da39b475bd653af
def vcsGetProjectHelper(self, project): <NEW_LINE> <INDENT> raise RuntimeError('Not implemented')
Public method to instanciate a helper object for the project. @param project reference to the project object @ireturn the project helper object @exception RuntimeError to indicate that this method must be implemented by a subclass
625941e52c8b7c6e89b35bf3
def get_organization_guid(self): <NEW_LINE> <INDENT> if 'PREDIX_ORGANIZATION_GUID' in os.environ: <NEW_LINE> <INDENT> return os.environ['PREDIX_ORGANIZATION_GUID'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> info = self._get_organization_info() <NEW_LINE> for key in ('Guid', 'GUID'): <NEW_LINE> <INDENT> if key in inf...
Returns the GUID for the organization currently targeted.
625941e5a934411ee3751aca
def draw_page(mypad_pos): <NEW_LINE> <INDENT> if mypad_pos == 0: <NEW_LINE> <INDENT> stats_data(mypad, m1, PAGE1_X, PAGE2_Y) <NEW_LINE> <DEDENT> elif mypad_pos == SCREEN_HEIGHT: <NEW_LINE> <INDENT> stats_data(mypad, m2 ,PAGE2_X, PAGE2_Y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stats_data(mypad, m3, PAGE3_X, PAGE3...
Draw page according to the mypad_pos
625941e50c0af96317bb861e
def get_weekday_totals(movie_data): <NEW_LINE> <INDENT> movies_by_weekday = {"Sunday": 0, "Monday": 0, "Tuesday": 0, "Wednesday": 0, "Thursday": 0, "Friday": 0, "Saturday": 0} <NEW_LINE> for year in movie_data.keys(): <NEW_LINE> <INDENT> if year >= 2017: <NEW_LINE> <INDENT> for movie in movie_data[year]: <NEW_LINE> <IN...
data for movies watched by weekday bar chart
625941e573bcbd0ca4b2c4ab
def next(self): <NEW_LINE> <INDENT> raise NotImplementedError
Iterator method to retrieve results from provider.
625941e5b7558d58953c5341
def pdbref(accessing_obj, accessed_obj, *args, **kwargs): <NEW_LINE> <INDENT> return dbref(_to_account(accessing_obj), accessed_obj, *args, **kwargs)
Same as dbref, but making sure accessing_obj is an account.
625941e51f5feb6acb0c4f7f
def update(self, *args, **kwargs): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> if len(args) >= 1: <NEW_LINE> <INDENT> super().__init__(args[0]) <NEW_LINE> <DEDENT> if len(args) >= 2: <NEW_LINE> <INDENT> self.width = args[1] <NEW_LINE> <DEDENT> if len(args) >= 3: <NEW_LINE> <INDENT> self.height = args[2] <NEW_LINE>...
Updating the class reading variable arguments
625941e576d4e153a657ef69
def is_699(self): <NEW_LINE> <INDENT> return self.num == 699
Verify whether num property is 699
625941e53617ad0b5ed6832d
def map_score(probs,labels,weights,scores,data_type): <NEW_LINE> <INDENT> labels = labels[:,:,0] <NEW_LINE> one_prob = probs[:,:,0] <NEW_LINE> bs,ld = one_prob.shape <NEW_LINE> if FLAGS.filtered_setting: <NEW_LINE> <INDENT> topk_mask = np.zeros([bs,ld],dtype=np.float32) <NEW_LINE> for i in range(bs): <NEW_LINE> <INDENT...
Calculates Mean Average Precision MAP Args: probs: Probabilities. [FLAGS.batch_size, FLAGS.max_doc_length, FLAGS.target_label_size] labels: Sentence extraction gold levels [FLAGS.batch_size, FLAGS.max_doc_length, FLAGS.target_label_size] weights: Weights to avoid padded part [FLAGS.batch_size, FLAGS.max_doc_lengt...
625941e5cc40096d61595d85
def is_client(self, cid): <NEW_LINE> <INDENT> return self._clients.has_key(cid)
Gets if the given client ID is one for a known client.
625941e5adb09d7d5db6cbc3
def getLinks(self, force=False): <NEW_LINE> <INDENT> if 'continue' not in self.site.features: <NEW_LINE> <INDENT> raise exceptions.UnsupportedError("MediaWiki 1.21+ is required for this function") <NEW_LINE> <DEDENT> if self.exists is None: <NEW_LINE> <INDENT> self.setPageInfo() <NEW_LINE> <DEDENT> if self.exists is Fa...
Gets a list of all the internal links *on* the page force - Deprecated, unused
625941e530c21e258bdfa8d8
def testInvalidIdxType(self): <NEW_LINE> <INDENT> invalid_idx = 0.5 <NEW_LINE> err = r"`idx` should be a \(nested\) array/tuple, or an integer." <NEW_LINE> with self.assertRaisesRegexp(TypeError, err): <NEW_LINE> <INDENT> snt.SelectInput(idx=invalid_idx)
Checks error on invalid idx type.
625941e52ae34c7f2600d567
def minus_rep(user, decrease=1): <NEW_LINE> <INDENT> userdb = DBManager.get_user(user) <NEW_LINE> new_rep = userdb['reputation'] - decrease <NEW_LINE> DBManager.update_user(user, userdb['jobs'], new_rep)
Removes rep from a user :param decrease: :param user:
625941e58c3a8732951587f6
def set_swaps_per_turn(self,total): <NEW_LINE> <INDENT> self._swaps_per_turn = total
Set the value of swaps can use per turn VersusStatusBar.set_swaps_per_turn(tk.Frame, int)
625941e5d18da76e23532911
def addSparseJacobian(self, alpha, x, px, con): <NEW_LINE> <INDENT> return
Compute the Jacobian-vector product con = alpha*J(x)*px
625941e5a8ecb033257d3502
def back(self): <NEW_LINE> <INDENT> if len(self.history) == 1: <NEW_LINE> <INDENT> console.print("[red]This is the starting page!") <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> title = utils.detect_title(self.cmd) <NEW_LINE> idx = [h[0].lower() for h in self.history].index(title.lower()) <NEW_LINE> n ...
Go back a certain number of pages, 1 by default.
625941e5b5575c28eb68e43a
def getCodingTranscriptCoords(self, t): <NEW_LINE> <INDENT> exons = t['genomic_coords'] <NEW_LINE> t_coords = t['transcript_coords'] <NEW_LINE> cds_start = t['cds_start'] <NEW_LINE> cds_stop = t['cds_stop'] <NEW_LINE> strand = t['strand'] <NEW_LINE> is_neg_strand = (strand == "-") <NEW_LINE> result = [] <NEW_LINE> t_st...
Gets the GAF exons, but adjusts to only include exons that code. And truncates the UTR portions from GAF exons that do both.
625941e5a219f33f34628d9a
def glInitFragmentProgramOptionNV(): <NEW_LINE> <INDENT> from OpenGL import extensions <NEW_LINE> return extensions.hasGLExtension( _EXTENSION_NAME )
Return boolean indicating whether this extension is available
625941e50fa83653e46573ef
def server_connection(): <NEW_LINE> <INDENT> if app.config.get('COUCHDB_SERVER_USERNAME'): <NEW_LINE> <INDENT> couch = couchdb.Server(app.config['COUCHDB_SERVER']) <NEW_LINE> couch.resource.credentials = (app.config['COUCHDB_SERVER_USERNAME'], app.config['COUCHDB_SERVER_PASSWORD']) <NEW_LINE> <DEDENT> else: <NEW_LINE> ...
Not including server location since, this is deployed to localhost for now
625941e585dfad0860c3b292
def save(self, section, param, value): <NEW_LINE> <INDENT> if not self.config.has_section(section): <NEW_LINE> <INDENT> self.config.add_section(section) <NEW_LINE> <DEDENT> self.config.set(section, param, value) <NEW_LINE> self._write()
Save the configuration file.
625941e523849d37ff7b34c2
def solve(request, question_id, answer_id): <NEW_LINE> <INDENT> question = get_object_or_404(Question, pk=question_id) <NEW_LINE> if not request.user.is_authenticated(): <NEW_LINE> <INDENT> watch_secret = request.GET.get('watch', None) <NEW_LINE> try: <NEW_LINE> <INDENT> watch = Watch.objects.get(secret=watch_secret, e...
Accept an answer as the solution to the question.
625941e5293b9510aa2c36c8
def test_as_data_frame__no_headers(self): <NEW_LINE> <INDENT> data = { 'ROW_ID': ['1', '5'], 'ROW_VERSION': ['2', '1'], 'ROW_ETAG': ['etag1', 'etag2'], 'col': ['I like trains', 'weeeeeeeeeeee'] } <NEW_LINE> pd_df = pd.DataFrame(data) <NEW_LINE> expected_df = pd.DataFrame( index=['1_2_etag1', '5_1_etag2'], columns=['col...
Verify we don't assume a schema has defined headers when converting to a Pandas data frame
625941e5596a897236089ef1
def get_distribution(input_df, gender_dict): <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> for index, row in input_df.iterrows(): <NEW_LINE> <INDENT> print("Gender dist:"+str(100*counter/self.input_df.shape[0])) <NEW_LINE> tokenxs = tknzr.tokenize(row['Snippet']) <NEW_LINE> for token in tokenxs: <NEW_LINE> <INDENT> token ...
Calculates word distribution of gender data frame
625941e5e5267d203edce0ce
def sort_bwolist(bwolist, sort_key): <NEW_LINE> <INDENT> if sort_key == "newest": <NEW_LINE> <INDENT> bwolist.sort(key=attrgetter("created"), reverse=True) <NEW_LINE> <DEDENT> elif sort_key == "oldest": <NEW_LINE> <INDENT> bwolist.sort(key=attrgetter("created"), reverse=False) <NEW_LINE> <DEDENT> elif sort_key == "upda...
Sort a list of workflow objects for the list.
625941e5be383301e01b58b4
def get_market_buy_price(self, quote_amount=0, base_amount=0, **kwargs): <NEW_LINE> <INDENT> exclude_own_orders = kwargs.get('exclude_own_orders', True) <NEW_LINE> market_buy_orders = [] <NEW_LINE> if exclude_own_orders: <NEW_LINE> <INDENT> market_buy_orders = self.get_market_buy_orders(depth=self.fetch_depth) <NEW_LIN...
Returns the BASE/QUOTE price for which [depth] worth of QUOTE could be bought, enhanced with moving average or weighted moving average :param float | quote_amount: :param float | base_amount: :param dict | kwargs: bool | exclude_own_orders: Exclude own orders when calculating a price :return: price as float
625941e576e4537e8c351aac
def sortColors(self, nums: List[int]) -> None: <NEW_LINE> <INDENT> start, current, end = 0, 0, len(nums) - 1 <NEW_LINE> while current <= end: <NEW_LINE> <INDENT> if nums[current] == 0: <NEW_LINE> <INDENT> nums[start], nums[current] = nums[current], nums[start] <NEW_LINE> start += 1 <NEW_LINE> current += 1 <NEW_LINE> <D...
Do not return anything, modify nums in-place instead.
625941e516aa5153ce3628ae
def paintEvent(self, ev): <NEW_LINE> <INDENT> super(ScienDSpinBox, self).paintEvent(ev)
Add drawing of a red frame around the spinbox if the is_valid flag is False
625941e5cdde0d52a9e5346c
def decode_state(state_repr, no_spins, labels): <NEW_LINE> <INDENT> state = {} <NEW_LINE> for i in range(no_spins): <NEW_LINE> <INDENT> state[labels[no_spins-(i+1)]] = 1 if state_repr % 2 else -1 <NEW_LINE> state_repr //= 2 <NEW_LINE> <DEDENT> return state
Decode integer representation of state into array +/- 1 array. :param state_repr: integer to be decoded :type state_repr: int :param no_bits: how many bits to decode. Note that this parameter is neccessary because the leading zeros matter. :type no_bits: int :returns: array of len `no_bits `consisting of -1 and 1 re...
625941e6ab23a570cc2505bc
def setUp(self): <NEW_LINE> <INDENT> self.app = create_app() <NEW_LINE> self.client = self.app.test_client <NEW_LINE> self.db = SQLAlchemy() <NEW_LINE> self.database_path = os.environ['TEST_DATABASE_URL'] <NEW_LINE> setup_test_db(self.app, self.database_path) <NEW_LINE> self.headers = { 'Authorization': f'bearer {os.en...
Define test variables and initialize app.
625941e6f9cc0f698b140a2e
def get_mouse_distance(last_x, current_x, last_y, current_y): <NEW_LINE> <INDENT> delta_x = last_x - current_x <NEW_LINE> delta_y = last_y - current_y <NEW_LINE> return sqrt(delta_x**2 + delta_y**2)
Return mouse distance
625941e63d592f4c4ed1d498
def rollback(self): <NEW_LINE> <INDENT> if self.dbmi.__name__ == "psycopg2": <NEW_LINE> <INDENT> if self.connected: <NEW_LINE> <INDENT> self.connection.rollback()
Roll back the last transaction. This must be called in case a new query should be performed after a db error. This is only relevant for postgresql database.
625941e6004d5f362079a767
def merge_fah_trajectories(input_data_path, output_data_path, top_filename): <NEW_LINE> <INDENT> top = md.load(top_filename) <NEW_LINE> n_runs, n_clones = get_num_runs_clones(input_data_path) <NEW_LINE> for run in range(n_runs): <NEW_LINE> <INDENT> for clone in range(n_clones): <NEW_LINE> <INDENT> print(run, clone) <NE...
Strip the water for a set of trajectories. Parameters ---------- input_data_path : str Path to FAH Core17/Core18 data directory. E.g. XYZ/server2/data/SVRXYZ/PROJ10470/ output_data_path : str Path to dump merged HDF5 files with concantenated trajectories. Metadata for which files are processed are include...
625941e6956e5f7376d712a3
def _list(self, **kwargs): <NEW_LINE> <INDENT> offset = 0 <NEW_LINE> lp = None <NEW_LINE> if "list_parameters" in kwargs: <NEW_LINE> <INDENT> lp = kwargs["list_parameters"] <NEW_LINE> del kwargs["list_parameters"] <NEW_LINE> <DEDENT> attributes = self._cls().wash_args(**kwargs) <NEW_LINE> if lp is not None: <NEW_LINE> ...
Get the object(s) matching the filter. A ListParameters class may be added to the list of arguments as "list_parameters=...". :return: Generator that provides object instances
625941e6090684286d50f122
def removeConnection(self, connection): <NEW_LINE> <INDENT> self.__connections.remove(connection) <NEW_LINE> return True
Removes a connection to the list. Arguments: connection -- connection, connection to remove. Return: True if successful.
625941e685dfad0860c3b293
def clear(self): <NEW_LINE> <INDENT> self._condition.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> self._q.clear() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._condition.release()
clear() Remove all items from the queue.
625941e631939e2706e4d29b
def get_url_list(): <NEW_LINE> <INDENT> response = requests.get("http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000") <NEW_LINE> soup = BeautifulSoup(response.content, "html5lib") <NEW_LINE> menu_tag = soup.find_all(class_="uk-nav uk-nav-side")[1] <NEW_LINE> urls = [] <NEW_LINE> for li i...
获取所有URL目录列表
625941e6090684286d50f123
def core_SongDetail_V1(self, id): <NEW_LINE> <INDENT> url = self.baseurl + '/api/songDetail/v1' <NEW_LINE> r = requests.get(url, params={'id': id}) <NEW_LINE> return r
歌曲详情 @Method:get @param: 歌曲id @return: data:{songs:[ images,songName,collectCount,songUrl,userName,praiseCount,fanCount,portrait, listenCount,id,shareHtmlUrl,description,creatTime,songDuration,commentCount,category,lyric ]},msg,status
625941e6be8e80087fb21073
def create_folder(folder_name): <NEW_LINE> <INDENT> file_metadata = { 'name': folder_name, 'mimeType': 'application/vnd.google-apps.folder' } <NEW_LINE> file = drive_service.files().create(body=file_metadata, fields='id').execute() <NEW_LINE> print('Folder ID: %s' % file.get('id'))
Create a new folder
625941e69b70327d1c4e120e
def __init__(self, first_name, last_name, age): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.age = age
Init method. Args: first_name (str): first name of the student second_name (str): second name of the student. age (int): age of the student.
625941e65166f23b2e1a5590
def _generate_nnmodels(self, nnpatch): <NEW_LINE> <INDENT> iter_params = None <NEW_LINE> iter_pp_params = {'rescale': 1. / 255} <NEW_LINE> if Globals.TEST_ITERMODE == TestIterMode.ITER_NO: <NEW_LINE> <INDENT> iter_params = None <NEW_LINE> iter_pp_params = None <NEW_LINE> <DEDENT> elif Globals.TEST_ITERMODE == TestIterM...
Extend this method to implement custom generation of `nnmodels`.
625941e6a79ad161976cc57c
@view_config(route_name="doLogin") <NEW_LINE> def doLogin(request): <NEW_LINE> <INDENT> p = request.params <NEW_LINE> login_info = { "email": p["email"], "password": p["password"] } <NEW_LINE> account = request.api.index("accounts/login", params=login_info) <NEW_LINE> if account: <NEW_LINE> <INDENT> request.session["us...
Logins a user, then goes to index
625941e6bde94217f3683224
@nox.session(python=["3.6"]) <NEW_LINE> def tests(session: Session) -> None: <NEW_LINE> <INDENT> args = session.posargs or ["--cov"] <NEW_LINE> session.install("-r", "requirements.txt") <NEW_LINE> session.install( "pytest", "pytest-cov", "coverage[toml]", "nameko", ) <NEW_LINE> session.run("pytest", *args)
Nox session for running unittests.
625941e69c8ee82313fbbbad
def Page(self): <NEW_LINE> <INDENT> self._page_count += 1 <NEW_LINE> self.Finish(last_page=False) <NEW_LINE> self._rows = [] <NEW_LINE> self._nest = []
Flushes the current resource page output.
625941e666656f66f7cbc5e4
def test_bytes_long_bothpw(self): <NEW_LINE> <INDENT> frame = FramePasswordChangeRequest(currentpassword="x" * 32, newpassword="y" * 32) <NEW_LINE> self.assertEqual( bytes(frame), b"\x00C0\x02xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyq" )
Test FramePasswordChangeRequest with long passwords.
625941e6a79ad161976cc57d
@after.all <NEW_LINE> def stop_stubs(_scenario): <NEW_LINE> <INDENT> world.browser.quit() <NEW_LINE> for name in SERVICES.keys(): <NEW_LINE> <INDENT> stub_server = getattr(world, name, None) <NEW_LINE> if stub_server is not None: <NEW_LINE> <INDENT> stub_server.shutdown()
Shut down any stub services.
625941e6d268445f265b52a6
def find_pack(inputstr): <NEW_LINE> <INDENT> global oppacks <NEW_LINE> inimport = False <NEW_LINE> output = "" <NEW_LINE> importbody = "" <NEW_LINE> for i in inputstr: <NEW_LINE> <INDENT> if i == ".": <NEW_LINE> <INDENT> inimport = not inimport <NEW_LINE> if not inimport: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> im...
find_pack finds OpPack imports in Integ code, executes the corresponding file, and deletes the definition so that metaparse can use it.
625941e6796e427e537b0a01
def t380000_x9(): <NEW_LINE> <INDENT> assert GetCurrentStateElapsedTime() > 2 <NEW_LINE> assert t380000_x1(gesture1=17, z1=9019, flag3=6067) <NEW_LINE> MainBonfireMenuFlag() <NEW_LINE> while True: <NEW_LINE> <INDENT> ClearTalkListData() <NEW_LINE> AddTalkListDataIf(GetEventStatus(14000101) == 1 or GetEventStatus(2050) ...
State 0,10
625941e6f548e778e58cd9b7
def __init__(self): <NEW_LINE> <INDENT> pass
Impute missing values If the Series is of dtype Object, then impute with the most frequent object. If the Series is not of dtype Object, then impute with the mean
625941e6adb09d7d5db6cbc4
def find_devices(self): <NEW_LINE> <INDENT> hid_devices = hid.enumerate() <NEW_LINE> devices = list(filter(self.is_console_hid, hid_devices)) <NEW_LINE> if not devices: <NEW_LINE> <INDENT> devices = self.find_devices_by_report(hid_devices) <NEW_LINE> <DEDENT> if self.vid and self.pid: <NEW_LINE> <INDENT> devices = list...
Returns a list of available teensy-style consoles.
625941e66fece00bbac2db7b
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ApiVersion): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941e64e696a04525c9885
@cli.command() <NEW_LINE> @click.argument("brightness", type=int, default=None, required=False) <NEW_LINE> @pass_dev <NEW_LINE> def brightness(dev, brightness): <NEW_LINE> <INDENT> if brightness: <NEW_LINE> <INDENT> click.echo("Setting brightness to %s" % brightness) <NEW_LINE> dev.set_brightness(brightness) <NEW_LINE>...
Gets or sets the brightness.
625941e650485f2cf553d1d3
@rest_call('PUT', '/network/<network>', Schema({ 'network': basestring, 'owner': basestring, 'access': basestring, 'net_id': basestring, })) <NEW_LINE> def network_create(network, owner, access, net_id): <NEW_LINE> <INDENT> auth_backend = get_auth_backend() <NEW_LINE> _assert_absent(model.Network, network) <NEW_LINE> i...
Create a network. If the network with that name already exists, a DuplicateError will be raised. If the combination of owner, access, and net_id is illegal, a BadArgumentError will be raised. If network ID allocation was requested, and the network cannot be allocated (due to resource exhaustion), an AllocationError ...
625941e6656771135c3ebcab
def test_get_planned_maintenance_view_filtered_jobs(self): <NEW_LINE> <INDENT> response = self.client.get(reverse("maintenance:planned-maintenance"), {"planned_jobs":"on", "start_date": "", "end_date": ""}) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(len(response.context["object_l...
filtered one class of objects expect the object list to have one element
625941e6d7e4931a7ee9e356
def exploit(self): <NEW_LINE> <INDENT> url = fuck.urlformate(URL,PORT,PATH) <NEW_LINE> exp = url+"call.php?action=query&num=j8g'%29/**/union/**/select/**/1,2,3,concat(username,0x7e,password),5,6,7,8,9,10,11,12,13,14,15,16/**/from/**/user/**/limit/**/0,1%23" <NEW_LINE> color.cprint("[*] Sending exp..",YELLOW) <NEW_LINE>...
start exploit
625941e656ac1b37e62645ff
def peek(self, figsize=(15, 5)): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> fig, axes = plt.subplots(nrows=1, ncols=3, figsize=figsize) <NEW_LINE> self.plot_containment(fraction=0.68, ax=axes[0]) <NEW_LINE> self.plot_containment(fraction=0.95, ax=axes[1]) <NEW_LINE> self.plot_containment_vs_energy(a...
Quick-look summary plots.
625941e6a4f1c619b28b0467
def config_sim_env(context): <NEW_LINE> <INDENT> if 'previous_module' in context() and context.previous_module == __file__: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> init_context() <NEW_LINE> if 'i_holding' not in context(): <NEW_LINE> <INDENT> context.i_holding = defaultdict(dict) <NEW_LINE> <DEDENT> cell = conte...
:param context: :class:'Context'
625941e6de87d2750b8601ce
def is_palindrome(word): <NEW_LINE> <INDENT> n = len(word) <NEW_LINE> for i, letter in enumerate(word): <NEW_LINE> <INDENT> if letter != word[n-i-1]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Funkcja sprawdza czy *word* jest palindromem
625941e6287bf620b61d3e98
def authorize(self, token): <NEW_LINE> <INDENT> token_info = self._get_token_from_cache(token) <NEW_LINE> return token_info
Check token authorization. :param token: user token
625941e6e8904600ed9f236b
def p_enamldef_body2(p): <NEW_LINE> <INDENT> items = filter(None, p[5]) <NEW_LINE> p[0] = (p[3], '', items)
enamldef_body : NEWLINE INDENT STRING NEWLINE enamldef_body_items DEDENT
625941e66fb2d068a760f4db
def test_ieee754(self): <NEW_LINE> <INDENT> assert fpu.infinity + fpu.infinity == fpu.infinity <NEW_LINE> assert fpu.isnan(fpu.nan) <NEW_LINE> assert fpu.isnan(0.0 * fpu.infinity) <NEW_LINE> assert fpu.isnan(fpu.infinity - fpu.infinity)
fpu.float respect ieee754 semantics.
625941e6460517430c3945b2
def set_clear_depth(depth=1.0): <NEW_LINE> <INDENT> gl.glClearDepth(float(depth))
Set the clear value for the depth buffer This is a wrapper for gl.glClearDepth. Parameters ---------- depth : float The depth to use.
625941e692d797404e3045c3