code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def enabled_on_current_os(properties): <NEW_LINE> <INDENT> if "deny_platforms" in properties: <NEW_LINE> <INDENT> if sys.platform.startswith("linux"): <NEW_LINE> <INDENT> curr_os = "Linux" <NEW_LINE> <DEDENT> elif sys.platform == "win32": <NEW_LINE> <INDENT> curr_os = "Windows" <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
Checks toolkit command properties to determine if a command is enabled on the current OS or not. :param dict properties: Properties dictionary as returned by the ``Engine.commands`` dictionary property. :returns: True if enabled, False if not.
625941d530bbd722463cbfe0
def remove_tag(self, id, tag_id): <NEW_LINE> <INDENT> return self._delete('api/posts/{0}/tags/{1}'.format(id, tag_id))
移除标签 :param id: 分享 ID :param tag_id: 标签 ID :return: 返回的 JSON 数据包
625941d5435de62698dfde65
def test_thank_you_view_redirect_anonymous(client, django_user_model): <NEW_LINE> <INDENT> user = django_user_model.objects.create_user(username='a', password='b') <NEW_LINE> transaction = models.SubscriptionTransaction.objects.create( user=user, amount='1.00', date_transaction=timezone.now() ) <NEW_LINE> response = cl...
Tests that anonymous users are redirected to login page.
625941d54527f215b584c66d
def handle_extracted_frame_features(self, features, frame, video_state, process_pool=None, *args, **kwargs): <NEW_LINE> <INDENT> if process_pool: <NEW_LINE> <INDENT> process_pool.apply_async( func=self.handle_sequential_buffer, value=(features, frame), video_state=video_state, *args, **kwargs ) <NEW_LINE> <DEDENT> retu...
:param features: :param frame: :param video_state: :param process_pool: :param args: :param kwargs: :return:
625941d55510c4643540f5f9
def svn_ra_invoke_push_wc_prop_func(*args): <NEW_LINE> <INDENT> return _ra.svn_ra_invoke_push_wc_prop_func(*args)
svn_ra_invoke_push_wc_prop_func(svn_ra_push_wc_prop_func_t _obj, void baton, char path, char name, svn_string_t value, apr_pool_t pool) -> svn_error_t
625941d54527f215b584c66e
def ensquared_energy(self, data): <NEW_LINE> <INDENT> if not have_scipy: <NEW_LINE> <INDENT> raise IQCalcError("Please install the 'scipy' module " "to use this function") <NEW_LINE> <DEDENT> tot = data.sum() <NEW_LINE> ny, nx = data.shape <NEW_LINE> cen_x = int(nx // 2) <NEW_LINE> cen_y = int(ny // 2) <NEW_LINE> ee = ...
Return a function of ensquared energy across pixel indices. Ideally, data is already a masked array and is assumed to be centered.
625941d52c8b7c6e89b359d9
def remove_val(df,name,val): <NEW_LINE> <INDENT> new= df[df[name] != val] <NEW_LINE> return new
Input: df - DataFrame name - name of the column val - value to be removed Output: DataFrame Work : Takes the name of column and the dataframe and delete the lowest
625941d556ac1b37e62643e6
def get_request_length(self): <NEW_LINE> <INDENT> remainder = self.stop_at - self.offset <NEW_LINE> return self.chunk_size if remainder > self.chunk_size else remainder
Return length of next chunk upload.
625941d550812a4eaa59c539
def runForFunctionName(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if args.verbose: <NEW_LINE> <INDENT> print('seting brightness to: {}'.format(args.brightness)) <NEW_LINE> print('Running {}'.format(args.function)) <NEW_LINE> <DEDENT> scrollphat.set_brightness(args.brightness) <NEW_LINE> if args.function == 'dance'...
Runs funcations from the other classes from parsed function name
625941d5d10714528d5ffefd
def movie_review(name): <NEW_LINE> <INDENT> reviews = ('See it!', 'A gem!', 'Ideological claptrap!',) <NEW_LINE> return reviews[randint(0, len(reviews)-1)]
Input: the name of a movie Output: a string (one of the review options), selected at random using randint
625941d5ad47b63b2c50a198
def undoCmd(self): <NEW_LINE> <INDENT> pass
Executes the user request (Ctrl Z)
625941d5460517430c39439a
def dump_flash_cookies(self, timeout=60): <NEW_LINE> <INDENT> self.total_timeout += timeout <NEW_LINE> if not self.contains_get_or_browse: <NEW_LINE> <INDENT> raise CommandExecutionError("No get or browse request preceding " "the dump storage vectors command", self) <NEW_LINE> <DEDENT> command = ('DUMP_FLASH_COOKIES',)...
dumps the local storage vectors (flash, localStorage, cookies) to db
625941d563f4b57ef000132e
def test_tmap_map(self): <NEW_LINE> <INDENT> expr = "R = tmap(singletmap) + A + map(singletmap)" <NEW_LINE> self.assertModule("t.rast.algebra", expression=expr, flags="gd", basename="r") <NEW_LINE> self.assertModule("t.rast.algebra", expression=expr, flags="g", basename="r") <NEW_LINE> D = tgis.open_old_stds("R", typ...
Test STDS + single map with and without timestamp
625941d5091ae35668667174
def get_min_quantity(self, instrument, account_row): <NEW_LINE> <INDENT> return self._b._getMinQuantity(instrument, account_row)
Gets the minimum size of a trade or of a market order. Parameters: instrument : The name of the instrument to get the trading setting for. account_row : The account information for the account to get the trading setting for. Returns:
625941d5a4f1c619b28b024e
def bollinger_bands(): <NEW_LINE> <INDENT> dates = pd.date_range('2012-01-01', '2012-12-31') <NEW_LINE> symbols = ['SPY'] <NEW_LINE> df = get_data(symbols, dates) <NEW_LINE> rm_SPY = get_rolling_mean(df['SPY'], window=20) <NEW_LINE> rstd_SPY = get_rolling_std(df['SPY'], window=20) <NEW_LINE> upper_band, lower_band = ge...
Bollinger Bands.
625941d57b180e01f3dc4a13
def numRabbits(self, answers): <NEW_LINE> <INDENT> d = defaultdict(int) <NEW_LINE> res = 0 <NEW_LINE> for i in answers: <NEW_LINE> <INDENT> d[i] += 1 <NEW_LINE> <DEDENT> for k, v in d.iteritems(): <NEW_LINE> <INDENT> if v <= k + 1: <NEW_LINE> <INDENT> res += (k + 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res += ...
:type answers: List[int] :rtype: int
625941d56e29344779a6282a
def test_create_short_link(self): <NEW_LINE> <INDENT> with main.db.connect() as conn: <NEW_LINE> <INDENT> conn.execute( main.table.insert(), TABLE_DATA ) <NEW_LINE> <DEDENT> with mock.patch("main.encrypt_url", return_value="aaaaaabc"): <NEW_LINE> <INDENT> with main.app.test_client() as _app: <NEW_LINE> <INDENT> respons...
Inserts some records to DB. Ensures, that old one will be removed And also checks, that new record will have correct hash
625941d53346ee7daa2b2f85
def _get_text(el): <NEW_LINE> <INDENT> response = '' <NEW_LINE> for segment in el.text_anchor.text_segments: <NEW_LINE> <INDENT> start_index = segment.start_index <NEW_LINE> end_index = segment.end_index <NEW_LINE> response += document.text[start_index:end_index] <NEW_LINE> <DEDENT> return response
Doc AI identifies form fields by their offsets in document text. This function converts offsets to text snippets.
625941d5bde94217f3683008
def _sage_(self): <NEW_LINE> <INDENT> from sage.matrix.constructor import matrix <NEW_LINE> from sage.modules.free_module_element import vector <NEW_LINE> from sage.rings.integer_ring import ZZ <NEW_LINE> result = repr(self) <NEW_LINE> result = result.replace("Pi", "pi") <NEW_LINE> if result[:6] == "Matrix": <NEW_LINE>...
Convert a maple expression back to a Sage expression. This currently does not implement a parser for the Maple output language, therefore only very simple expressions will convert successfully. EXAMPLES:: sage: m = maple('x^2 + 5*y') # optional - maple sage: m.sage() ...
625941d53cc13d1c6d3c7592
def __init__(self, *args): <NEW_LINE> <INDENT> this = _AriaPy.new_ArModeActs(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this
__init__(self, ArRobot robot, char name, char key, char key2, ArACTS_1_2 acts = None) -> ArModeActs __init__(self, ArRobot robot, char name, char key, char key2) -> ArModeActs
625941d5a4f1c619b28b024f
def create_gist(txt, fn, descr=None, github_user=None, github_token=None): <NEW_LINE> <INDENT> dry_run = build_option('dry_run') or build_option('extended_dry_run') <NEW_LINE> if descr is None: <NEW_LINE> <INDENT> descr = "(none)" <NEW_LINE> <DEDENT> if github_token is None: <NEW_LINE> <INDENT> github_token = fetch_git...
Create a gist with the provided text.
625941d5ec188e330fd5a9b5
def get_thickness(boundaries_in, ref_in, hemi, path_output, r=[0.4, 0.4, 0.4]): <NEW_LINE> <INDENT> if not os.path.exists(path_output): <NEW_LINE> <INDENT> os.makedirs(path_output) <NEW_LINE> <DEDENT> if r is not None: <NEW_LINE> <INDENT> resample_volume(ref_in, os.path.join(path_output, "ref.nii"), r, "Cu") <NEW_LINE>...
Get thickness. This function computes the cortical thickness as euclidean distances between vertex ras coordinates from outer levelset boundaries. Parameters ---------- boundaries_in : str Filename of 4D levelset image. ref_in : str Filename of reference volume for coordinate transformation. hemi : str ...
625941d50a50d4780f6670ac
def redraw(self): <NEW_LINE> <INDENT> pages = list(self.visiblePages()) <NEW_LINE> documents = set(page.document() for page in pages) <NEW_LINE> for document in documents: <NEW_LINE> <INDENT> cache.clear(document) <NEW_LINE> <DEDENT> for page in pages: <NEW_LINE> <INDENT> page.repaint()
Redraws, e.g. when you changed rendering hints or papercolor on the document.
625941d5627d3e7fe0d6906a
def grow_tree_from_stats_summaries(stats_summaries_list, feature_ids_list): <NEW_LINE> <INDENT> node_ids_per_feature = [] <NEW_LINE> gains_list = [] <NEW_LINE> thresholds_list = [] <NEW_LINE> left_node_contribs_list = [] <NEW_LINE> right_node_contribs_list = [] <NEW_LINE> all_feature_ids = [] <NEW_LINE> assert len(stat...
Updates ensemble based on the best gains from stats summaries.
625941d5956e5f7376d71085
def unpack(self, buffer, _pos): <NEW_LINE> <INDENT> _pos = EntityState.EntityState.unpack(self, buffer, _pos) <NEW_LINE> self.BankAngle = struct.unpack_from(">f", buffer, _pos)[0] <NEW_LINE> _pos += 4 <NEW_LINE> self.Speed = struct.unpack_from(">f", buffer, _pos)[0] <NEW_LINE> _pos += 4 <NEW_LINE> return _pos
Unpacks data from a bytearray and sets class members
625941d5283ffb24f3c55b18
def evaluate_score(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError
Score estimation. Signature depends on the type of estimator. The only returned value is the score with shape `(n_x)`.
625941d5adb09d7d5db6c9a7
def get(self, request, token): <NEW_LINE> <INDENT> user, token = self._authenticate_credentials(request, token) <NEW_LINE> if not user.is_valid: <NEW_LINE> <INDENT> user.is_valid = True <NEW_LINE> user.save() <NEW_LINE> return Response({"message": "youve been verified", "status": 200}, status=status.HTTP_200_OK) <NEW_L...
Method to activate a user after they click link in their emails
625941d58e71fb1e9831d9c2
def vp_start_gui(servIp,passw): <NEW_LINE> <INDENT> global val, w, root, start, ip, password <NEW_LINE> password = passw <NEW_LINE> ip =servIp <NEW_LINE> value = 1 <NEW_LINE> root = Tk() <NEW_LINE> root.title('IMer V2') <NEW_LINE> root.geometry('600x450+650+150') <NEW_LINE> w = New_Toplevel_1 (root) <NEW_LINE> if value...
Starting point when module is the main routine.
625941d57c178a314d6ef67b
def test_clean_empty(runner_with_mocked_store): <NEW_LINE> <INDENT> rmtree(runner_with_mocked_store.store.directory) <NEW_LINE> assert not os.path.exists(runner_with_mocked_store.store.directory) <NEW_LINE> clean(runner_with_mocked_store) <NEW_LINE> assert not os.path.exists(runner_with_mocked_store.store.directory)
Make sure clean succeeds when the directory doesn't exist.
625941d592d797404e3043a4
def setUp(self): <NEW_LINE> <INDENT> super(test_uniform_partition_uniform_distribution_rectangle_domain_2D, self).createData() <NEW_LINE> super( test_uniform_partition_uniform_distribution_rectangle_domain_2D, self).setUp()
Set up problem.
625941d526068e7796caeefa
def partition(self, s): <NEW_LINE> <INDENT> def helper(str, index): <NEW_LINE> <INDENT> if index == len(str): <NEW_LINE> <INDENT> res.append(list(path)) <NEW_LINE> return <NEW_LINE> <DEDENT> for i in range(index, len(str)): <NEW_LINE> <INDENT> left = index <NEW_LINE> right = i <NEW_LINE> while left < right and str[left...
:type s: str :rtype: List[List[str]]
625941d5c4546d3d9de72c4e
def longestPalindrome(self, s): <NEW_LINE> <INDENT> res = 0 <NEW_LINE> lst = [False] * 128 <NEW_LINE> for c in s: <NEW_LINE> <INDENT> lst[ord(c)] = not lst[ord(c)] <NEW_LINE> if not lst[ord(c)]: <NEW_LINE> <INDENT> res += 2 <NEW_LINE> <DEDENT> <DEDENT> if res < len(s): <NEW_LINE> <INDENT> res += 1 <NEW_LINE> <DEDENT> r...
:type s: str :rtype: int
625941d585dfad0860c3b074
def verify_consumer_seek(c, seek_to_msg): <NEW_LINE> <INDENT> tp = confluent_kafka.TopicPartition(seek_to_msg.topic(), seek_to_msg.partition(), seek_to_msg.offset()) <NEW_LINE> print('seek: Seeking to %s' % tp) <NEW_LINE> c.seek(tp) <NEW_LINE> while True: <NEW_LINE> <INDENT> msg = c.poll() <NEW_LINE> assert msg is not ...
Seek to message and verify the next consumed message matches. Must only be performed on an actively consuming consumer.
625941d54e4d5625662d45ef
def isub(self): <NEW_LINE> <INDENT> val2 = numpy.int32(self.stack.pop_op()) <NEW_LINE> val1 = numpy.int32(self.stack.pop_op()) <NEW_LINE> self.stack.push_op(val1 - val2)
implements the isub opcode
625941d51d351010ab855d35
def check_refinement_stability(self): <NEW_LINE> <INDENT> fpfdp_test_case.check_refinement_stability(self) <NEW_LINE> oxygen_fps = [ sc.fp for sc in self.xray_structure.scatterers() if sc.element_symbol()=='O' ] <NEW_LINE> oxygen_fdps = [ sc.fdp for sc in self.xray_structure.scatterers() if sc.element_symbol()=='O' ] <...
Shake the fps and fdps, then refine, then make sure they are all equal within a very small tolerance.
625941d550485f2cf553cfb4
def test_mul(self): <NEW_LINE> <INDENT> tr = Trace(data=np.arange(10)) <NEW_LINE> st = tr * 5 <NEW_LINE> assert len(st) == 5 <NEW_LINE> with pytest.raises(TypeError): <NEW_LINE> <INDENT> tr.__mul__(2.5) <NEW_LINE> <DEDENT> with pytest.raises(TypeError): <NEW_LINE> <INDENT> tr.__mul__('1234')
Tests the __mul__ method of the Trace class.
625941d58c0ade5d55d3ebd5
def fire(self, arg, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError
Fire this event. This method is called by the :meth:`EventHandler.fire_event` method.
625941d5ff9c53063f47c40c
def home(request, template_name='projector/home.html'): <NEW_LINE> <INDENT> return simple.direct_to_template(request, {'template': template_name})
Home view for projector app.
625941d54a966d76dd55122a
def save_credential(self): <NEW_LINE> <INDENT> Credential.credential_list.append(self)
methode to save credential globally
625941d5f9cc0f698b140813
def process_item(self, item, spider): <NEW_LINE> <INDENT> query = self.dbpool.runInteraction(self._conditional_insert, item) <NEW_LINE> query.addErrback(self._handle_error, item) <NEW_LINE> return item
Run db query in thread pool
625941d5dd821e528d63b3c1
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self.atom <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW_LINE> length = len(_x) <NEW_LINE> <DEDENT> buff.write(struct.pack('<I%ss'%length, length, _x)) <N...
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
625941d573bcbd0ca4b2c28f
@click.command('me', short_help='Update current user') <NEW_LINE> @click.option('--name', help='Name of user') <NEW_LINE> @click.option('--email', help='Email address (login username)') <NEW_LINE> @click.option('--password', help='Password') <NEW_LINE> @click.option('--status', help='Status eg. active, inactive') <NEW_...
Update current user details, including password reset.
625941d5b57a9660fec33aa0
def _load_released_version(): <NEW_LINE> <INDENT> global _version <NEW_LINE> global _revision <NEW_LINE> global _released <NEW_LINE> global _version_str <NEW_LINE> global _is_loaded <NEW_LINE> if not _is_loaded: <NEW_LINE> <INDENT> vc, v = _load_released_version_config() <NEW_LINE> if v is not None: <NEW_LINE> <INDENT>...
Load the release data if present. If not found the package is not released. A release can be made by adding a file called `VERSION` to the top level directory of a package. This is useful for user deploying a package and making custom releases. The RTEMS project reserves the `rtems-version.ini` file for it's releases...
625941d530c21e258bdfa6b7
def convert_molecule(in_filename, out_filename): <NEW_LINE> <INDENT> molecule_name, ext_in = parse_ligand_filename(in_filename) <NEW_LINE> molecule_name, ext_out = parse_ligand_filename(out_filename) <NEW_LINE> cmd = "obabel -i %s %s -o %s -O %s" % (ext_in[1:], in_filename, ext_out[1:], out_filename) <NEW_LINE> print(c...
Use openbabel to convert filenames. May not work for all file formats!
625941d58a349b6b435e838d
def get_contest_by_permalink(self, contest_permalink): <NEW_LINE> <INDENT> the_contest = None <NEW_LINE> try: <NEW_LINE> <INDENT> the_contest = Contest.objects.get( permalink=contest_permalink ) <NEW_LINE> <DEDENT> except Contest.DoesNotExist: <NEW_LINE> <INDENT> logger.debug("No open Contest exists with permalink %s" ...
Returns the contest with given permalink
625941d5d8ef3951e3243757
def __init__(self, db, ignorepath=None, filtr=False, cutTime=None, table=None, delFeatures=[], explval=10): <NEW_LINE> <INDENT> self.db = db <NEW_LINE> self.explval = explval <NEW_LINE> self.filtr = filtr <NEW_LINE> self.features = self.db.getFeatureList(cutTime=cutTime, table=table) <NEW_LINE> delstart = [] <NEW_LINE>...
Create all necessary variables, objects :param db: backend object to be used :param ignorepath: path to file containing names of features to be disregarded in encoding, instead pass through values unencoded :param filtr: Use filter for mapping objects? :param cutTime: time at which to start using emails for classificat...
625941d57cff6e4e81117b9f
@app.route('/api/user/') <NEW_LINE> def user(): <NEW_LINE> <INDENT> return jsonify({'id': request.parsed_data['args']['id'], 'name': 'test'})
Flasgger will try to load './examples/docs/user.yml' as swagger doc
625941d53317a56b86939e6e
def grab_key(self, window): <NEW_LINE> <INDENT> if not window: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> winclass = window.get_wm_class() <NEW_LINE> if not (winclass and winclass[-1] == self.winclass): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for modmask in vary_modmask(self.key[1], (X.Mod2Mask, X.LockMask))...
Grab the undesirable key on the given Windows if it's Firefox
625941d5a219f33f34628b81
def testParseValue(self): <NEW_LINE> <INDENT> parse_value = S3ResourceFilter._parse_value <NEW_LINE> self.assertEqual(parse_value("NONE"), None) <NEW_LINE> self.assertEqual(parse_value('"NONE"'), "NONE") <NEW_LINE> self.assertEqual(parse_value("None"), None) <NEW_LINE> self.assertEqual(parse_value('"None"'), "None") <N...
Test URL query value parser handling of NONE/None
625941d510dbd63aa1bd2dbc
@permission_classes((IsOwnerOrReadOnly, IsOwnerOrReadOnlyAuthor)) <NEW_LINE> @api_view(['GET', 'PUT', 'DELETE']) <NEW_LINE> def post_detail(request, pk): <NEW_LINE> <INDENT> if request.user.is_anonymous: <NEW_LINE> <INDENT> if request.method == 'DELETE': <NEW_LINE> <INDENT> return Response(status=status.HTTP_401_UNAUTH...
get: Retrieve a Post. put: Update a Post. delete: Delete a Post.
625941d57d847024c06be4d7
def test_20_merge_record_complex(self): <NEW_LINE> <INDENT> self.clear_database() <NEW_LINE> example = base_connector_merge_example() <NEW_LINE> rec_id1 = self.instance.save_element(example.from_node["attributes"], example.from_node["metadata"]) <NEW_LINE> attr_modified = dict() <NEW_LINE> attr_modified.update({"ex:a o...
In this example we test if we merge different attributes into one node **Graph-Strucutre** .. figure:: https://cdn.rawgit.com/dlr-sc/prov-db-connector/master/docs/_images/test_cases/test_20_merge_record_complex.svg :align: center :scale: 50 % **Input-Data** This is the attributes used to create the entry .....
625941d54e696a04525c9665
def trans(psy): <NEW_LINE> <INDENT> for invoke in psy.invokes.invoke_list: <NEW_LINE> <INDENT> sched = invoke.schedule <NEW_LINE> if not sched: <NEW_LINE> <INDENT> print(f"Invoke {invoke.name} has no Schedule! Skipping...") <NEW_LINE> continue <NEW_LINE> <DEDENT> make_sir_compliant(sched) <NEW_LINE> add_kernels(sched.c...
Transformation routine for use with PSyclone. It calls :py:func:`sir_trans.make_sir_compliant` and then :py:func:`kernels_trans.add_kernels` for each schedule in each invoke. :param psy: the PSy object which this script will transform. :type psy: :py:class:`psyclone.psyGen.PSy` :returns: the transformed PSy object. :...
625941d5009cb60464c635ca
def t250380_x28(): <NEW_LINE> <INDENT> if not GetEventStatus(72500102): <NEW_LINE> <INDENT> assert t250380_x3(text3=38060000, z3=72500102, flag16=1, mode13=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert t250380_x3(text3=38060010, z3=72500104, flag16=1, mode13=1) <NEW_LINE> <DEDENT> """State 4""" <NEW_LINE> ret...
State 0,1
625941d530c21e258bdfa6b8
def test_add_new_attributes(self): <NEW_LINE> <INDENT> dict_attr = {'name': 'Betty', 'last': 'Holberton', 'age': 40} <NEW_LINE> my_amenity = Amenity() <NEW_LINE> for key, value in dict_attr.items(): <NEW_LINE> <INDENT> setattr(my_amenity, key, value) <NEW_LINE> <DEDENT> for key, value in dict_attr.items(): <NEW_LINE> <...
Checks that can add new attributes to the objects
625941d5379a373c97cfad5f
def test_reference_number_other(self): <NEW_LINE> <INDENT> reference_number_template = 'LEBA/{agreement_type}' + str(self.date.year) + '{id}' <NEW_LINE> agreement_types = [agreement_type[0] for agreement_type in models.Agreement.AGREEMENT_TYPES] <NEW_LINE> for agreement_type in agreement_types: <NEW_LINE> <INDENT> agre...
Verify simple agreement reference # generation for all agreement types
625941d5656771135c3eba8a
def retry_mangled(get_set_del): <NEW_LINE> <INDENT> cls_name = cls.__name__ <NEW_LINE> @wraps(get_set_del) <NEW_LINE> def wrapper(self, name, *args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return get_set_del(self, name, *args) <NEW_LINE> <DEDENT> except AttributeError as err: <NEW_LINE> <INDENT> other_cls, _, nam...
Decorates the getter, setter or deleter of _cls_ to retry for mangled names after "re-mangling" the attribute name with the name of _cls_.
625941d5e64d504609d74a5a
def get_last_work_diretory(self): <NEW_LINE> <INDENT> self.last_work_dir = os.getcwd() <NEW_LINE> print("enter get_last_work_diretory() , last_work_dir = " + self.last_work_dir) <NEW_LINE> last_path_config_file = os.getcwd() + os.path.sep + "last_data_path.txt" <NEW_LINE> if os.path.exists(last_path_config_file): <NEW_...
Add this part to memory the last work directory. Due to confliction between backslash and escape character (with special character), when we save file path ( backslash included ) to a file (such as .txt file ), the system will change the path format to a Unix style, i.e, aaa/bbb, no matter what kind of OS we are using...
625941d5a79ad161976cc35f
def train(self, rl_environment): <NEW_LINE> <INDENT> for episode_number in range(self.number_of_episodes): <NEW_LINE> <INDENT> self.total_reward_gained = 0 <NEW_LINE> self.current_episode_number = episode_number <NEW_LINE> episode_steps = 0 <NEW_LINE> state = rl_environment.reset() <NEW_LINE> while True: <NEW_LINE> <IN...
This method trains the agent on the game environment :param rl_environment (obj:`Environment`): the environment to train the agent on
625941d5925a0f43d254a092
def __init__(self, body, seq=-1, update_ids_from_dap=False, **kwargs): <NEW_LINE> <INDENT> self.type = 'event' <NEW_LINE> self.event = 'stopped' <NEW_LINE> if body is None: <NEW_LINE> <INDENT> self.body = StoppedEventBody() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.body = StoppedEventBody(update_ids_from_dap=u...
:param string type: :param string event: :param StoppedEventBody body: :param integer seq: Sequence number.
625941d597e22403b379d1b4
def compat_as_text(str_): <NEW_LINE> <INDENT> def _recur_convert(s): <NEW_LINE> <INDENT> if isinstance(s, (list, tuple, np.ndarray)): <NEW_LINE> <INDENT> s_ = [_recur_convert(si) for si in s] <NEW_LINE> return _maybe_list_to_array(s_, s) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return tf.c...
Converts strings into `unicode` (Python 2) or `str` (Python 3). Args: str\_: A string or other data types convertible to string, or an `n`-D numpy array or (possibly nested) list of such elements. Returns: The converted strings of the same structure/shape as :attr:`str_`.
625941d563d6d428bbe44709
def _playout(self, state): <NEW_LINE> <INDENT> node = self._root <NEW_LINE> while(1): <NEW_LINE> <INDENT> if node.is_leaf(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> action, node = node.select(self._c_puct) <NEW_LINE> state.do_move(action) <NEW_LINE> <DEDENT> action_probs, _ = self._policy(state) <NEW_LINE> end, w...
Run a single playout from the root to the leaf, getting a value at the leaf and propagating it back through its parents. State is modified in-place, so a copy must be provided.
625941d57b25080760e39672
def merge(lst1, lst2): <NEW_LINE> <INDENT> if not lst1 or not lst2: <NEW_LINE> <INDENT> return lst1 + lst2 <NEW_LINE> <DEDENT> if lst1[0] < lst2[0]: <NEW_LINE> <INDENT> return [lst1[0]] + merge(lst1[1:], lst2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [lst2[0]] + merge(lst1, lst2[1:])
Merges two sorted lists. >>> merge([1, 3, 5], [2, 4, 6]) [1, 2, 3, 4, 5, 6] >>> merge([], [2, 4, 6]) [2, 4, 6] >>> merge([1, 2, 3], []) [1, 2, 3] >>> merge([5, 7], [2, 4, 6]) [2, 4, 5, 6, 7]
625941d5ec188e330fd5a9b6
def compute_partial_densities( self, molecules=["pol", "SOL", "NA", "CL"], binwidth=0.25, dim="z", fname=None, ): <NEW_LINE> <INDENT> data = {} <NEW_LINE> for res in molecules: <NEW_LINE> <INDENT> _sel = self.universe.select_atoms(f"resname {res}") <NEW_LINE> _lin = LinearDensity(_sel, binwidth=binwidth) <NEW_LINE> _li...
Compute the partial densities of molecules in the simulation box. If you wish to change which molecules are included, you can pass a list of resnames as the molecules argument. For a much quicker computation, do not unwrap the trajectory before calling this method. binwidth is the width of the bins in angstroms - den...
625941d5167d2b6e31218daf
def _connect_signals(self): <NEW_LINE> <INDENT> self.password_textbox.connect('changed', self.on_password_modified)
Connects the gtk signals
625941d51b99ca400220accc
def get_rundir(): <NEW_LINE> <INDENT> return _get_system_dir("/run/user/{}/pbapps/run")
Get the directory for regular .pid files.
625941d54428ac0f6e5baa0d
def update(self, bbox): <NEW_LINE> <INDENT> self.time_since_update = 0 <NEW_LINE> self.history = [] <NEW_LINE> self.hits += 1 <NEW_LINE> self.hit_streak += 1 <NEW_LINE> if bbox != []: <NEW_LINE> <INDENT> self.kf.update(self.convert_bbox_to_z(bbox))
Updates the state vector with observed bbox.
625941d5d164cc6175782f68
def contains(self, item): <NEW_LINE> <INDENT> return item in self.disposables
Determines whether the CompositeDisposable contains a specific disposable. Keyword arguments: item -- Disposable to search for Returns True if the disposable was found; otherwise, False
625941d58c3a8732951585d6
def feedback(plant, sensor=None): <NEW_LINE> <INDENT> if not isinstance(plant, signal.lti): <NEW_LINE> <INDENT> plant = signal.lti(*plant) <NEW_LINE> <DEDENT> if sensor is None: <NEW_LINE> <INDENT> sensor = signal.lti([1], [1]) <NEW_LINE> <DEDENT> elif not isinstance(sensor, signal.lti): <NEW_LINE> <INDENT> sensor = si...
Negative feedback connection of plant and sensor. If sensor is None, then it is assumed to be 1.
625941d5377c676e912723c2
def set_SellerSKU(self, value): <NEW_LINE> <INDENT> super(GetCompetitivePricingForSKUInputSet, self)._set_input('SellerSKU', value)
Set the value of the SellerSKU input for this Choreo. ((required, string) A comma-separated list of up to 20 SellerSKU values used to identify products in the given marketplace.)
625941d591f36d47f21ac70e
def testCeilWrongDim(self): <NEW_LINE> <INDENT> print(self.typeStr, "... ", file=sys.stderr) <NEW_LINE> ceil = SuperTensor.__dict__[self.typeStr + "Ceil"] <NEW_LINE> supertensor = np.arange(2*2*2, dtype=self.typeCode).reshape((2, 2, 2)) <NEW_LINE> self.assertRaises(TypeError, ceil, supertensor)
Test ceil function with wrong dimensions
625941d599cbb53fe6792e00
def get_count(self): <NEW_LINE> <INDENT> return self.counter
get current value of counter
625941d563b5f9789fde72ff
def to_dict(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'email': self.email, 'created_at': self.created_at }
Export user to a dictionary.
625941d5e8904600ed9f2149
def chi2(mod, dat, cov, CC): <NEW_LINE> <INDENT> argsum = dat - mod <NEW_LINE> AA = torch.sum(cov*argsum**2, dim=1) <NEW_LINE> BB = torch.sum(argsum*cov, dim=1) <NEW_LINE> chi = AA - (BB**2)/CC <NEW_LINE> return chi, BB/CC
mod: tensor (batch_size, ndata): model values dat: array (ndata): data values cov: array (ndata, ndata): data error
625941d5462c4b4f79d1d8ea
def list_surveys(self): <NEW_LINE> <INDENT> if self._survey_list is None: <NEW_LINE> <INDENT> survey_list_response = self.request("GET", "http://archive.eso.org/wdb/wdb/adp/phase3_main/form") <NEW_LINE> root = BeautifulSoup(survey_list_response .content, 'html5lib') <NEW_LINE> self._survey_list = [] <NEW_LINE> for sele...
List all the available surveys (phase 3) in the ESO archive. Returns ------- survey_list : list of strings
625941d59f2886367277aaa6
def _agg_sort_country_streams(self, streams_df): <NEW_LINE> <INDENT> return streams_df.sum(level='countryname').sort_values( 'total_streams', ascending=False)
Aggregate streams by country and sort in descending order.
625941d501c39578d7e75056
def get_env(): <NEW_LINE> <INDENT> file_name = '/'.join((os.path.dirname(os.path.abspath(__file__)), 'config.env')) <NEW_LINE> with open(file_name) as f: <NEW_LINE> <INDENT> env = f.read() <NEW_LINE> if env: <NEW_LINE> <INDENT> return env.strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ''
获取运行环境
625941d5187af65679ca5339
def calculate_bounding_box(origin: CoordinatePoint, radius: int) -> (float, float, float, float): <NEW_LINE> <INDENT> upper_right = point_from_distance_and_angle(origin, radius, 45) <NEW_LINE> lower_left = point_from_distance_and_angle(origin, radius, 225) <NEW_LINE> return (lower_left.latitude, lower_left.longitude, u...
Calculates the Bounding Box for the Overpass API
625941d5627d3e7fe0d6906b
@click.command() <NEW_LINE> @click.argument('infile', metavar='input', type=click.Path(exists=True)) <NEW_LINE> @click.argument('data-field', type=str, metavar='data-field') <NEW_LINE> @click.argument('outfile', metavar='output', type=click.Path(writable=True, allow_dash=True)) <NEW_LINE> @click.option('-m', '--method'...
Write a geodata file with bins based on a data field.
625941d51f5feb6acb0c4d68
def upgrade(product, old_buildversion, new_buildversion): <NEW_LINE> <INDENT> import sys <NEW_LINE> from django.utils.importlib import import_module <NEW_LINE> ensure_pootle_config() <NEW_LINE> product_module = '.'.join((__name__, product)) <NEW_LINE> import_module(''.join(('.', product)), __name__) <NEW_LINE> upgrade_...
Upgrade to the latest build version and executes any needed actions. :param product: Product that needs to be upgraded. It must be a valid module name in this package. :param old_buildversion: Old build version that was stored in the DB at the time of running the upgrade command. :param new_buildversion: New b...
625941d54f88993c3716c281
def generate_output_file_name(file_name, suffix): <NEW_LINE> <INDENT> main_part_of_name, file_extension = os.path.splitext( file_name) <NEW_LINE> if large_size: <NEW_LINE> <INDENT> suffix = suffix .replace(".png", "LARGE.png") <NEW_LINE> <DEDENT> return main_part_of_name + suffix
Takes a file name as an argument and returns string for the name of the output file. The generated name is based on the original file name. It also notes in name specific chromsomes or scaffolds if plotting was limited to those. Specific example ================ Calling function with ("data1.txt", "_plot.png") r...
625941d57d43ff24873a2ebb
def check_condition(self, condition, entry): <NEW_LINE> <INDENT> eval_locals = copy(entry) <NEW_LINE> eval_locals.update({'has_field': lambda f: f in entry, 'timedelta': datetime.timedelta, 'now': datetime.datetime.now()}) <NEW_LINE> try: <NEW_LINE> <INDENT> passed = safer_eval(condition, eval_locals) <NEW_LINE> if pas...
Checks if a given `entry` passes `condition`
625941d52c8b7c6e89b359da
def get_flexvol_capacity(self, flexvol_path=None, flexvol_name=None): <NEW_LINE> <INDENT> volume_id_attributes = {} <NEW_LINE> if flexvol_path: <NEW_LINE> <INDENT> volume_id_attributes['junction-path'] = flexvol_path <NEW_LINE> <DEDENT> if flexvol_name: <NEW_LINE> <INDENT> volume_id_attributes['name'] = flexvol_name <N...
Gets total capacity and free capacity, in bytes, of the flexvol.
625941d5099cdd3c635f0e75
def set_value(self, key, value): <NEW_LINE> <INDENT> self._ensure_have_load_only() <NEW_LINE> fname, parser = self._get_parser_to_modify() <NEW_LINE> if parser is not None: <NEW_LINE> <INDENT> section, name = _disassemble_key(key) <NEW_LINE> if not parser.has_section(section): <NEW_LINE> <INDENT> parser.add_section(sec...
Modify a value in the configuration.
625941d5ff9c53063f47c40d
def log2stdout(loglevel): <NEW_LINE> <INDENT> logging.basicConfig( format = '%(asctime)s %(levelname)s %(name)s: %(message)s' ) <NEW_LINE> logging.getLogger().setLevel(loglevel) <NEW_LINE> return logging.getLogger('checkIfMaintTooLong')
Setup logging
625941d530dc7b7665901b7f
def t_COMMENT_char(t): <NEW_LINE> <INDENT> pass
\"([^\\\n]|(\\.))*?\"
625941d5f548e778e58cd799
def create_run(self, dataset, run_info): <NEW_LINE> <INDENT> return self.data_service.create_run(dataset, run_info)
Create a new run metadata Parameters ---------- dataset: Dataset Object of the dataset metadata run_info: Run Object containing the metadata of the run. md_uri is ignored and created automatically by this method Returns ------- Run object with the metadata and the new created md_uri
625941d545492302aab5e4e0
def get_dc_mobile_data(self): <NEW_LINE> <INDENT> return self.dc.get("mobile_data", False)
Whether Mobile Clients should download Assessments (Data not just Forms) - e.g. when these are created through Targetting
625941d5b5575c28eb68e21c
def dpi(self): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument( '-d', '--dpi', type=int, default=0, required=False, help='DPI rate') <NEW_LINE> parser.add_argument( '-p', '--preset', type=int, default=0, required=False, help='Preset no. to set, starting from 1 (default)') <NEW_LINE...
get/set DPI
625941d5cb5e8a47e48b7cc2
def setDayAwardTime(self,datet,state = 1): <NEW_LINE> <INDENT> self.dayawardtime = datet <NEW_LINE> nowday = datetime.datetime.today() <NEW_LINE> if nowday.day != self.dayawardtime.day: <NEW_LINE> <INDENT> self._owner.icon.addIcon(self._owner.icon.DAY_AWARD,0,state = state)
设置上次领取每日奖励的时间
625941d5091ae35668667176
def viterbi(log_emlik, log_startprob, log_transmat, forceFinalState=True): <NEW_LINE> <INDENT> B = np.zeros(log_emlik.shape, dtype=int) <NEW_LINE> V = np.zeros(log_emlik.shape) <NEW_LINE> V[0] = log_startprob.flatten() + log_emlik[0] <NEW_LINE> for n in range(1, log_emlik.shape[0]): <NEW_LINE> <INDENT> for j in range(l...
Viterbi path. Args: log_emlik: NxM array of emission log likelihoods, N frames, M states log_startprob: log probability to start in state i log_transmat: transition log probability from state i to j forceFinalState: if True, start backtracking from the final state in the model, instead of...
625941d5498bea3a759b9cc9
def load_image_into_numpy_array(image): <NEW_LINE> <INDENT> if (image.mode == "RGBA") or (image.mode == "CMYK"): <NEW_LINE> <INDENT> image = image.convert("RGB") <NEW_LINE> <DEDENT> (im_width, im_height) = image.size <NEW_LINE> return np.array(image.getdata()).reshape( (im_height, im_width, 3)).astype(np.uint8)
This function takes an image, and returns a Numpy array representation of that image.
625941d56e29344779a6282c
def crawl(self): <NEW_LINE> <INDENT> self._start_time = datetime.datetime.now() <NEW_LINE> while True: <NEW_LINE> <INDENT> url = random.choice(self._config["root_urls"]) <NEW_LINE> try: <NEW_LINE> <INDENT> body = self._request(url).content <NEW_LINE> self._links = self._extract_urls(body, url) <NEW_LINE> logging.debug(...
Collects links from our root urls, stores them and then calls `_browse_from_links` to browse them
625941d59b70327d1c4e0ff0
def rename(self, **kwargs): <NEW_LINE> <INDENT> self.options.update(kwargs) <NEW_LINE> self.options['action'] = 'group.rename' <NEW_LINE> return self.call(self.options)
Rename an existing group keyword arguments: group_id -- ID of the group to rename name -- new name of the group
625941d5fbf16365ca6f63e0
def on_message(self, unused_channel, basic_deliver, properties, body): <NEW_LINE> <INDENT> LOGGER.info('Received message # %s from %s: %s', basic_deliver.delivery_tag, properties.app_id, body) <NEW_LINE> self.work_q.put(json.loads(body)) <NEW_LINE> self.acknowledge_message(basic_deliver.delivery_tag)
Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the message. The properties passed in is an instance of BasicProperties with the message properties...
625941d5046cf37aa974cf61
def get_output_params(self): <NEW_LINE> <INDENT> return self._output_params
Get all of the output parameters.
625941d566673b3332b922ac
def read_index_file(infile, f_header=[]): <NEW_LINE> <INDENT> if len(f_header) == 0: <NEW_LINE> <INDENT> f_header=['EXPERIMENT_ID','FILE_TYPE','SAMPLE_NAME','EXPERIMENT_TYPE','FILE','LIBRARY_STRATEGY'] <NEW_LINE> <DEDENT> infile=os.path.abspath(infile) <NEW_LINE> if os.path.exists(infile) == False: <NEW_LINE> <INDENT> ...
Read an index file and a list of fields (optional) Returns a list of dictionary
625941d5be383301e01b569e
def remove_comment(self, lines): <NEW_LINE> <INDENT> return [self.remove_comment_in_a_line(line) for line in lines]
Remove comment in lines Args: lines (list[str]): lines which may or may not include comments Returns: list[str]: lines from which removed comment
625941d529b78933be1e58c4
def p_expression_get(self, p): <NEW_LINE> <INDENT> p[0] = ('get', p[1], p[3])
expression : expression LBRACKET infix_chain RBRACKET
625941d51d351010ab855d36
def chunks(items, chunk_size): <NEW_LINE> <INDENT> for i in range(0, len(items), chunk_size): <NEW_LINE> <INDENT> yield items[i:i + chunk_size]
Yield successive n-sized chunks from l.
625941d5c432627299f04e62
def stopWaitingForJobs(self): <NEW_LINE> <INDENT> self.job_lock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> connections = self.active_connections[:] <NEW_LINE> now = time.time() <NEW_LINE> ok = True <NEW_LINE> for connection in connections: <NEW_LINE> <INDENT> if connection.state == "G...
Interrupts all running :py:meth:`getJob` calls, which will raise an exception.
625941d52eb69b55b151cacc