code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def singleshot(self, name, target=None, **kwargs): <NEW_LINE> <INDENT> if target is not None: <NEW_LINE> <INDENT> return self.__singleshot.run(name, target=target, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__singleshot[name] | Handles single shot events specific to this state
:param name:
:param target:
:param kwargs:
:return: | 625941c3090684286d50ec96 |
def change_path(self,path): <NEW_LINE> <INDENT> os.chdir(path) <NEW_LINE> log.info('now relocating to '+path) <NEW_LINE> log.info('done') <NEW_LINE> return | Change the current path.
Parameters
----------
Path: string
Path name
Return
------
None. | 625941c34a966d76dd550fc0 |
def _world_tick_planets(self): <NEW_LINE> <INDENT> for planet in self._planets: <NEW_LINE> <INDENT> mps = planet.res_per_hour.met / 3600 <NEW_LINE> cps = planet.res_per_hour.cry / 3600 <NEW_LINE> dps = planet.res_per_hour.deit / 3600 <NEW_LINE> planet.res_current.met += mps <NEW_LINE> planet.res_current.cry += cps <NEW_LINE> planet.res_current.deit += dps <NEW_LINE> num_completed = 0 <NEW_LINE> for bitem in planet.buildings_items: <NEW_LINE> <INDENT> if bitem.is_in_progress(): <NEW_LINE> <INDENT> bitem.seconds_left -= 1 <NEW_LINE> if bitem.seconds_left <= 0: <NEW_LINE> <INDENT> bitem.seconds_left = -1 <NEW_LINE> bitem.dt_end = None <NEW_LINE> bitem.level += 1 <NEW_LINE> num_completed += 1 <NEW_LINE> self.build_complete.emit(planet, bitem) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> todel_list = [] <NEW_LINE> for bitem in planet.shipyard_progress_items: <NEW_LINE> <INDENT> bitem.seconds_left -= 1 <NEW_LINE> if bitem.seconds_left <= 0: <NEW_LINE> <INDENT> todel_list.append(bitem) <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> if len(todel_list) > 0: <NEW_LINE> <INDENT> for bitem in todel_list: <NEW_LINE> <INDENT> planet.shipyard_progress_items.remove(bitem) <NEW_LINE> self.build_complete.emit(planet, bitem) <NEW_LINE> <DEDENT> <DEDENT> num_completed = 0 <NEW_LINE> for bitem in planet.research_items: <NEW_LINE> <INDENT> if bitem.is_in_progress(): <NEW_LINE> <INDENT> bitem.seconds_left -= 1 <NEW_LINE> if bitem.seconds_left <= 0: <NEW_LINE> <INDENT> bitem.seconds_left = -1 <NEW_LINE> bitem.dt_end = None <NEW_LINE> bitem.level += 1 <NEW_LINE> num_completed += 1 <NEW_LINE> self.build_complete.emit(planet, bitem) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> num_completed = 0 <NEW_LINE> for bitem in planet.researchfleet_items: <NEW_LINE> <INDENT> if bitem.is_in_progress(): <NEW_LINE> <INDENT> bitem.seconds_left -= 1 <NEW_LINE> if bitem.seconds_left <= 0: <NEW_LINE> <INDENT> bitem.seconds_left = -1 <NEW_LINE> bitem.dt_end = None <NEW_LINE> bitem.level += 1 <NEW_LINE> num_completed += 1 <NEW_LINE> self.build_complete.emit(planet, bitem) | This should do the following:
- increase planet resources every second
- move planet buildings progress
:return: None | 625941c329b78933be1e5661 |
def build_label(self, nombrecampo): <NEW_LINE> <INDENT> nombres = {'planta': 'Trabaja en planta', 'activo': 'Trabajador con alta en la empresa', 'categoriaLaboralID': 'Categoría laboral', 'centroTrabajoID': 'Centro de trabajo', 'dni': 'DNI', 'nomina': 'Sueldo base', 'apellidos': '<b>Apellidos</b>', 'nombre': '<b>Nombre</b>', } <NEW_LINE> try: <NEW_LINE> <INDENT> label = gtk.Label(nombres[nombrecampo]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> label = gtk.Label(utils.descamelcase_o_matic(nombrecampo)) <NEW_LINE> <DEDENT> label.set_use_markup(True) <NEW_LINE> label.set_property("xalign", 1) <NEW_LINE> return label | Construye la etiqueta correspondiente a "nombrecampo". | 625941c392d797404e30413c |
def clean_dates(self, task): <NEW_LINE> <INDENT> user_tz = self.env.user.tz or pytz.utc <NEW_LINE> if len(task['start_date']) > 16: <NEW_LINE> <INDENT> task['start_date'] = datetime.datetime.strptime( task['start_date'][:-8], "%Y-%m-%dT%H:%M").astimezone(pytz.timezone(user_tz)).strftime('%Y-%m-%d %H:%M') <NEW_LINE> <DEDENT> if len(task['end_date']) > 16: <NEW_LINE> <INDENT> task['end_date'] = datetime.datetime.strptime( task['end_date'][:-8], "%Y-%m-%dT%H:%M").strftime('%Y-%m-%d %H:%M') | pulisce le date di una task con il fuso orario e il formato giusto in modo che vengano accettate dall'ORM di odoo
:param task:
:return: | 625941c3d8ef3951e32434ef |
def import_csv_data(mode): <NEW_LINE> <INDENT> print("Starting import data...") <NEW_LINE> InitialImport.UploadCollData.coll_data_handler(mode, collCSV) <NEW_LINE> InitialImport.UploadPhenoData.pheno_data_handler(mode, phenoCSV) <NEW_LINE> print("Data has been imported into postgres DB") | import_csv_data imports csv files, formats them, and stores them in db
mode - 0 = print data, 1 = push data to SQL table | 625941c36fb2d068a760f04e |
@click.command() <NEW_LINE> @click.pass_context <NEW_LINE> @click.option( '--scenario-name', '-s', default=base.MOLECULE_DEFAULT_SCENARIO_NAME, help='Name of the scenario to target. ({})'.format( base.MOLECULE_DEFAULT_SCENARIO_NAME)) <NEW_LINE> def lint(ctx, scenario_name): <NEW_LINE> <INDENT> args = ctx.obj.get('args') <NEW_LINE> subcommand = base._get_subcommand(__name__) <NEW_LINE> command_args = { 'subcommand': subcommand, } <NEW_LINE> s = scenarios.Scenarios( base.get_configs(args, command_args), scenario_name) <NEW_LINE> s.print_matrix() <NEW_LINE> for scenario in s: <NEW_LINE> <INDENT> for action in scenario.sequence: <NEW_LINE> <INDENT> scenario.config.action = action <NEW_LINE> base.execute_subcommand(scenario.config, action) | Lint the role. | 625941c376e4537e8c351623 |
def setResults(self, results): <NEW_LINE> <INDENT> sum_kills = 0 <NEW_LINE> sum_lives = 0 <NEW_LINE> for result in results: <NEW_LINE> <INDENT> if "ship_id" not in result or "kills" not in result or "lives" not in result: <NEW_LINE> <INDENT> raise Exception("Missing values in ship_results dictionary") <NEW_LINE> <DEDENT> if result["lives"] > self.rounds or result["kills"] > (self.rounds*len(self.ships)): <NEW_LINE> <INDENT> raise Exception("Inconsistent results") <NEW_LINE> <DEDENT> sum_lives += result["lives"] <NEW_LINE> sum_kills += result["kills"] <NEW_LINE> ship = self.ships.through.objects.get(ship__id=result["ship_id"]) <NEW_LINE> if ship.confirmed: <NEW_LINE> <INDENT> if ship.kills != int(result["kills"]) or ship.lives != int(result["lives"]): <NEW_LINE> <INDENT> ship.confirmed = ship.confirmed - 1 <NEW_LINE> if ship.confirmed > 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ship.confirmed = ship.confirmed + 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> ship.kills = int(result["kills"]) <NEW_LINE> ship.lives = int(result["lives"]) <NEW_LINE> ship.confirmed = ship.confirmed + 1 <NEW_LINE> <DEDENT> if (sum_kills + sum_lives) != self.rounds*len(self.ships): <NEW_LINE> <INDENT> raise Exception("Inconsistent results!") <NEW_LINE> <DEDENT> self.save() <NEW_LINE> return True | Set result of battle. Check the consistency of input data. Confirm the correct results
@param results: array of {ship_id:x, kills:x, lives:x} dictionaries | 625941c3c432627299f04bf7 |
def _build_datasets(self): <NEW_LINE> <INDENT> self.datasets = data_partitioner.load_dataset(Constants.config['root_dir'], Constants.config['dataset']) <NEW_LINE> self.data_interface = DataInterface(self.datasets) | Retrieve the train/test datasets | 625941c32eb69b55b151c860 |
def readPointsFile(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fd = open(filename, 'r') <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> msg = "Can't find points file '%s'" % filename <NEW_LINE> raise RuntimeError(msg) <NEW_LINE> <DEDENT> layer_data = [] <NEW_LINE> for (lnum, line) in enumerate(fd.readlines()): <NEW_LINE> <INDENT> data = line.split() <NEW_LINE> if len(data[0]) < 2: <NEW_LINE> <INDENT> msg = 'File %s needs at least two fields on line %d' % lnum <NEW_LINE> raise RuntimeError(msg) <NEW_LINE> <DEDENT> new_line = [float(data[0]), float(data[1])] <NEW_LINE> new_line.extend(data[2:]) <NEW_LINE> layer_data.append(new_line) <NEW_LINE> <DEDENT> fd.close() <NEW_LINE> return layer_data | Read a file of points data into memory.
filename path to the points data
Returns a list of [lon, lat, ...].
Any fields after lon & lat are split on space and added to data list. | 625941c3379a373c97cfaaf6 |
def __init__(self, jobs=None): <NEW_LINE> <INDENT> self._jobs = None <NEW_LINE> self.discriminator = None <NEW_LINE> if jobs is not None: <NEW_LINE> <INDENT> self.jobs = jobs | JobPartsDto - a model defined in Swagger | 625941c3e64d504609d747f2 |
def _cleanup_links_qemu(self): <NEW_LINE> <INDENT> qemu_path = os.path.join(self.test_builddir, self.QEMU_BIN) <NEW_LINE> qemu_img_path = os.path.join(self.test_builddir, self.QEMU_IMG_BIN) <NEW_LINE> qemu_io_path = os.path.join(self.test_builddir, self.QEMU_IO_BIN) <NEW_LINE> qemu_fs_proxy_path = os.path.join(self.test_builddir, self.QEMU_FS_PROXY_BIN) <NEW_LINE> for path in (qemu_path, qemu_img_path, qemu_io_path, qemu_fs_proxy_path): <NEW_LINE> <INDENT> if os.path.lexists(path): <NEW_LINE> <INDENT> os.unlink(path) | Removes previously created links, if they exist
:return: None | 625941c3956e5f7376d70e21 |
def on_message(self, message): <NEW_LINE> <INDENT> pass | Called when a message has been decoded from the SockJS session.
The message is what was sent from the SockJS client, this could be a
simple string or a dict etc. It is up to subclasses to handle
validation of the message. | 625941c355399d3f05588666 |
def digits_to_words(input_string): <NEW_LINE> <INDENT> digit_string = "" <NEW_LINE> number = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] <NEW_LINE> for i in input_string: <NEW_LINE> <INDENT> if i.isdigit(): <NEW_LINE> <INDENT> if digit_string != "": <NEW_LINE> <INDENT> digit_string += ' ' <NEW_LINE> <DEDENT> digit_string += number[int(i)] <NEW_LINE> <DEDENT> <DEDENT> return digit_string | 인풋으로 받는 스트링에서 숫자만 추출하여 영어 단어로 변환하여 단어들이 연결된 스트링을 반환함
아래의 요건들을 충족시켜야함
* 반환하는 단어들은 영어 소문자여야함
* 단어들 사이에는 띄어쓰기 한칸이 있음
* 만약 인풋 스트링에서 숫자가 존재하지 않는 다면, 빈 문자열 (empty string)을 반환함
Parameters:
input_string (string): 영어로 된 대문자, 소문자, 띄어쓰기, 문장부호, 숫자로 이루어진 string
ex - "Zip Code: 19104"
Returns:
digit_string (string): 위 요건을 충족시킨 숫자만 영어단어로 추출된 string
ex - 'one nine one zero four'
Examples:
>>> import text_processing2 as tp2
>>> digits_str1 = "Zip Code: 19104"
>>> tp2.digits_to_words(digits_str1)
'one nine one zero four'
>>> digits_str2 = "Pi is 3.1415..."
>>> tp2.digits_to_words(digits_str2)
'three one four one five' | 625941c3498bea3a759b9a62 |
def _decide_row_lfs(self, row, column): <NEW_LINE> <INDENT> lfs_oid = _lfs_oid(row, column) <NEW_LINE> if lfs_oid is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> _set_decided_lfs(row, column) <NEW_LINE> if column == self._gdest_column: <NEW_LINE> <INDENT> row.p4_request = common.P4_REQUEST_LFS_COPY <NEW_LINE> row.p4filetype = self._decide_one_p4filetype(row, prev_p4filetype = row.cell(column.index).type()) <NEW_LINE> <DEDENT> return True | If this file is tracked by LFS, then record a decision
to 'p4 copy' it from LFS de-dupe storage.
Sets p4_request and p4filetype, through the RowWrapper.
Return True if decided to copy LFS, False if not. | 625941c34a966d76dd550fc1 |
def test_item_model_represents_object_by_name(self): <NEW_LINE> <INDENT> self.assertIn("Enjoy", str(Item.query.all())) | Test the __repr__ of the Item model. | 625941c376e4537e8c351624 |
def register_function(self): <NEW_LINE> <INDENT> self.show_message( main_handler.insert(self.sales_text.toPlainText(), self.purchases_text.toPlainText())) | Show the result of the insertion to the user. | 625941c3cb5e8a47e48b7a5f |
def wrapped(cls): <NEW_LINE> <INDENT> for name, path in suite_paths: <NEW_LINE> <INDENT> def test_suite(self): <NEW_LINE> <INDENT> return SelexeRunner(path, **self.options).run() <NEW_LINE> <DEDENT> test_suite.__name__ = 'test_%s' % ''.join(i if i in ALPHADIGIT else '_' for i in name) <NEW_LINE> test_suite.__doc__ = 'Selenium testsuite for %s' % name <NEW_LINE> setattr(cls, test_suite.__name__, test_suite) <NEW_LINE> <DEDENT> return cls | Inner wrapper for 'include_selexe_tests' decorator. This function must be called with the class-to-decorate as
its only argument.
This function uses arguments given to 'include_selexe_tests' for adding 'test_'-prefixed methods to
class.
@param cls: class to decorate
@return given class | 625941c3a219f33f3462891f |
def close_all(self, closer_method='close'): <NEW_LINE> <INDENT> for conn in self._connections: <NEW_LINE> <INDENT> getattr(conn, closer_method)() <NEW_LINE> <DEDENT> self.empty_cache() <NEW_LINE> return self.current | Closes connections using given closer method and empties cache.
If simply calling the closer method is not adequate for closing
connections, clients should close connections themselves and use
:meth:`empty_cache` afterwards. | 625941c3236d856c2ad4478b |
def __draw_snap_indicator(self, cr): <NEW_LINE> <INDENT> offset = self.get_hadjustment().get_value() <NEW_LINE> x = self.nsToPixel(self.snap_position) - offset <NEW_LINE> if x <= 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__draw_vertical_bar(cr, x, SNAPBAR_WIDTH, SNAPBAR_COLOR) | Draws a snapping indicator line. | 625941c316aa5153ce36242b |
def push_file(filename, parent=None): <NEW_LINE> <INDENT> if(os.path.isdir(filename)): <NEW_LINE> <INDENT> print("%s is a directory, use: push -r %s to upload recursively" % (filename, filename)) <NEW_LINE> return; <NEW_LINE> <DEDENT> if(not os.path.isfile(filename)): <NEW_LINE> <INDENT> print("Can not find %s, no such file" % filename) <NEW_LINE> return; <NEW_LINE> <DEDENT> mimetype = magic.from_file(filename, mime=True) <NEW_LINE> media = None <NEW_LINE> name = os.path.basename(filename) <NEW_LINE> service = get_service(); <NEW_LINE> body = { 'name': name, 'parents': [parent] if(parent) else None } <NEW_LINE> if(not mimetype == 'inode/x-empty'): <NEW_LINE> <INDENT> media = MediaFileUpload(filename, mimetype = mimetype, resumable=True) <NEW_LINE> request = service.files().create(body=body, media_body=media) <NEW_LINE> response = None <NEW_LINE> while response is None: <NEW_LINE> <INDENT> uplodadtry = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> status, response = request.next_chunk() <NEW_LINE> <DEDENT> except errors.HttpError as e: <NEW_LINE> <INDENT> if(e.resp.status in [404]): <NEW_LINE> <INDENT> print("An error ocurred, restarting upload") <NEW_LINE> push_file(filename) <NEW_LINE> <DEDENT> elif(e.resp.status in [500, 502, 503, 504] and uploadtry < 6): <NEW_LINE> <INDENT> uploadtry += 1 <NEW_LINE> exponetialBackoff(uploadtry) <NEW_LINE> continue; <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Error: %s not downloaded" % filename, e) <NEW_LINE> return; <NEW_LINE> <DEDENT> <DEDENT> if status: <NEW_LINE> <INDENT> progress = int(status.progress() * 100) <NEW_LINE> sys.stdout.write("\rUploading %s: %d%%" % (filename, progress)) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request = service.files().create(body=body).execute() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("File not uploaded: %s" % filename) <NEW_LINE> return; <NEW_LINE> <DEDENT> <DEDENT> sys.stdout.write("\n %s uploaded\n" % filename) | Uploads a file to google drive | 625941c3d6c5a10208143ffc |
def test_register_delete_view(self): <NEW_LINE> <INDENT> self.login("awilliam") <NEW_LINE> user = get_user_model().objects.get(username="awilliam") <NEW_LINE> phone = PhoneRegistration.objects.create(user=user, manufacturer="other", imei="351756051523999", description="A phone") <NEW_LINE> calc = CalculatorRegistration.objects.create(user=user, calc_type="ti84p", calc_serial="9999999", calc_id="999999") <NEW_LINE> comp = ComputerRegistration.objects.create(user=user, manufacturer="other", model="test", serial="999999999", screen_size=14) <NEW_LINE> registration_types = {CalculatorRegistration: "calculator", PhoneRegistration: "phone", ComputerRegistration: "computer"} <NEW_LINE> for item in [phone, calc, comp]: <NEW_LINE> <INDENT> self.client.post( reverse("itemreg_delete", kwargs={"item_type": registration_types[type(item)], "item_id": item.id}), data={"confirm": "confirm"} ) <NEW_LINE> self.assertEqual(0, type(item).objects.filter(id=item.id).count()) | Test register_delete_view, the view to delete a registered item. | 625941c31f5feb6acb0c4b06 |
def validate(self, standalone): <NEW_LINE> <INDENT> return True | Perform validation | 625941c34c3428357757c2dd |
def describe_restaurant(self): <NEW_LINE> <INDENT> print(f"{self.restaurant_name} is a new restaurant opening on Main Street!") <NEW_LINE> print(f"The restaurant specializes in {self.cuisine_type}.") | Description of the restaurant | 625941c3435de62698dfdbff |
def get_relations_attributes(self): <NEW_LINE> <INDENT> cursor = self.conn.cursor() <NEW_LINE> q = ( "SELECT c.table_name, c.column_name FROM information_schema.columns c " "INNER JOIN information_schema.tables t ON c.table_name = t.table_name " "AND c.table_schema = t.table_schema " "AND t.table_type = 'BASE TABLE' " "AND t.table_schema = 'public' " "AND c.table_name != 'queries'" ) <NEW_LINE> cursor.execute(q) <NEW_LINE> rows = cursor.fetchall() <NEW_LINE> cursor.close() <NEW_LINE> tables_attributes = {} <NEW_LINE> for table, attribute in rows: <NEW_LINE> <INDENT> if table in tables_attributes: <NEW_LINE> <INDENT> tables_attributes[table].append(attribute) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tables_attributes[table] = [attribute] <NEW_LINE> <DEDENT> <DEDENT> tables = list(tables_attributes.keys()) <NEW_LINE> relations_attributes = {} <NEW_LINE> relations = [] <NEW_LINE> relations_tables = {} <NEW_LINE> x = self.get_queries_incremental(target="") <NEW_LINE> for group in x: <NEW_LINE> <INDENT> for q in group: <NEW_LINE> <INDENT> for r in q["moz"]["from"]: <NEW_LINE> <INDENT> if r["name"] not in relations: <NEW_LINE> <INDENT> relations.append(r["name"]) <NEW_LINE> relations_attributes[r["name"]] = tables_attributes[r["value"]] <NEW_LINE> relations_tables[r["name"]] = r["value"] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return tables, relations, relations_attributes, relations_tables | Returns relations and their attributes
Uses tables/attributes from the database but also aliases found on the dataset's queries
Args:
None
Returns:
relations: list ['alias1','alias2',..]
relations_attributes: dict {'alias1':['attr1','attr2',..], .. } | 625941c350812a4eaa59c2d6 |
def __init__(self, k=None, W=None, alpha=100, init='random', n_inits=1, tol=1e-3, max_iter=1000, n_jobs=1, parallel_backend='multiprocessing'): <NEW_LINE> <INDENT> self.k = k <NEW_LINE> self.W = W <NEW_LINE> if W is not None: <NEW_LINE> <INDENT> self.D = sparse.coo_matrix(np.diagflat(W.sum(axis=1))) <NEW_LINE> self.L = self.D - self.W <NEW_LINE> <DEDENT> self.alpha = alpha <NEW_LINE> self.init = init <NEW_LINE> self.n_inits = n_inits <NEW_LINE> self.tol = tol <NEW_LINE> self.max_iter = max_iter <NEW_LINE> self.n_jobs = n_jobs <NEW_LINE> self.parallel_backend = parallel_backend | k: number of components
W: Adjacency matrix of the nearest neighboor matrix
alpha: regularization parameter
init: 'random' initializes to a random W,H
n_inits: number of runs to make with different random inits (in order to avoid being stuck in local minima)
n_jobs: number of parallel jobs to run, when n_inits > 1
tol: stopping criteria
max_iter: stopping criteria | 625941c34e696a04525c93ff |
def message_subscribe(self, partner_ids=None, channel_ids=None, subtype_ids=None): <NEW_LINE> <INDENT> res = super(Outsourcing, self).message_subscribe(partner_ids=partner_ids, channel_ids=channel_ids, subtype_ids=subtype_ids) <NEW_LINE> outsourcing_subtypes = self.env['mail.message.subtype'].browse(subtype_ids) if subtype_ids else None <NEW_LINE> task_subtypes = (outsourcing_subtypes.mapped('parent_id') | outsourcing_subtypes.filtered(lambda sub: sub.internal or sub.default)).ids if outsourcing_subtypes else None <NEW_LINE> if not subtype_ids or task_subtypes: <NEW_LINE> <INDENT> self.mapped('tasks').message_subscribe( partner_ids=partner_ids, channel_ids=channel_ids, subtype_ids=task_subtypes) <NEW_LINE> <DEDENT> return res | Subscribe to all existing active tasks when subscribing to a outsourcing | 625941c376d4e153a657eae3 |
def test_manager_cache_relationships_only_sub(self): <NEW_LINE> <INDENT> team = Team.objects.create() <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> Account.objects.create(team=team) <NEW_LINE> <DEDENT> with self.assertNumQueries(3): <NEW_LINE> <INDENT> entities = Entity.objects.cache_relationships(cache_super=False) <NEW_LINE> for entity in entities: <NEW_LINE> <INDENT> self.assertTrue(len(list(entity.get_sub_entities())) >= 0) <NEW_LINE> <DEDENT> <DEDENT> self.assertEquals(entities.count(), 6) | Tests a retrieval of cache relationships on the manager and verifies it results in the smallest amount of
queries when only caching sub entities. | 625941c366656f66f7cbc15d |
def get_symmetrized_structure(self): <NEW_LINE> <INDENT> ds = self.get_symmetry_dataset() <NEW_LINE> sg = SpacegroupOperations(self.get_space_group_symbol(), self.get_space_group_number(), self.get_symmetry_operations()) <NEW_LINE> return SymmetrizedStructure(self._structure, sg, ds["equivalent_atoms"]) | Get a symmetrized structure. A symmetrized structure is one where the
sites have been grouped into symmetrically equivalent groups.
Returns:
:class:`pymatgen.symmetry.structure.SymmetrizedStructure` object. | 625941c3851cf427c661a4c4 |
def update_dir_names(all_lowercase): <NEW_LINE> <INDENT> if os.path.exists("../pluginApp"): <NEW_LINE> <INDENT> os.rename("../pluginApp", "../"+all_lowercase+"App") | Updates the name of the main plugin directory | 625941c33c8af77a43ae3751 |
def _bfs(objs, get_referrers, ignore=None, action=None, getid=id): <NEW_LINE> <INDENT> import types <NEW_LINE> visited = set() <NEW_LINE> referrers = list(objs) <NEW_LINE> extraids = set() <NEW_LINE> extraids.add(getid(objs)) <NEW_LINE> while True: <NEW_LINE> <INDENT> front = [] <NEW_LINE> for ref in referrers: <NEW_LINE> <INDENT> refid = getid(ref) <NEW_LINE> if refid in visited: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if action: action(ref) <NEW_LINE> visited.add(refid) <NEW_LINE> front.append(ref) <NEW_LINE> <DEDENT> <DEDENT> if len(front) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> extraids.add(getid(referrers)) <NEW_LINE> extraids.add(getid(front)) <NEW_LINE> newreferrers = get_referrers(*front) <NEW_LINE> extraids.add(getid(newreferrers)) <NEW_LINE> referrers = _ignore_filter(newreferrers, ignore=ignore, extraids=extraids) <NEW_LINE> <DEDENT> return visited - extraids | A breadth first search traverse of the graph.
| 625941c3d4950a0f3b08c304 |
def get_rgb(self, index): <NEW_LINE> <INDENT> index = int(index) <NEW_LINE> return tuple(self.arr[index]) | Return a tuple of (R, G, B) values in the 0-maxc range associated
mapped by the value of `index`. | 625941c3ff9c53063f47c1a7 |
def tearDown(self): <NEW_LINE> <INDENT> self.report_timeout() <NEW_LINE> self._teardown_errors = self.pre_tear_down() <NEW_LINE> self._teardown_errors.extend(self.stop_job_managers()) <NEW_LINE> self._teardown_errors.extend(self.destroy_containers(self.container)) <NEW_LINE> self._teardown_errors.extend(self.destroy_pools(self.pool)) <NEW_LINE> self._teardown_errors.extend(self.stop_agents()) <NEW_LINE> self._teardown_errors.extend(self.stop_servers()) <NEW_LINE> super().tearDown() | Tear down after each test case. | 625941c371ff763f4b54963b |
def list_cortana_endpoints( self, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = self.list_cortana_endpoints.metadata['url'] <NEW_LINE> path_format_arguments = { 'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True) } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = 'application/json' <NEW_LINE> if custom_headers: <NEW_LINE> <INDENT> header_parameters.update(custom_headers) <NEW_LINE> <DEDENT> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> response = self._client.send(request, stream=False, **operation_config) <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> raise models.ErrorResponseException(self._deserialize, response) <NEW_LINE> <DEDENT> deserialized = None <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> deserialized = self._deserialize('PersonalAssistantsResponse', response) <NEW_LINE> <DEDENT> if raw: <NEW_LINE> <INDENT> client_raw_response = ClientRawResponse(deserialized, response) <NEW_LINE> return client_raw_response <NEW_LINE> <DEDENT> return deserialized | Gets the endpoint URLs for the prebuilt Cortana applications.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PersonalAssistantsResponse or ClientRawResponse if raw=true
:rtype:
~azure.cognitiveservices.language.luis.authoring.models.PersonalAssistantsResponse
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<azure.cognitiveservices.language.luis.authoring.models.ErrorResponseException>` | 625941c3d58c6744b4257c13 |
def getOptimizer(opt: str): <NEW_LINE> <INDENT> import os <NEW_LINE> from keras import optimizers as k_opt <NEW_LINE> if not os.path.isfile(default_opt_cfg): <NEW_LINE> <INDENT> writeDefaultConfig() <NEW_LINE> <DEDENT> opt_cfg = configparser.ConfigParser() <NEW_LINE> opt_cfg.read(default_opt_cfg) <NEW_LINE> if opt == 'sgd': <NEW_LINE> <INDENT> return k_opt.SGD(lr=parseParam(opt, 'lr', opt_cfg), momentum=parseParam(opt, 'momentum', opt_cfg), decay=parseParam(opt, 'decay', opt_cfg), nesterov=parseParam(opt, 'nesterov', opt_cfg)) <NEW_LINE> <DEDENT> if opt == 'rmsprop': <NEW_LINE> <INDENT> return k_opt.RMSprop(lr=parseParam(opt, 'lr', opt_cfg), rho=parseParam(opt, 'rho', opt_cfg), epsilon=parseParam(opt, 'epsilon', opt_cfg), decay=parseParam(opt, 'decay', opt_cfg)) <NEW_LINE> <DEDENT> if opt == 'adagrad': <NEW_LINE> <INDENT> return k_opt.Adagrad(lr=parseParam(opt, 'lr', opt_cfg), epsilon=parseParam(opt, 'epsilon', opt_cfg), decay=parseParam(opt, 'decay', opt_cfg)) <NEW_LINE> <DEDENT> if opt == 'adadelta': <NEW_LINE> <INDENT> return k_opt.Adadelta(lr=parseParam(opt, 'lr', opt_cfg), rho=parseParam(opt, 'rho', opt_cfg), epsilon=parseParam(opt, 'epsilon', opt_cfg), decay=parseParam(opt, 'decay', opt_cfg)) <NEW_LINE> <DEDENT> if opt == 'adam': <NEW_LINE> <INDENT> return k_opt.Adam(lr=parseParam(opt, 'lr', opt_cfg), beta_1=parseParam(opt, 'beta_1', opt_cfg), beta_2=parseParam(opt, 'beta_2', opt_cfg), epsilon=parseParam(opt, 'epsilon', opt_cfg), decay=parseParam(opt, 'decay', opt_cfg), amsgrad=parseParam(opt, 'amsgrad', opt_cfg)) <NEW_LINE> <DEDENT> if opt == 'adamax': <NEW_LINE> <INDENT> return k_opt.Adamax(lr=parseParam(opt, 'lr', opt_cfg), beta_1=parseParam(opt, 'beta_1', opt_cfg), beta_2=parseParam(opt, 'beta_2', opt_cfg), epsilon=parseParam(opt, 'epsilon', opt_cfg), decay=parseParam(opt, 'decay', opt_cfg)) <NEW_LINE> <DEDENT> if opt == 'nadam': <NEW_LINE> <INDENT> return k_opt.Nadam(lr=parseParam(opt, 'lr', opt_cfg), beta_1=parseParam(opt, 'beta_1', opt_cfg), beta_2=parseParam(opt, 'beta_2', opt_cfg), epsilon=parseParam(opt, 'epsilon', opt_cfg), schedule_decay=parseParam(opt, 'schedule_decay', opt_cfg)) <NEW_LINE> <DEDENT> raise ValueError('Unrecognized optimizer ({})'.format(opt)) | Returns a Keras optimizer object | 625941c3498bea3a759b9a63 |
def vect_from_qarray(q): <NEW_LINE> <INDENT> v = scipy.array(q[:,1:]) <NEW_LINE> return v | Return vector array from quaternion array | 625941c33c8af77a43ae3752 |
def Meld(*args): <NEW_LINE> <INDENT> return _MEDCouplingCorba.DataArrayInt_Meld(*args) | Meld(DataArrayInt a1, DataArrayInt a2) -> DataArrayInt
Meld(std::vector<(p.q(const).ParaMEDMEM::DataArrayInt,std::allocator<(p.q(const).ParaMEDMEM::DataArrayInt)>)> arr) -> DataArrayInt
Meld(PyObject li) -> DataArrayInt
1 | 625941c396565a6dacc8f67f |
def get_reset_channel(self): <NEW_LINE> <INDENT> return self._reset_send.clone() | Get a channel that can send resets to the rate limiter.
:rtype: trio.ReceiveChannel | 625941c3009cb60464c63366 |
def test_get_dataset_files(self): <NEW_LINE> <INDENT> pass | Test case for get_dataset_files
Get Dataset Files # noqa: E501 | 625941c345492302aab5e275 |
def write_index(self, outdir, froot="index", relative_to=None, rst_extension=".rst"): <NEW_LINE> <INDENT> if self.written_usecases is None: <NEW_LINE> <INDENT> raise ValueError('No modules written') <NEW_LINE> <DEDENT> path = os.path.join(outdir, froot + rst_extension) <NEW_LINE> if relative_to is not None: <NEW_LINE> <INDENT> relpath = outdir.replace(relative_to + os.path.sep, "") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> relpath = outdir <NEW_LINE> <DEDENT> idx = open(path, "wt") <NEW_LINE> w = idx.write <NEW_LINE> w(".. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n") <NEW_LINE> w(".. raw:: html\n\n") <NEW_LINE> table = ["<!-- Block section -->"] <NEW_LINE> table.append("<table border='1' class='docutils' style='width:100%'>") <NEW_LINE> table.append("<colgroup><col width='25%'/><col width='75%'/>" "</colgroup>") <NEW_LINE> table.append("<tbody valign='top'>") <NEW_LINE> for title_str, f in self.written_usecases: <NEW_LINE> <INDENT> relative_uid = ".".join(f.split(".")[2:]) <NEW_LINE> ref = os.path.join(relpath, f + ".html") <NEW_LINE> table.append("<tr class='row-odd'>") <NEW_LINE> table.append( "<td><a class='reference internal' href='{0}'>" "<em>{1}</em></a></td>\n".format(ref, relative_uid)) <NEW_LINE> table.append("<td>{0}</td>".format(title_str)) <NEW_LINE> table.append("</tr>") <NEW_LINE> <DEDENT> table.append("</tbody>\n\n") <NEW_LINE> table.append("</table>") <NEW_LINE> table_with_indent = [" " * 4 + line for line in table] <NEW_LINE> w("\n".join(table_with_indent)) <NEW_LINE> idx.close() | Make a reST API index file from written files
Parameters
----------
outdir : string (mandatory)
Directory to which to write generated index file
froot : string (optional)
root (filename without extension) of filename to write to
Defaults to 'index'. We add ``rst_extension``.
relative_to : string
path to which written filenames are relative. This
component of the written file path will be removed from
outdir, in the generated index. Default is None, meaning,
leave path as it is.
rst_extension : string (optional)
Extension for reST files, default '.rst' | 625941c329b78933be1e5662 |
def ensure_iso_8859_15_only(commit): <NEW_LINE> <INDENT> if git_config("hooks.no-rh-character-range-check"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for lineno, line in enumerate(commit.raw_revlog_lines, start=1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> line.encode("ISO-8859-15") <NEW_LINE> <DEDENT> except UnicodeEncodeError as e: <NEW_LINE> <INDENT> raise InvalidUpdate( "Invalid revision history for commit %s:" % commit.rev, "It contains characters not in the ISO-8859-15 charset.", "", "Below is the first line where this was detected" " (line %d):" % lineno, "| " + line, " " + " " * e.start + "^", " " + " " * e.start + "|", "", "Please amend the commit's revision history to remove it", "and try again.", ) | Raise InvalidUpdate if the revision log contains non-ISO-8859-15 chars.
The purpose of this check is make sure there are no unintended
characters that snuck in, particularly non-printable characters
accidently copy/pasted (this has been seen on MacOS X for instance,
where the <U+2069> character was copy/pasted without the user
even realizing it). This, in turn, can have serious unintended
consequences, for instance when checking for ticket numbers, because
tickets numbers need to be on a word boundary, and such invisible
character prevents that.
PARAMETERS
commit: A CommitInfo object corresponding to the commit being checked. | 625941c3090684286d50ec97 |
def stop(self): <NEW_LINE> <INDENT> if self._play_thread is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self._play_thread.is_alive(): <NEW_LINE> <INDENT> self._play_thread = None <NEW_LINE> return <NEW_LINE> <DEDENT> global event_queue <NEW_LINE> event_queue.put({'key':EVENT_STOP}) <NEW_LINE> while self._play_thread.is_alive(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> from machinery.core.core import turn_off_speakers <NEW_LINE> turn_off_speakers() | Stops the current playback and cancels the playing thread. | 625941c3de87d2750b85fd44 |
def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): <NEW_LINE> <INDENT> if 'env' in kwargs: <NEW_LINE> <INDENT> salt.utils.warn_until( 'Oxygen', 'Parameter \'env\' has been detected in the argument list. This ' 'parameter is no longer used and has been replaced by \'saltenv\' ' 'as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.' ) <NEW_LINE> kwargs.pop('env') <NEW_LINE> <DEDENT> kwargs['saltenv'] = saltenv <NEW_LINE> url_data = urlparse(url) <NEW_LINE> sfn = self.cache_file(url, saltenv, cachedir=cachedir) <NEW_LINE> if not os.path.exists(sfn): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if template in salt.utils.templates.TEMPLATE_REGISTRY: <NEW_LINE> <INDENT> data = salt.utils.templates.TEMPLATE_REGISTRY[template]( sfn, **kwargs ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.error('Attempted to render template with unavailable engine ' '{0}'.format(template)) <NEW_LINE> return '' <NEW_LINE> <DEDENT> if not data['result']: <NEW_LINE> <INDENT> log.error( 'Failed to render template with error: {0}'.format( data['data'] ) ) <NEW_LINE> return '' <NEW_LINE> <DEDENT> if not dest: <NEW_LINE> <INDENT> dest = self._extrn_path(url, saltenv, cachedir=cachedir) <NEW_LINE> makedirs = True <NEW_LINE> <DEDENT> destdir = os.path.dirname(dest) <NEW_LINE> if not os.path.isdir(destdir): <NEW_LINE> <INDENT> if makedirs: <NEW_LINE> <INDENT> os.makedirs(destdir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> salt.utils.safe_rm(data['data']) <NEW_LINE> return '' <NEW_LINE> <DEDENT> <DEDENT> shutil.move(data['data'], dest) <NEW_LINE> return dest | Cache a file then process it as a template | 625941c3b57a9660fec33836 |
def watcher(fn): <NEW_LINE> <INDENT> @functools.wraps(fn) <NEW_LINE> def _watcher(*, config, num=None, **kwargs): <NEW_LINE> <INDENT> name = fn.__name__ <NEW_LINE> if num is not None: <NEW_LINE> <INDENT> name += "-" + str(num) <NEW_LINE> <DEDENT> with file_logger.FileLogger(config.path, name, config.quiet) as logger: <NEW_LINE> <INDENT> print("{} started".format(name)) <NEW_LINE> logger.print("{} started".format(name)) <NEW_LINE> try: <NEW_LINE> <INDENT> return fn(config=config, logger=logger, **kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.print("\n".join([ "", " Exception caught ".center(60, "="), traceback.format_exc(), "=" * 60, ])) <NEW_LINE> print("Exception caught in {}: {}".format(name, e)) <NEW_LINE> raise <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> logger.print("{} exiting".format(name)) <NEW_LINE> print("{} exiting".format(name)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return _watcher | A decorator to fn/processes that gives a logger and logs exceptions. | 625941c3925a0f43d2549e29 |
def run(args: argparse.Namespace) -> None: <NEW_LINE> <INDENT> lister = MergeRequestList(args.project, args.merged, args.opened, args.closed, args.url) <NEW_LINE> lister.print_formatted_list() | run merge request list command
:param args: parsed arguments | 625941c33cc13d1c6d3c732e |
def testNumber(self): <NEW_LINE> <INDENT> num = ee.Number(1) <NEW_LINE> self.assertEqual(1, num.encode()) <NEW_LINE> computed = ee.Number(1).add(2) <NEW_LINE> self.assertIsInstance(computed, ee.Number) <NEW_LINE> self.assertEqual(ee.ApiFunction.lookup('Number.add'), computed.func) <NEW_LINE> self.assertEqual({ 'left': ee.Number(1), 'right': ee.Number(2) }, computed.args) | Verifies basic behavior of ee.Number. | 625941c38e05c05ec3eea326 |
def pad_identities_right(self, d, L): <NEW_LINE> <INDENT> npad = L - self.iend <NEW_LINE> self.oplist += [np.identity(d) for _ in range(npad)] <NEW_LINE> self.qD += npad*[0] | Pad identity matrices on the right. | 625941c3d58c6744b4257c14 |
def Process(self, save = True): <NEW_LINE> <INDENT> self.ReadData(); <NEW_LINE> self.Filter(); <NEW_LINE> self.Normalize(); <NEW_LINE> self.Transform(); <NEW_LINE> if save: <NEW_LINE> <INDENT> self.Save(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.info("Skipping save as it was passed to this method") | To automate the preprocessing procedure in one go!
returns:
None
class variable return:
method based
modification:
method based | 625941c3aad79263cf3909f2 |
def tabOpen(self, tab_name): <NEW_LINE> <INDENT> for other_tab_name in self._page_tabs.tabNames(): <NEW_LINE> <INDENT> if tab_name == other_tab_name: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Checks if the selected tab name already exists within the tabs. | 625941c371ff763f4b54963c |
def get_LogNegNum(CovM): <NEW_LINE> <INDENT> V = np.linalg.det(CovM) <NEW_LINE> A = np.linalg.det(CovM[:2, :2]) <NEW_LINE> B = np.linalg.det(CovM[2:, 2:]) <NEW_LINE> C = np.linalg.det(CovM[:2, 2:]) <NEW_LINE> sigma = A + B - 2.0 * C <NEW_LINE> if sigma*sigma-4.0*V < 0.0: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> vn = np.sqrt(sigma / 2.0 - np.sqrt(sigma * sigma - 4.0 * V) / 2.0) <NEW_LINE> if C == 0: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> return -np.log10(2.0 * vn) | function to calculate Log-Negativity from a covariance matrix
CovM looks a bit like:
I1 I1I1 I1Q1 I1I2 I1Q2
Q1 Q1I1 Q1Q1 Q1I2 Q1Q2
I2 I2I1 I2Q1 I2I2 I2Q2
Q2 Q2I1 Q2Q1 Q2I2 Q2Q2
I1 Q1 I2 Q2 | 625941c3a17c0f6771cbe006 |
def call(self, inputs, state): <NEW_LINE> <INDENT> sigmoid = math_ops.sigmoid <NEW_LINE> input_size = inputs.get_shape().with_rank(2).dims[1] <NEW_LINE> if input_size.value is None: <NEW_LINE> <INDENT> raise ValueError("Could not infer input size from inputs.get_shape()[-1]") <NEW_LINE> <DEDENT> with vs.variable_scope( vs.get_variable_scope(), initializer=self._initializer): <NEW_LINE> <INDENT> cell_inputs = array_ops.concat([inputs, state], 1) <NEW_LINE> if self._linear is None: <NEW_LINE> <INDENT> self._linear = _Linear(cell_inputs, 2 * self._num_units, True) <NEW_LINE> <DEDENT> rnn_matrix = self._linear(cell_inputs) <NEW_LINE> [g_act, c_act] = array_ops.split( axis=1, num_or_size_splits=2, value=rnn_matrix) <NEW_LINE> c = self._activation(c_act) <NEW_LINE> g = sigmoid(g_act + self._forget_bias) <NEW_LINE> new_state = g * state + (1.0 - g) * c <NEW_LINE> new_output = new_state <NEW_LINE> <DEDENT> return new_output, new_state | Run one step of UGRNN.
Args:
inputs: input Tensor, 2D, batch x input size.
state: state Tensor, 2D, batch x num units.
Returns:
new_output: batch x num units, Tensor representing the output of the UGRNN
after reading `inputs` when previous state was `state`. Identical to
`new_state`.
new_state: batch x num units, Tensor representing the state of the UGRNN
after reading `inputs` when previous state was `state`.
Raises:
ValueError: If input size cannot be inferred from inputs via
static shape inference. | 625941c3ac7a0e7691ed4083 |
def GetAllCompany(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | 获取所有公司
| 625941c366673b3332b92044 |
def Variables(self, x_in, y_in, z_in, theta, direction): <NEW_LINE> <INDENT> altitude = round(z_in/float(1000), 2) <NEW_LINE> font = pygame.font.SysFont("Arial", 15) <NEW_LINE> sprites = pygame.sprite.Group() <NEW_LINE> altitude_group = pygame.sprite.Group() <NEW_LINE> direction_sprite = pygame.sprite.Sprite() <NEW_LINE> theta_sprite = pygame.sprite.Sprite() <NEW_LINE> altitude_indicator = pygame.sprite.Sprite() <NEW_LINE> altitude_level = pygame.sprite.Sprite() <NEW_LINE> direction_sprite.image = pygame.image.load("images/indicator.png") <NEW_LINE> theta_sprite.image = pygame.image.load("images/indicator.png") <NEW_LINE> altitude_level.image = pygame.image.load("images/altitude.png") <NEW_LINE> altitude_indicator.image = pygame.image.load("images/altitude_indicator.png") <NEW_LINE> direction_sprite.rect = direction_sprite.image.get_rect(x=self.width-80, y=60) <NEW_LINE> theta_sprite.rect = theta_sprite.image.get_rect(x=self.width-80, y=0) <NEW_LINE> altitude_level.rect = altitude_indicator.image.get_rect(x=self.width-70, y=125) <NEW_LINE> altitude_indicator.rect = altitude_indicator.image.get_rect(x=self.width-67, y=175-(altitude)) <NEW_LINE> sprites.add(direction_sprite, theta_sprite, altitude_level) <NEW_LINE> altitude_group.add(altitude_indicator) <NEW_LINE> direction_sprite.image = pygame.transform.rotate(direction_sprite.image, direction) <NEW_LINE> theta_sprite.image = pygame.transform.rotate(theta_sprite.image, theta) <NEW_LINE> x = font.render("X "+str(int(x_in)) , True, (0,0,0)) <NEW_LINE> y = font.render("Y "+str(int(y_in)), True, (0,0,0)) <NEW_LINE> z = font.render("Z "+str(int(z_in)), True, (0,0,0)) <NEW_LINE> theta = font.render("Theta "+str(int(theta))+u"\u00b0", True, (0,0,0)) <NEW_LINE> direction = font.render("Yaw(F/ E) "+str(int(direction))+u"\u00b0", True, (0,0,0)) <NEW_LINE> altitude = font.render("Altitude "+str(altitude)+"km", True, (0,0,0)) <NEW_LINE> self.screen.blit(x, ((self.width/3)/2, self.height-20)) <NEW_LINE> self.screen.blit(y, (((self.width/3)*3)/2 ,self.height-20)) <NEW_LINE> self.screen.blit(z, (((self.width/3)*5)/2 ,self.height-20)) <NEW_LINE> self.screen.blit(theta, ((self.width-100), 40)) <NEW_LINE> self.screen.blit(direction, ((self.width-100), 100)) <NEW_LINE> self.screen.blit(altitude, ((self.width-100), 190)) <NEW_LINE> sprites.draw(self.screen) <NEW_LINE> altitude_group.draw(self.screen) | display the location of the object | 625941c3bde94217f3682da6 |
def get_cargo_by_sequence_number(self, sequence_number): <NEW_LINE> <INDENT> return self.cargoes[sequence_number] | :rtype: Cargo | 625941c3a4f1c619b28afff1 |
def test_ensemble(tmpdir, request, H0, H1, L1, L2, pop1, pop2): <NEW_LINE> <INDENT> filename = request.module.__file__ <NEW_LINE> test_dir, _ = os.path.splitext(filename) <NEW_LINE> psi = np.array([0, 1, 1, 0], dtype=np.complex128) / np.sqrt(2.0) <NEW_LINE> pulse = AnalyticalPulse.from_func( partial(blackman, t_start=0, t_stop=50), ampl_unit='unitless', time_unit='ns', ) <NEW_LINE> model = two_level_model(H0, H1, L1, L2, pop1, pop2, pulse, psi) <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> r1 = (np.random.rand() - 0.5) * 0.01 <NEW_LINE> r2 = (np.random.rand() - 0.5) * 0.01 <NEW_LINE> ens = "ens%d" % (i + 1) <NEW_LINE> H0_fn = "H0_%s.dat" % ens <NEW_LINE> H1_fn = "H1_%s.dat" % ens <NEW_LINE> model.add_ham(H0 + r1 * H0, label=ens, filename=H0_fn) <NEW_LINE> model.add_ham(H1 + r2 * H1, pulse, label=ens, filename=H1_fn) <NEW_LINE> <DEDENT> assert len(model.ham()) == 2 <NEW_LINE> assert len(model.ham(label='ens1')) == 2 <NEW_LINE> assert len(model.ham(label='*')) == 12 <NEW_LINE> assert len(model.pulses(label='ens1')) == 1 <NEW_LINE> assert len(model.pulses(label='*')) == 6 <NEW_LINE> model.write_to_runfolder( str(tmpdir.join('model_rf')), config='ensemble.config' ) <NEW_LINE> assert filecmp.cmp( os.path.join(test_dir, 'ensemble.config'), str(tmpdir.join('model_rf', 'ensemble.config')), shallow=False, ) | Test ensemble of multiple Hamiltonians | 625941c38e71fb1e9831d75e |
def get_welcome_message(self, user): <NEW_LINE> <INDENT> username = user.first_name if user.first_name else user.username <NEW_LINE> return mark_safe('<strong>Welcome back to %s, %s.</strong><br/>%s' % ( self.get_site_name(), username, ('Your last login was on %s (%s).' % ( filter_date(user.last_login), naturaltime(user.last_login) ) if user.last_login else '') )) | Return welcome message addressing the user who logged in. | 625941c3bde94217f3682da7 |
def test_post_watermark(self): <NEW_LINE> <INDENT> pass | Test case for post_watermark
Add custom watermark | 625941c391f36d47f21ac4a4 |
def share_data(self, override_previous=True, **parameters): <NEW_LINE> <INDENT> if not self.IS_COMPLEX: <NEW_LINE> <INDENT> self.parent._set_parameters(override_previous=override_previous, **parameters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._set_parameters(override_previous=override_previous, **parameters) | Inject the parameters to the parent and sibling components.
Args:
override_previous (bool): whether to override previous value of
the parameters if they were already injected or not. | 625941c344b2445a3393204b |
def test_count_data_test_1(self): <NEW_LINE> <INDENT> row_count = self.fetcher.count_data(text='test_1') <NEW_LINE> self.assertEqual(row_count, 10) | text=test_1 | 625941c33346ee7daa2b2d1f |
def finish_initializing(self, builder): <NEW_LINE> <INDENT> self.builder = builder <NEW_LINE> self.ui = builder.get_ui(self) | Called when we're finished initializing.
finish_initalizing should be called after parsing the ui definition
and creating a PreviewDialog object with it in order to
finish initializing the start of the new PreviewDialog
instance. | 625941c3fb3f5b602dac3645 |
def __init__(self, arch='r2plus1d_18', pretrained=True, progress=True, block=BasicBlock, conv_makers=[Conv2Plus1D] * 4, layers=[2, 2, 2, 2], stem=R2Plus1dStem, keyfeatures=512, zero_init_residual=False): <NEW_LINE> <INDENT> super(VideoResNetAttention3C, self).__init__() <NEW_LINE> self.inplanes = 64 <NEW_LINE> self.stem = stem() <NEW_LINE> self.layer1 = self._make_layer(block, conv_makers[0], 64, layers[0], stride=1) <NEW_LINE> self.attention_layer = Simple3dConv(1, 64) <NEW_LINE> self.layer2 = self._make_layer(block, conv_makers[1], 128, layers[1], stride=2) <NEW_LINE> self.layer3 = self._make_layer(block, conv_makers[2], 256, layers[2], stride=2) <NEW_LINE> self.layer4 = self._make_layer(block, conv_makers[3], 512, layers[3], stride=2) <NEW_LINE> self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1)) <NEW_LINE> self.fc_layer = nn.Linear(512 * block.expansion, keyfeatures) <NEW_LINE> self._initialize_weights() <NEW_LINE> if zero_init_residual: <NEW_LINE> <INDENT> for m in self.modules(): <NEW_LINE> <INDENT> if isinstance(m, Bottleneck): <NEW_LINE> <INDENT> nn.init.constant_(m.bn3.weight, 0) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if pretrained: <NEW_LINE> <INDENT> pretrained_dict = load_state_dict_from_url(model_urls[arch], progress=progress) <NEW_LINE> model_dict = self.state_dict() <NEW_LINE> pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} <NEW_LINE> model_dict.update(pretrained_dict) <NEW_LINE> self.load_state_dict(pretrained_dict, strict=False) | Generic resnet video generator.
Args:
block (nn.Module): resnet building block
conv_makers (list(functions)): generator function for each layer
layers (List[int]): number of blocks per layer
stem (nn.Module, optional): Resnet stem, if None, defaults to conv-bn-relu. Defaults to None.
num_classes (int, optional): Dimension of the final FC layer. Defaults to 400.
zero_init_residual (bool, optional): Zero init bottleneck residual BN. Defaults to False. | 625941c3293b9510aa2c324c |
def authenticate(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def authenticate_and_call(*args, **kwargs): <NEW_LINE> <INDENT> flag = False <NEW_LINE> can_auth = request.json and 'session_id' in request.json <NEW_LINE> if can_auth: <NEW_LINE> <INDENT> flag = authentication_check( request.json['session_id'])['status'] <NEW_LINE> <DEDENT> if not flag: <NEW_LINE> <INDENT> raise Unauthorized('You must be logged in to perform this action.') <NEW_LINE> <DEDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> return authenticate_and_call | AuthN decorator. Applying this decorator to a method will require any
request to successfully pass an authentication challenge or return an
error response.
:param func: Method to decorate
:type func: callable
:return: Wrapped method
:rtype: callable | 625941c331939e2706e4ce20 |
def populate_database(self): <NEW_LINE> <INDENT> self.dye_stocks.add_new_dye_stocks() <NEW_LINE> self.detections.add_new_detections() <NEW_LINE> self.profiles.add_new_profiles() | Adds the data to the database. Run this only after parsing
all database entries. That way errors will be detected before
database entry. | 625941c3fbf16365ca6f6174 |
def time_alive(self): <NEW_LINE> <INDENT> return time.time() - self._time | Retourne le temps depuis lequel le socket n'a pas ete utilise | 625941c385dfad0860c3ae0e |
def __init__(self, channels, colorspace): <NEW_LINE> <INDENT> colorspace = colorspace.lower() <NEW_LINE> if colorspace not in self.COLORSPACES: <NEW_LINE> <INDENT> raise ValueError('Colorspace must be one of %s.' % self.COLORSPACES) <NEW_LINE> <DEDENT> self.colorspace = colorspace <NEW_LINE> datatype = self.COLORSPACE_DATA_TYPES[colorspace] <NEW_LINE> self.channels = [datatype(c) for c in channels] <NEW_LINE> if self.channels != channels: <NEW_LINE> <INDENT> warnings.warn(ValueWarning("Loss of precision when converting to canonical datatype for colorspace %s." % colorspace)) | channels: a tuple
colorspace: hsv or rgb | 625941c323e79379d52ee51a |
def test_related_tree_manager(self): <NEW_LINE> <INDENT> self.assertIs(type(Page.objects.get_for_path('/').children.all()), UrlNodeQuerySet) <NEW_LINE> self.assertEqual(Page.objects.get_for_path('/').children.in_navigation()[0].slug, 'level1') | The tree manager should get the same abilities as the original manager.
This was broken in django-mptt 0.5.2 | 625941c3e76e3b2f99f3a7c3 |
def test_pairwise_align_sequences_with_gaps_in_first_sequence(self): <NEW_LINE> <INDENT> seq1 = "GSNAKFGLWVDGNCEDIPHVNEFPAID" <NEW_LINE> seq1_bio = Seq(seq1) <NEW_LINE> seq2 = "NAKFLWVDG" <NEW_LINE> seq2_bio = Seq(seq2) <NEW_LINE> test_map_reverse, test_map_forward = seqtools.pairwise_align(seq2, seq1) <NEW_LINE> forward_match = {3: 1, 4: 2, 5: 3, 6: 4, 8: 5, 9: 6, 10: 7, 11: 8, 12: 9} <NEW_LINE> reverse_match = {1: 3, 2: 4, 3: 5, 4: 6, 5: 8, 6: 9, 7: 10, 8: 11, 9: 12} <NEW_LINE> self.assertEqual(forward_match, test_map_forward) <NEW_LINE> self.assertEqual(reverse_match, test_map_reverse) <NEW_LINE> test_map_forward, test_map_reverse = seqtools.pairwise_align(seq1_bio, seq2_bio) <NEW_LINE> self.assertEqual(forward_match, test_map_forward) <NEW_LINE> self.assertEqual(reverse_match, test_map_reverse) | Test with reverse input (ie gaps in first sequence) | 625941c36aa9bd52df036d57 |
def _update_lp(self, dmu_code): <NEW_LINE> <INDENT> self._concrete_model.update_objective(self.input_data, dmu_code, self._input_variables, self._output_variables, self.lp_model) <NEW_LINE> self._concrete_model.update_equality_constraint(self.input_data, dmu_code, self._input_variables, self._output_variables, self.lp_model) | Updates existing linear program with coefficients corresponding
to a given DMU.
Args:
dmu_code (str): DMU code. | 625941c373bcbd0ca4b2c02a |
def mouseReleaseEvent(self, event): <NEW_LINE> <INDENT> super(TabBarDe, self).mouseReleaseEvent(event) <NEW_LINE> self.mPos = None <NEW_LINE> event.accept() | 鼠标弹起事件 | 625941c3ec188e330fd5a757 |
def part2(entries: list) -> int: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for group in entries: <NEW_LINE> <INDENT> for key in group[1].keys(): <NEW_LINE> <INDENT> if group[1][key] == group[0]: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return count | part2 solver take a list of sets and return an int | 625941c321bff66bcd684909 |
def put(self, key, value): <NEW_LINE> <INDENT> if key in self.setkeys: <NEW_LINE> <INDENT> for i in range(len(self.keys)): <NEW_LINE> <INDENT> if self.keys[i] == key: <NEW_LINE> <INDENT> self.values[i] = value <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.keys.append(key) <NEW_LINE> self.values.append(value) <NEW_LINE> self.setkeys.add(key) | value will always be non-negative.
:type key: int
:type value: int
:rtype: void | 625941c3187af65679ca50d2 |
def isoweekday(): <NEW_LINE> <INDENT> pass | Return the day of the week as an integer.
Monday is 1 and Sunday is 7. The same as self.date().isoweekday.
.. seealso:: `weekday`, `isocalendar`. | 625941c3a4f1c619b28afff2 |
def store_tracer(self): <NEW_LINE> <INDENT> match_dict = self.get_all_matches() <NEW_LINE> with h5py.File(self.storage_file, 'w') as f: <NEW_LINE> <INDENT> for snap_id, matches in match_dict.items(): <NEW_LINE> <INDENT> h5_group = '/Heritage/{}/{}'.format(self.branching, str(snap_id)) <NEW_LINE> f.create_group(h5_group) <NEW_LINE> for key, arr in matches.items(): <NEW_LINE> <INDENT> if arr.size != 0: <NEW_LINE> <INDENT> f[h5_group].create_dataset(key, data=arr) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return match_dict | Save another copy of the matches into a NumPy file. | 625941c321a7993f00bc7ca1 |
def asrequirement(self): <NEW_LINE> <INDENT> return u"%s(=%s)" % (self.package,self.version) | Return package and version for designing this package in depends or install actions
Returns:
str: "packagename (=version)" | 625941c3b830903b967e98c1 |
def parse(self, content): <NEW_LINE> <INDENT> self.found = False <NEW_LINE> self.anime = None <NEW_LINE> self.feed(content) <NEW_LINE> title = self.anime.strip().replace( ' - MyAnimeList.net', '') if self.found else None <NEW_LINE> return dict(title=title) | Parse content and return object | 625941c34a966d76dd550fc2 |
def setup(root=None, settings_module_name=None): <NEW_LINE> <INDENT> root = root or os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> path = lambda *a: os.path.join(root, *a) <NEW_LINE> settings_module_name = settings_module_name or 'settings' <NEW_LINE> settings = import_module(settings_module_name) <NEW_LINE> if os.path.exists(path('lib')): <NEW_LINE> <INDENT> site.addsitedir(path('lib')) <NEW_LINE> <DEDENT> setup_environ(settings) | Simple setup snippet that makes easy to create
fast sandbox to try new things.
:param root: the root of your project
:param settings_module_name: name of settings module eg:
"project.setting"
Usage:
>>> import env
>>> env.setup()
>>> # from now on paths are setup, and django is configured
>>> # you can use it in separate "sandbox" script just to check
>>> # things really quick | 625941c32eb69b55b151c861 |
def test_options_structure(self): <NEW_LINE> <INDENT> deploy = self.wsgiDeploy() <NEW_LINE> expected_keys = self.DEFAULTS.keys() <NEW_LINE> actual_keys = deploy.options.keys() <NEW_LINE> self.assertListEqual(expected_keys, actual_keys) | A test to ensure that HendrixDeploy.options also has the complete set
of options available | 625941c3de87d2750b85fd45 |
def count_possible_inputs(meta_data, networks): <NEW_LINE> <INDENT> input_counts = [defaultdict(int) for g in xrange(meta_data.G)] <NEW_LINE> for net in networks: <NEW_LINE> <INDENT> for g in xrange(meta_data.G): <NEW_LINE> <INDENT> input_counts[g][net.input_parameters[g]] += 1 <NEW_LINE> <DEDENT> <DEDENT> return input_counts | Count how often each possible input parameters occurs. | 625941c3cdde0d52a9e52fe6 |
def cmd_user(self, line): <NEW_LINE> <INDENT> if len(line) > 1: <NEW_LINE> <INDENT> self.user = line[1] <NEW_LINE> self.respond('331 Password required.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.command_not_understood(string.join(line)) | specify user name | 625941c31b99ca400220aa66 |
def tupleify_state(state): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> for row in state: <NEW_LINE> <INDENT> temp.append(tuple(row)) <NEW_LINE> <DEDENT> return tuple(temp) | Returns the state as a tuple | 625941c329b78933be1e5663 |
def nextAction(game, player): <NEW_LINE> <INDENT> output("What do you want to do today ?") <NEW_LINE> connections = game.rooms[player.where].connections <NEW_LINE> names = [] <NEW_LINE> for c in connections: <NEW_LINE> <INDENT> if game.rooms[c].explored: <NEW_LINE> <INDENT> names.append(game.rooms[c].description) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> names.append("unknown room") <NEW_LINE> <DEDENT> <DEDENT> output("0.........other actions") <NEW_LINE> for d in enumerate(names, 1): <NEW_LINE> <INDENT> output("{}.........{}".format(d[0], d[1])) <NEW_LINE> <DEDENT> answer = select_number(range(len(names)+1)) <NEW_LINE> if answer != 0: <NEW_LINE> <INDENT> return connections[int(answer)-1] <NEW_LINE> <DEDENT> output("") <NEW_LINE> output("What do you want to do today?") <NEW_LINE> actions = {"d":"drop item", "i":"inspect inventory", "p":"pick up item", "u":"use item", "c":"cancel"} <NEW_LINE> for a in actions: <NEW_LINE> <INDENT> output("{}....{}".format(a, actions[a])) <NEW_LINE> <DEDENT> answer = "" <NEW_LINE> while answer not in actions: <NEW_LINE> <INDENT> answer = input("please type selected letter and press ENTER: ") <NEW_LINE> <DEDENT> if answer == "i": <NEW_LINE> <INDENT> show_inventory(game, player) <NEW_LINE> <DEDENT> elif answer == "d": <NEW_LINE> <INDENT> drop_item(game, player) <NEW_LINE> <DEDENT> elif answer == "p": <NEW_LINE> <INDENT> pickup_item(game, player) <NEW_LINE> <DEDENT> elif answer == "u": <NEW_LINE> <INDENT> use_item(game, player) <NEW_LINE> <DEDENT> return player.where | ask the user to select only one of many options | 625941c3796e427e537b0579 |
def loc_glbl_var(individual: np.ndarray) -> float: <NEW_LINE> <INDENT> mids = tuple(map(lambda x: int(x/2), individual.shape)) <NEW_LINE> s1 = np.var(individual[:mids[0], :mids[1]]) <NEW_LINE> s2 = np.var(individual[:mids[0], mids[1]:]) <NEW_LINE> s3 = np.var(individual[mids[0]:, :mids[1]]) <NEW_LINE> s4 = np.var(individual[mids[0]:, mids[1]:]) <NEW_LINE> result = s1 + s2 + s3 + s4 - 10*np.var(individual[...]) <NEW_LINE> return float(result) | Computes score as function of quadrant and global variance
:param individual: candidate to score
:return: sum of quadrant variance - 5*global variance | 625941c315baa723493c3f28 |
def __init__(self,spec_path='M:\\fwog\\members\\qiu05\\Dec_2017_APS\\fer',spec_name='rcut_cmp_zn_7mm_1.spec',scan_number=[15]+range(17,41), corr_params=CORR_PARAMS, integ_pars=INTEG_PARS, general_labels=GENERAL_LABELS, correction_labels=CORRECTION_LABELS, angle_labels=ANGLE_LABELS, angle_labels_escan=ANGLE_LABELS_ESCAN, G_labels=G_LABELS, img_extention=IMG_EXTENTION, find_center_pix=False, substrate='muscovite', rank=rank, size=size): <NEW_LINE> <INDENT> self.spec_path=spec_path <NEW_LINE> self.spec_name=spec_name <NEW_LINE> self.dl_bl=dl_bl_lib[substrate] <NEW_LINE> self.bragg_peaks_lib=bragg_peaks_lib[substrate] <NEW_LINE> self.substrate=substrate <NEW_LINE> self.scan_number=scan_number <NEW_LINE> self.rank=rank <NEW_LINE> self.size=size <NEW_LINE> self.data_info={} <NEW_LINE> self.corr_params=corr_params <NEW_LINE> self.integ_pars=integ_pars <NEW_LINE> self.general_labels=general_labels <NEW_LINE> self.correction_labels=correction_labels <NEW_LINE> self.angle_labels=angle_labels <NEW_LINE> self.angle_labels_escan=angle_labels_escan <NEW_LINE> self.G_labels=G_labels <NEW_LINE> self.img_extention=img_extention <NEW_LINE> self.combine_spec_image_info() <NEW_LINE> if scan_number!=[] and find_center_pix: <NEW_LINE> <INDENT> self.find_center_pix() <NEW_LINE> <DEDENT> if mpi_tag: <NEW_LINE> <INDENT> self.data_info_copy=copy.copy(self.data_info) <NEW_LINE> self.assign_jobs() <NEW_LINE> self.extract_data_info() <NEW_LINE> <DEDENT> self.batch_image_integration() <NEW_LINE> self.data_info['substrate']=substrate <NEW_LINE> if not mpi_tag: <NEW_LINE> <INDENT> self.formate_hkl() <NEW_LINE> <DEDENT> if scan_number!=[] and not mpi_tag: <NEW_LINE> <INDENT> self.report_info() | spec_path:full path to the directory of the spec file
spec_name:full name of the spec file
scan_number=
[]:do nothing but initilize the instance (do this when you want to reload a saved dump data_info file)
None: do all rodscan and Escan throughout the spec file
[13,14,15,16]:a list of integers specify the scan numbers you want to do | 625941c38e7ae83300e4af80 |
def my_service(): <NEW_LINE> <INDENT> logging.debug("Starting") <NEW_LINE> time.sleep(0.3) <NEW_LINE> logging.debug("Stopping") | "thread service function | 625941c396565a6dacc8f680 |
def test_if_delete_allowed_photograph_detail(self): <NEW_LINE> <INDENT> handpiece = Handpiece.objects.get(name="testhandpiece") <NEW_LINE> photograph = Photograph.objects.get(handpiece=handpiece) <NEW_LINE> response = self.client.delete( reverse('api:photograph-detail', kwargs={'pk': photograph.id}), kwargs={'id': 300}, format="json") <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) | Test if DELETE method is NOT allowed on photograph detail view. | 625941c36fece00bbac2d6f2 |
def parse_config(path=DEFAULT_CONFIG_PATH, section=None, eval_keys=['metrics', 'queries']): <NEW_LINE> <INDENT> configreader = configparser.RawConfigParser() <NEW_LINE> try: <NEW_LINE> <INDENT> configreader.read(path) <NEW_LINE> configdict = configreader._sections <NEW_LINE> configdict = configdict[section] if section else configdict <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> logger.error('Unable to load/parse .cfg file at "{}". Does it exist?'.format( path)) <NEW_LINE> configdict = {} <NEW_LINE> <DEDENT> for k in eval_keys: <NEW_LINE> <INDENT> if k in configdict: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> configdict[k] = eval(configdict[k], {'pd': pd, 'np': np}, {}) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.error('Unable to eval(configdict[{}]):\n{}'.format(k, configdict[k])) <NEW_LINE> msg = format_exc() <NEW_LINE> logger.error(msg) <NEW_LINE> print(msg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return dict2obj(configdict) | Pares a cfg file, retrieving the requested section as a dictionary
Args:
section (str): name of the section you'd like to extract
eval_keys (list of str): Parser will try to evaluate strings in the config variables for the indicated eval_keys | 625941c33d592f4c4ed1d027 |
def test_parent(self) -> None: <NEW_LINE> <INDENT> state = State() <NEW_LINE> cloned_state = state.clone() <NEW_LINE> assert cloned_state.parent is state <NEW_LINE> del state <NEW_LINE> gc.collect() <NEW_LINE> assert cloned_state.parent is None | Test referencing parent and weak reference handling. | 625941c360cbc95b062c64f7 |
def chunks(iterable, chunk_size: int = 1000): <NEW_LINE> <INDENT> iter_data = iter(iterable) <NEW_LINE> while True: <NEW_LINE> <INDENT> chunk = tuple(itertools.islice(iter_data, chunk_size)) <NEW_LINE> if not chunk: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> yield chunk | split iterable array into chunks
>>> chunks(range(6),chunk_size=2)
... [(0,1),(2,3),(4,5)]
:param iterable: list, iter
:param chunk_size: chunk split size
:return: yield iterable values | 625941c3d99f1b3c44c67546 |
@contract(res='dict') <NEW_LINE> def _dynreports_getres(res): <NEW_LINE> <INDENT> return res['f-result'] | gets only the result | 625941c376e4537e8c351626 |
def on_intent(intent_request, session): <NEW_LINE> <INDENT> print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) <NEW_LINE> intent = intent_request['intent'] <NEW_LINE> intent_name = intent_request['intent']['name'] <NEW_LINE> if intent_name == "CityIntent": <NEW_LINE> <INDENT> return say_wind_speed(intent, session) <NEW_LINE> <DEDENT> elif intent_name == "AMAZON.HelpIntent": <NEW_LINE> <INDENT> return get_welcome_response() <NEW_LINE> <DEDENT> elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent": <NEW_LINE> <INDENT> return handle_session_end_request() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid intent") | Called when the user specifies an intent for this skill | 625941c307f4c71912b11436 |
def get_stock_balance(code): <NEW_LINE> <INDENT> cpTradeUtil.TradeInit() <NEW_LINE> acc = cpTradeUtil.AccountNumber[0] <NEW_LINE> accFlag = cpTradeUtil.GoodsList(acc, 1) <NEW_LINE> cpBalance.SetInputValue(0, acc) <NEW_LINE> cpBalance.SetInputValue(1, accFlag[0]) <NEW_LINE> cpBalance.SetInputValue(2, 50) <NEW_LINE> cpBalance.BlockRequest() <NEW_LINE> if code == 'ALL': <NEW_LINE> <INDENT> dbgout('계좌명: ' + str(cpBalance.GetHeaderValue(0))) <NEW_LINE> dbgout('결제잔고수량 : ' + str(cpBalance.GetHeaderValue(1))) <NEW_LINE> dbgout('평가금액: ' + str(cpBalance.GetHeaderValue(3))) <NEW_LINE> dbgout('평가손익: ' + str(cpBalance.GetHeaderValue(4))) <NEW_LINE> dbgout('종목수: ' + str(cpBalance.GetHeaderValue(7))) <NEW_LINE> <DEDENT> stocks = [] <NEW_LINE> for i in range(cpBalance.GetHeaderValue(7)): <NEW_LINE> <INDENT> stock_code = cpBalance.GetDataValue(12, i) <NEW_LINE> stock_name = cpBalance.GetDataValue(0, i) <NEW_LINE> stock_qty = cpBalance.GetDataValue(15, i) <NEW_LINE> if code == 'ALL': <NEW_LINE> <INDENT> dbgout(str(i+1) + ' ' + stock_code + '(' + stock_name + ')' + ':' + str(stock_qty)) <NEW_LINE> stocks.append({'code': stock_code, 'name': stock_name, 'qty': stock_qty}) <NEW_LINE> <DEDENT> if stock_code == code: <NEW_LINE> <INDENT> return stock_name, stock_qty <NEW_LINE> <DEDENT> <DEDENT> if code == 'ALL': <NEW_LINE> <INDENT> return stocks <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stock_name = cpCodeMgr.CodeToName(code) <NEW_LINE> return stock_name, 0 | 인자로 받은 종목의 종목명과 수량을 반환한다. | 625941c3be383301e01b543e |
def site_read(context, data_dict): <NEW_LINE> <INDENT> return {'success': True} | This function should be deprecated. It is only here because we couldn't
get hold of Friedrich to ask what it was for.
./ckan/controllers/api.py | 625941c3a219f33f34628921 |
def mutated_additional_data(func): <NEW_LINE> <INDENT> func_name = func.__name__ <NEW_LINE> @wraps(func) <NEW_LINE> def handle_mutate(session, *args, **kwargs): <NEW_LINE> <INDENT> log.debug("Mutating value on function %s with args %s and kwargs %s" % (func_name, unicode(args), unicode(kwargs))) <NEW_LINE> ret = func(session, *args, **kwargs) <NEW_LINE> session._additional_data = session._cache_additional_data <NEW_LINE> return ret <NEW_LINE> <DEDENT> return handle_mutate | A decorator to track mutation and propagate it to the database.
The decorator is to be used on all functions that change the value of the
:attr:`Session.additional_data` dict. Functions like ``set`` or ``pop``
need this decorator to ensure the changes are afterwards propagated
into the database.
From an implementation point it just sets the complete dictionary as a
new value. | 625941c31d351010ab855ad1 |
def twoSum(self, nums, target): <NEW_LINE> <INDENT> dict = {} <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> x = nums[i] <NEW_LINE> if target - x in dict: <NEW_LINE> <INDENT> return [dict[target - x], i] <NEW_LINE> <DEDENT> dict[x] = i <NEW_LINE> <DEDENT> return [] | :type nums: List[int]
:type target: int
:rtype: List[int] | 625941c3656771135c3eb821 |
def _insert_object_resp(bucket=None, name=None, data=None): <NEW_LINE> <INDENT> assert type(data) is bytes <NEW_LINE> hasher = hashlib.md5() <NEW_LINE> hasher.update(data) <NEW_LINE> md5_hex_hash = hasher.hexdigest() <NEW_LINE> return { u'bucket': bucket, u'name': name, u'md5Hash': _hex_to_base64(md5_hex_hash), u'timeCreated': _datetime_to_gcptime(), u'size': str(len(data)), u'_data': data } | Fake GCS object metadata | 625941c3d6c5a10208143ffe |
def test_favoriting_referendum_without_existent_user(new_session): <NEW_LINE> <INDENT> from sqlalchemy.exc import IntegrityError <NEW_LINE> new_session.add(make_test_referendum(666)) <NEW_LINE> with pytest.raises(IntegrityError): <NEW_LINE> <INDENT> new_session.flush() | Test the database rejects favoriting a candidate without a user. | 625941c36e29344779a625c8 |
def box(): <NEW_LINE> <INDENT> print("---Box---") <NEW_LINE> D1 = Symbol('D1') <NEW_LINE> D2 = Symbol('D2') <NEW_LINE> D3 = Symbol('D3') <NEW_LINE> D4 = Symbol('D4') <NEW_LINE> h1 = h3 = D3 <NEW_LINE> h2 = D2 - h1 - h3 <NEW_LINE> w1 = w3 = D4 <NEW_LINE> w2 = D1 - w1 - w3 <NEW_LINE> o2 = Rational(1, 2) <NEW_LINE> p1 = [0, D2 * o2] <NEW_LINE> a = subx(p1, D1 * o2) <NEW_LINE> b = addx(p1, D1 * o2) <NEW_LINE> c = suby(b, D2) <NEW_LINE> d = subx(c, D1) <NEW_LINE> e = suby(p1, D3) <NEW_LINE> f = addx(e, w2) <NEW_LINE> g = suby(f, h2) <NEW_LINE> h = subx(g, w2) <NEW_LINE> sections = [[1, a, b], [1, b, c], [1, c, d], [1, d, a], [-1, e, f], [-1, f, g], [-1, g, h], [-1, h, e]] <NEW_LINE> Ixx(sections) | y
^
|
w1 | w2 w3
|
a-----p1------b
| | | h1
| e--|----f |
| | | | |
| | | | | h2
| | o-------|--> x
| | | |
| h-------g |
| | h3
d-------------c
# given
#a-d = D2
#(f-g)_y = D3
#d-c = D1
#(g-c)_x = D4 | 625941c37d43ff24873a2c54 |
def InterpolateValueCore(self,*args): <NEW_LINE> <INDENT> pass | InterpolateValueCore(self: SplineSingleKeyFrame,baseValue: Single,keyFrameProgress: float) -> Single
Uses splined interpolation to transition between the previous key frame value and the value of
the current key frame.
baseValue: The value to animate from.
keyFrameProgress: A value between 0.0 and 1.0,inclusive,that specifies the percentage of time that has elapsed
for this key frame.
Returns: The output value of this key frame given the specified base value and progress. | 625941c3f8510a7c17cf96b0 |
def read_filtered_directory_content(dirpath, *filters): <NEW_LINE> <INDENT> def filter_directory_files(dirpath, *filters): <NEW_LINE> <INDENT> return it.chain.from_iterable(glob.iglob(dirpath + '/' + filter) for filter in filters) <NEW_LINE> <DEDENT> content_dict = {} <NEW_LINE> for filename in filter_directory_files(dirpath, *filters): <NEW_LINE> <INDENT> content = "" <NEW_LINE> with open(os.path.join(filename), 'rb') as obj: <NEW_LINE> <INDENT> content = obj.read() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> content.decode('utf-8') <NEW_LINE> <DEDENT> except UnicodeError: <NEW_LINE> <INDENT> content = content.encode('base64') <NEW_LINE> content_dict['base64_encoded_files'] = content_dict.get("base64_encoded_files", []) + [filename] <NEW_LINE> <DEDENT> content_dict[filename] = content <NEW_LINE> <DEDENT> return content_dict | Reads the content of a directory, filtered on glob like expressions.
Returns a dictionary, with the "key" being the filename
and the "value" being the content of that file. | 625941c3d18da76e23532489 |
def __json_struct__(self): <NEW_LINE> <INDENT> if self._value or self._value == 0: <NEW_LINE> <INDENT> super().__json_struct__() | :return: | 625941c3ad47b63b2c509f34 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.