code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def PrintDeffacts(self): <NEW_LINE> <INDENT> _c.routerClear("temporary") <NEW_LINE> _c.listDeffacts("temporary", self.__defmodule) <NEW_LINE> s = _c.routerRead("temporary") <NEW_LINE> if s: <NEW_LINE> <INDENT> _sys.stdout.write(s) | print Deffacts to standard output | 625941c1f7d966606f6a9f82 |
def transport_link(): <NEW_LINE> <INDENT> transport = paramiko.Transport(('192.168.142.128', 22)) <NEW_LINE> transport.connect(username='ysan', password='ysan') <NEW_LINE> ssh = paramiko.SSHClient() <NEW_LINE> ssh._transport = transport <NEW_LINE> stdin, stdout, sterr = ssh.exec_command("ls") <NEW_LINE> print(stdout.read().decode()) <NEW_LINE> ssh.close() | 通过transport连接
:return: | 625941c145492302aab5e241 |
def _is_collection(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> iter(self.example) <NEW_LINE> return True <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False | Returns True if the given example is a collection of examples
(aka, ExampleGroup), or just one example. | 625941c1e8904600ed9f1eaa |
def __init__(self, basekey='', redis_server='localhost', redis_port=6379): <NEW_LINE> <INDENT> self.basekey = basekey <NEW_LINE> self.hits = 0 <NEW_LINE> self.misses = 0 <NEW_LINE> self.lookups = 0 <NEW_LINE> self.redis = redis.Redis(host=redis_server, port=redis_port, db=0) | Initialize a Cache instance
Caches can preprend a basekey to every cached item, e.g. for using a cache provider such as Redis with multiple
Cache instances. Remember to include a seperator in the base key | 625941c1d58c6744b4257be0 |
def results2json(self, results, outfile_prefix): <NEW_LINE> <INDENT> result_files = dict() <NEW_LINE> if isinstance(results[0], list): <NEW_LINE> <INDENT> json_results = self._det2json(results) <NEW_LINE> result_files['bbox'] = f'{outfile_prefix}.bbox.json' <NEW_LINE> result_files['proposal'] = f'{outfile_prefix}.bbox.json' <NEW_LINE> mmcv.dump(json_results, result_files['bbox']) <NEW_LINE> <DEDENT> elif isinstance(results[0], tuple): <NEW_LINE> <INDENT> json_results = self._segm2json(results) <NEW_LINE> result_files['bbox'] = f'{outfile_prefix}.bbox.json' <NEW_LINE> result_files['proposal'] = f'{outfile_prefix}.bbox.json' <NEW_LINE> result_files['segm'] = f'{outfile_prefix}.segm.json' <NEW_LINE> print("Start dump bbox json.") <NEW_LINE> mmcv.dump(json_results[0], result_files['bbox']) <NEW_LINE> print("Start dump segm json.") <NEW_LINE> if len(json_results[0])<=5000000: <NEW_LINE> <INDENT> mmcv.dump(json_results[1], result_files['segm']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Split segm into {} parts, each includes 10000 images".format(len(json_results[0])//100000)) <NEW_LINE> for i in range(0,len(json_results[0])//100000): <NEW_LINE> <INDENT> print("Start dump segm {} json.".format(i)) <NEW_LINE> mmcv.dump(json_results[1][i*100000:(i+1)*100000], f'{outfile_prefix}.segm{i}.json') <NEW_LINE> <DEDENT> if len(json_results[0])>(i+1)*100000: <NEW_LINE> <INDENT> print("Start dump segm last json.") <NEW_LINE> mmcv.dump(json_results[1][(i + 1) * 100000:], f'{outfile_prefix}.segm{i+1}.json') <NEW_LINE> <DEDENT> <DEDENT> print("Finish dumping files") <NEW_LINE> <DEDENT> elif isinstance(results[0], np.ndarray): <NEW_LINE> <INDENT> json_results = self._proposal2json(results) <NEW_LINE> result_files['proposal'] = f'{outfile_prefix}.proposal.json' <NEW_LINE> mmcv.dump(json_results, result_files['proposal']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('invalid type of results') <NEW_LINE> <DEDENT> return result_files | Dump the detection results to a COCO style json file.
There are 3 types of results: proposals, bbox predictions, mask
predictions, and they have different data types. This method will
automatically recognize the type, and dump them to json files.
Args:
results (list[list | tuple | ndarray]): Testing results of the
dataset.
outfile_prefix (str): The filename prefix of the json files. If the
prefix is "somepath/xxx", the json files will be named
"somepath/xxx.bbox.json", "somepath/xxx.segm.json",
"somepath/xxx.proposal.json".
Returns:
dict[str: str]: Possible keys are "bbox", "segm", "proposal", and
values are corresponding filenames. | 625941c1be383301e01b5409 |
def view_mentors_titles(): <NEW_LINE> <INDENT> titles = ["Name", "Surname", "e-mail"] <NEW_LINE> return titles | Hold strings w column titles for printing mentors
list.
Return:
list: list of strings | 625941c1287bf620b61d39e5 |
def combine_chem_and_elec(self): <NEW_LINE> <INDENT> self.D = self.C.copy() <NEW_LINE> for (a,b) in self.E.edges(): <NEW_LINE> <INDENT> w = 0.5*self.E[a][b]['weight'] <NEW_LINE> if not self.D.has_edge(a,b): self.D.add_edge(a,b,weight=0) <NEW_LINE> if not self.D.has_edge(b,a): self.D.add_edge(b,a,weight=0) <NEW_LINE> self.D[a][b]['weight'] += w <NEW_LINE> self.D[b][a]['weight'] += w | Combine the chemical and gap junction connectivity graphs
Combined graph stored in attribute self.D | 625941c15e10d32532c5eea7 |
def testMySQL(self): <NEW_LINE> <INDENT> self.genericTest(testname='testMySQL', testoptions={'dialect':'mysql', 'host':'host', 'database':'database'}, testurl='mysql://host/database') <NEW_LINE> self.genericTest(testname='testMySQL', testoptions={'dialect':'mysql', 'host':'host', 'username':'username', 'database':'database'}, testurl='mysql://username@host/database') <NEW_LINE> self.genericTest(testname='testMySQL', testoptions={'dialect':'mysql', 'host':'host', 'username':'username', 'password':'password', 'database':'database', 'port':1234}, testurl='mysql://username:password@host:1234/database') | Test that factory correctly makes:
mysql://host/database
mysql://username@host/database
mysql://username:password@host:1234/database | 625941c15fc7496912cc38fe |
def BN(der): <NEW_LINE> <INDENT> BN = np.zeros((3,8)) <NEW_LINE> BN[0,0:4] = der[0,:] <NEW_LINE> BN[1,4:] = der[1,:] <NEW_LINE> BN[2,0:4] = der[1,:] <NEW_LINE> BN[2,4:] = der[0,:] <NEW_LINE> return BN | build the deformation tensor shape functions
DOFs are assumed to be ordered as [x0 x1 x2 x3 y0 y1 y2 y3] | 625941c18e7ae83300e4af4c |
def load(self, filepath): <NEW_LINE> <INDENT> if not os.path.isfile(filepath): <NEW_LINE> <INDENT> print("File open error: {} not found".format(filepath)) <NEW_LINE> return <NEW_LINE> <DEDENT> with open(filepath, "r") as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> if len(lines) != 2: <NEW_LINE> <INDENT> print("Format error: ") <NEW_LINE> return <NEW_LINE> <DEDENT> self.base = [int(x) for x in lines[0].split(",")] <NEW_LINE> self.check = [int(x) for x in lines[1].split(",")] | load double array
Parameters
----------
filepath : str
filepath | 625941c1aad79263cf3909be |
def set_directory_structure(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.screenshots_parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','screenshots')) <NEW_LINE> if not os.path.exists(self.screenshots_parent_dir): <NEW_LINE> <INDENT> os.makedirs(self.screenshots_parent_dir) <NEW_LINE> <DEDENT> self.logs_parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','log')) <NEW_LINE> if not os.path.exists(self.logs_parent_dir): <NEW_LINE> <INDENT> os.makedirs(self.logs_parent_dir) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.write("Exception when trying to set directory structure") <NEW_LINE> self.write(str(e)) <NEW_LINE> self.exceptions.append("Error when setting up the directory structure") | Setup the required directory structure if it is not already present | 625941c101c39578d7e74dbb |
def update_cache(self, poss = { 'img': [] }): <NEW_LINE> <INDENT> urls_hash = sha1(self.urls_path) <NEW_LINE> if 'hash' in poss and poss['hash'] == urls_hash: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.logger.debug("urls hash was not up to date") <NEW_LINE> self.logger.debug("updating cache") <NEW_LINE> poss['hash'] = urls_hash <NEW_LINE> self.logger.debug("get the current set of urls") <NEW_LINE> urls = [] <NEW_LINE> with copen(self.urls_path) as u: <NEW_LINE> <INDENT> urls = set([i.strip('\n') for i in u.readlines()]) <NEW_LINE> logging.debug("got urls: %s", urls) <NEW_LINE> <DEDENT> from glob import glob <NEW_LINE> poss['img'] = [{ 'url': url } for url in urls] <NEW_LINE> cached_images = glob(self.config['cache-prefix'] + "/*") <NEW_LINE> poss['img'].extend([{ 'url': self.config['cache-prefix'] + fn, 'mime_type': mimetypes.guess_type(fn)[0], 'cached': True } for fn in cached_images]) <NEW_LINE> poss['img'] = [Chooser.fetch(img) for img in poss['img']] <NEW_LINE> poss = Chooser.with_valid_imgs(poss) <NEW_LINE> self.update_manifest(poss) <NEW_LINE> self.logger.debug("fetched: %s", poss['img']) <NEW_LINE> self.update_urls([img['url'] for img in poss['img']]) | Completely rebuilds the cache from the file at self.urls_path. | 625941c130bbd722463cbd44 |
def plot_result_per_step(self, ax=None, color="b", plot_min=None, plot_max=None): <NEW_LINE> <INDENT> self._logger.debug("Plotting result per step. ax %s, colors %s, " "plot_min %s, plot_max %s", ax, color, plot_min, plot_max) <NEW_LINE> plots = self._best_result_per_step_dicts(color, cutoff_percentage=0.5) <NEW_LINE> if self._experiment.minimization_problem: <NEW_LINE> <INDENT> legend_loc = 'upper right' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> legend_loc = 'upper left' <NEW_LINE> <DEDENT> self._logger.debug("Setting legend to %s LOC", legend_loc) <NEW_LINE> plot_options = { "legend_loc": legend_loc, "x_label": "steps", "y_label": "result", "title": "Plot of %s result over the steps." % (str(self._experiment.name)), "minimizing": self._experiment.minimization_problem } <NEW_LINE> self._logger.debug("Plot options are %s", plot_options) <NEW_LINE> fig, ax = plot_lists(plots, ax=ax, fig_options=plot_options, plot_min=plot_min, plot_max=plot_max) <NEW_LINE> return fig | Returns the plt.figure plotting the results over the steps.
Parameters
----------
ax : None or matplotlib.Axes, optional
The ax to update. If None, a new figure will be created.
color : string, optional
A string representing a pyplot color.
plot_min : float, optional
The smallest value to plot on the y axis.
plot_max : float, optional
The biggest value to plot on the y axis.
Returns
-------
ax: plt.Axes
The Axes containing the results over the steps. | 625941c18e05c05ec3eea2f3 |
def parse(self, response): <NEW_LINE> <INDENT> a_selectors = response.xpath("//a[contains(@href, 'amazon')]") <NEW_LINE> with open('AmazonLinks.txt','a') as f: <NEW_LINE> <INDENT> for selector in a_selectors: <NEW_LINE> <INDENT> text = selector.xpath("text()").extract_first() <NEW_LINE> link = selector.xpath("@href").extract_first() <NEW_LINE> if "amazon" in link: <NEW_LINE> <INDENT> if not (text is None) and not (link[40]=='B'): <NEW_LINE> <INDENT> f.write(link[40:50]+'\t'+text+'\n') | Main function that parses downloaded pages | 625941c1187af65679ca509e |
def wsgi_middleware(self, app): <NEW_LINE> <INDENT> _app = StaticServerMiddleware(app, '/' + self.prefix, self.path) <NEW_LINE> def app(environ, start_response): <NEW_LINE> <INDENT> if not hasattr(self, 'host_url'): <NEW_LINE> <INDENT> self.host_url = (environ['wsgi.url_scheme'] + '://' + environ['HTTP_HOST'] + '/') <NEW_LINE> <DEDENT> return _app(environ, start_response) <NEW_LINE> <DEDENT> return app | WSGI middlewares that wraps the given ``app`` and serves
actual image files. ::
fs_store = HttpExposedFileSystemStore('userimages', 'images/')
app = fs_store.wsgi_middleware(app)
:param app: the wsgi app to wrap
:type app: :class:`collections.Callable`
:returns: the another wsgi app that wraps ``app``
:rtype: :class:`StaticServerMiddleware` | 625941c14c3428357757c2aa |
def run(): <NEW_LINE> <INDENT> env = Environment() <NEW_LINE> agent = env.create_agent(LearningAgent,learning=True,alpha=0.5) <NEW_LINE> env.set_primary_agent(agent,enforce_deadline=True) <NEW_LINE> sim = Simulator(env,display=False,update_delay=0.01,log_metrics=True,optimized=True) <NEW_LINE> sim.run(n_test=40) | Driving function for running the simulation.
Press ESC to close the simulation, or [SPACE] to pause the simulation. | 625941c1462c4b4f79d1d650 |
def get_top_level_folders(self, **kwargs): <NEW_LINE> <INDENT> limit = kwargs.get('limit', None) <NEW_LINE> start = kwargs.get('start', None) <NEW_LINE> return_count = kwargs.get('return_count', False) <NEW_LINE> append_personal = kwargs.get('append_personal', True) <NEW_LINE> try: <NEW_LINE> <INDENT> libraries = self.api._fetch_libraries(limit=limit, start=start) <NEW_LINE> <DEDENT> except zotero_errors.ResourceNotFound: <NEW_LINE> <INDENT> raise HTTPError(404) <NEW_LINE> <DEDENT> except zotero_errors.UserNotAuthorised: <NEW_LINE> <INDENT> raise HTTPError(403) <NEW_LINE> <DEDENT> except zotero_errors.HTTPError: <NEW_LINE> <INDENT> sentry.log_exception() <NEW_LINE> sentry.log_message('Unexpected Zotero Error when fetching group libraries.') <NEW_LINE> raise HTTPError(500) <NEW_LINE> <DEDENT> serialized = [] <NEW_LINE> for library in libraries[:-1]: <NEW_LINE> <INDENT> data = library['data'] <NEW_LINE> serialized.append(self.serialize_folder('library', data['id'], data['name'], str(data['id']))) <NEW_LINE> <DEDENT> if return_count: <NEW_LINE> <INDENT> serialized.append(libraries[-1]) <NEW_LINE> <DEDENT> if append_personal: <NEW_LINE> <INDENT> serialized.insert(0, self.serialize_folder('library', 'personal', 'My Library', 'personal')) <NEW_LINE> <DEDENT> return serialized | Returns serialized group libraries - your personal library along with any group libraries.
This is the top-tier of "folders" in Zotero.
You can use kwargs to refine what data is returned - how to limit the number of group libraries,
whether to return the personal library alongside group_libraries, or append the total library count. | 625941c166673b3332b92011 |
def __init__(self, interface, duration, callback): <NEW_LINE> <INDENT> self._timeout = EventTimeout(duration=duration, timeout_cb=callback) <NEW_LINE> self._events = [ interface.sensors.kidnapped_event, interface.sensors.pickup_event, interface.sensors.putdown_event, interface.touch.touch_event, interface.power.docked_event, interface.nav_client.nav_event, interface.wheels_mux.teleop.move_event, interface.head_ctl.move_event, interface.comm_interface.command_event, interface.voice.wake_event] <NEW_LINE> for event in self._events: <NEW_LINE> <INDENT> event.connect(self._reset_timeout) | :params interface: gizmo Context.
:params duration: wait before timing out in seconds.
:params callback: function to call once the task time out. | 625941c150812a4eaa59c2a4 |
def plot3d(self, **kwds): <NEW_LINE> <INDENT> from sage.plot.plot3d.shapes2 import text3d <NEW_LINE> options = self._plot3d_options() <NEW_LINE> options.update(kwds) <NEW_LINE> return text3d(self.string, (self.x, self.y, 0), **options) | Plot 2D text in 3D.
EXAMPLES::
sage: T = text("ABC", (1, 1))
sage: t = T[0]
sage: s = t.plot3d()
sage: s.jmol_repr(s.testing_render_params())[0][2]
'label "ABC"'
sage: s._trans
(1.0, 1.0, 0) | 625941c1796e427e537b0544 |
def context_cycle_array(data_path: str = "", reverse: bool = False): <NEW_LINE> <INDENT> pass | Set a context array value (useful for cycling the active mesh edit mode)
:param data_path: Context Attributes, RNA context string
:type data_path: str
:param reverse: Reverse, Cycle backwards
:type reverse: bool | 625941c1a8370b7717052821 |
def alpha_149(self): <NEW_LINE> <INDENT> return | 尚未实现 | 625941c1cad5886f8bd26f5a |
def test_get_counts2(doc: Doc) -> None: <NEW_LINE> <INDENT> doc[0]._.spaczz_ratio = 100 <NEW_LINE> doc[1]._.spaczz_counts = (0, 0, 0) <NEW_LINE> assert doc[:2]._.spaczz_counts is None | Returns span counts. | 625941c160cbc95b062c64c3 |
def get_name(header, splitchar = "_", items = 2): <NEW_LINE> <INDENT> if splitchar: <NEW_LINE> <INDENT> return "_".join(header.split(splitchar)[:items]).lstrip('>') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return header.lstrip('>') | use own function vs. import from match_contigs_to_probes - we don't want lowercase | 625941c11b99ca400220aa31 |
def setUp(self): <NEW_LINE> <INDENT> self.load_metrics() | Load metrics stored as jsons. | 625941c11b99ca400220aa32 |
def __init__(self, regression_model_description): <NEW_LINE> <INDENT> self.intercept = regression_model_description.intercept <NEW_LINE> self.coefs = regression_model_description.coefs <NEW_LINE> RegressionModelSimulator.__init__(self) | :param regression_model_description: OLSModelDescription | 625941c14e696a04525c93cd |
def get_band_value_fetch_pool(bandraster, pxy, dataType, cloud=False): <NEW_LINE> <INDENT> bandraster = gdal.Open(bandraster) <NEW_LINE> result = ( bandraster.GetRasterBand(1).ReadAsArray(int(pxy[0]), int(pxy[1]), 1, 1)[0, 0], ) <NEW_LINE> if cloud: <NEW_LINE> <INDENT> value = round(result, 4) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if dataType in [1, 2]: <NEW_LINE> <INDENT> value = round(result * 0.0001, 4) <NEW_LINE> <DEDENT> elif dataType is 3: <NEW_LINE> <INDENT> value = round(result * 0.02, 4) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = -1 <NEW_LINE> <DEDENT> <DEDENT> del bandraster <NEW_LINE> return value | function to get band value by fetching data given a locations
in: bandraster, raster band file
pxy, a tuple (x,y)
dataType, which satellite data
cloud, cloud masking
out: band raster data for given location
#NOTE, this function should be used in threading or alike parallel scheme | 625941c107d97122c4178807 |
def main(current_date, file_details, write_file=False, file_stem=None): <NEW_LINE> <INDENT> sources = _get_sources('source_keys.txt') <NEW_LINE> conn = utilities.make_conn(file_details.db_db, file_details.db_collection, file_details.auth_db, file_details.auth_user, file_details.auth_pass, file_details.db_host) <NEW_LINE> less_than = datetime.datetime(current_date.year, current_date.month, current_date.day) <NEW_LINE> greater_than = less_than - datetime.timedelta(days=1) <NEW_LINE> less_than = less_than + datetime.timedelta(days=1) <NEW_LINE> results, text = query_all(conn, less_than, greater_than, sources, write_file=write_file) <NEW_LINE> filename = '' <NEW_LINE> if text: <NEW_LINE> <INDENT> text = text.decode('utf-8') <NEW_LINE> if file_stem: <NEW_LINE> <INDENT> filename = '{}{:02d}{:02d}{:02d}.txt'.format(file_stem, current_date.year, current_date.month, current_date.day) <NEW_LINE> with codecs.open(filename, 'w', encoding='utf-8') as f: <NEW_LINE> <INDENT> f.write(text) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print('Need filestem to write results to file.') <NEW_LINE> <DEDENT> <DEDENT> return results, filename | Function to create a connection to a MongoDB instance, query for a given
day's results, optionally write the results to a file, and return the
results.
Parameters
----------
current_date: datetime object.
Date for which records are pulled. Normally this is
$date_running - 1. For example, if the script is running on
the 25th, the current_date will be the 24th.
file_details: Named tuple.
Tuple containing config information.
write_file: Boolean.
Option indicating whether to write the results from the web
scraper to an intermediate file. Defaults to false.
file_stem: String. Optional.
Optional string defining the file stem for the intermediate
file for the scraper results.
Returns
-------
posts: Dictionary.
Dictionary of results from the MongoDB query.
filename: String.
If `write_file` is True, contains the filename to which the
scraper results are writen. Otherwise is an empty string. | 625941c1dd821e528d63b12b |
def criteria(json_data): <NEW_LINE> <INDENT> return json_data['event_type'] in important_events | Helper function that returns a bool representing whether to process json_data | 625941c1a934411ee3751614 |
def create_fake_articles(apps, schema_editor): <NEW_LINE> <INDENT> Article = apps.get_model("articles", "Article") <NEW_LINE> for i in range(1, 10000): <NEW_LINE> <INDENT> Article.objects.create( title=create_fake_title(i), posted=timezone.now() - timedelta(minutes=i*10 + random.randint(1, 60)), upvotes=max(0, int(random.gauss(10, 30))), downvotes=max(0, int(random.gauss(10, 30))), ) | Create a random list of articles of sufficient size to test the workings and performance of the module. Each
article will have it's information set to something approaching a possible use-case. | 625941c1711fe17d825422f0 |
def calculate_ds_int(self): <NEW_LINE> <INDENT> dphidp = np.zeros([self.var_num + self.con_num, self.num_flatten_var]) <NEW_LINE> p_ind = {} <NEW_LINE> count = 1 <NEW_LINE> for x in self.states: <NEW_LINE> <INDENT> for j in self.state_vars[x]: <NEW_LINE> <INDENT> p_ind[(x,j)], = self.var_num + np.where(self.coninfo == count)[0] <NEW_LINE> dphidp[p_ind[(x,j)], count-1] = -1. <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> <DEDENT> ds_int = self.amsnmpc_kkt.solve(-dphidp) <NEW_LINE> return ds_int | kkt * ds = -dphidp * delP0, (final target is ds but only solve for ds_int in this function.)
ds = inv(kkt) * (-dphidp) *delP0
= ds_int *delP0, where ds_int = inv(kkt) * (-dphidp) | 625941c1b830903b967e988e |
@app.route('/binary=<string:number>') <NEW_LINE> def binary(number) -> dict: <NEW_LINE> <INDENT> return calculator_api.denary_binary(binary=number) | Converts Hexadecimal code to decimal(or denary)
:param hex_code: Stuff on which calculation will be carried on Example: 5+7*9
:return: Dictionary | 625941c1090684286d50ec64 |
def f_affine(t,y): <NEW_LINE> <INDENT> return a*y+b | Fonction affine pour y' = ay+b. Les coefficients a et b sont des
variables globales du module. | 625941c15fdd1c0f98dc01b3 |
def notifyMetaChanged(self, function, **kwargs): <NEW_LINE> <INDENT> return self._notifyGeneric(self._sig_changed, function, **kwargs) | calls the corresponding function when the slot meta
information is changed
first argument of the function is the slot
the keyword arguments follow | 625941c1379a373c97cfaac5 |
def iso8601_timestamp_to_datetime_obj(s): <NEW_LINE> <INDENT> s = s[:-1].split('.')[0] <NEW_LINE> try: <NEW_LINE> <INDENT> return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print(s) | 2017-05-17T04:03:05.173862Z
Ignore the fractional part for now. | 625941c1956e5f7376d70def |
def _updateConfigFromGui(self, bProfilesChanged=False): <NEW_LINE> <INDENT> gui = self.__gui <NEW_LINE> curProf = None <NEW_LINE> if bProfilesChanged: <NEW_LINE> <INDENT> curProf = self.__kolConfigsManager.getProfileByName( gui.cboProfiles.itemText(self.__PreviousChosenProfileIndex)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> curProf = self.__kolConfigsManager.getProfileByName( gui.cboProfiles.currentText()) <NEW_LINE> <DEDENT> if (curProf != None): <NEW_LINE> <INDENT> curProf.kanjiDeckName = gui.cboCustomDeckName.currentText() <NEW_LINE> curProf.kanjiExpression = gui.cboCustomExpression.currentText() <NEW_LINE> curProf.kanjiKeyword = gui.cboCustomKeyword.currentText() <NEW_LINE> curProf.kanjiOnYomi = gui.cboOnYomi.currentText() <NEW_LINE> curProf.kanjiKunYomi = gui.cboKunYomi.currentText() <NEW_LINE> curProf.kanjiMemoStory = gui.cboMemoStory.currentText() <NEW_LINE> curProf.kanjiCustomProfileEnabled = gui.chkUseCustomDeck.isChecked() <NEW_LINE> curProf.kanjiLoadDefaultValuesForNonExistingValues = gui.chkAlsoLoadDefaultDB.isChecked() <NEW_LINE> curProf.kanjiShowColorsForKnownKanji = gui.chkColorizeKanjis.isChecked() <NEW_LINE> curProf.kanjiUseLink = gui.chkKanjiLink.isChecked() <NEW_LINE> curProf.kanjiOnYomiEnabled = gui.chkOnYomi.isChecked() <NEW_LINE> curProf.kanjiKunYomiEnabled = gui.chkKunYomi.isChecked() <NEW_LINE> curProf.kanjiMemoStoryEnabled = gui.chkMemoStory.isChecked() <NEW_LINE> curProf.kanjiUseLinkUrl = gui.editKanjiLink.text() <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | bProfileChanged: if the Profile was changed, the previous chosen profile is used | 625941c17b25080760e393db |
def move_pr2_base(self, goal_pose): <NEW_LINE> <INDENT> self.simple_base_pose_pub.publish(goal_pose) | :type goal_pose: PoseStamped | 625941c1046cf37aa974ccca |
def compile_pillar(self, *args, **kwargs): <NEW_LINE> <INDENT> log.debug('Scanning pillar cache for information about minion %s and pillarenv %s', self.minion_id, self.pillarenv) <NEW_LINE> log.debug('Scanning cache for minion %s: %s', self.minion_id, self.cache[self.minion_id] or '*empty*') <NEW_LINE> if self.minion_id in self.cache: <NEW_LINE> <INDENT> if self.pillarenv in self.cache[self.minion_id]: <NEW_LINE> <INDENT> log.debug('Pillar cache hit for minion %s and pillarenv %s', self.minion_id, self.pillarenv) <NEW_LINE> pillar_data = self.cache[self.minion_id][self.pillarenv] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pillar_data = self.fetch_pillar() <NEW_LINE> self.cache[self.minion_id][self.pillarenv] = pillar_data <NEW_LINE> self.cache.store() <NEW_LINE> log.debug('Pillar cache miss for pillarenv %s for minion %s', self.pillarenv, self.minion_id) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> pillar_data = self.fetch_pillar() <NEW_LINE> self.cache[self.minion_id] = {self.pillarenv: pillar_data} <NEW_LINE> log.debug('Pillar cache has been added for minion %s', self.minion_id) <NEW_LINE> log.debug('Current pillar cache: %s', self.cache[self.minion_id]) <NEW_LINE> <DEDENT> return pillar_data | Compile pillar and set it to the cache, if not found.
:param args:
:param kwargs:
:return: | 625941c1cdde0d52a9e52fb2 |
def authorized_handler(self, method='POST', grant_type='authorization_code', decoder=parse_json): <NEW_LINE> <INDENT> def create_authorized_handler(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def decorated(*args, **kwargs): <NEW_LINE> <INDENT> resp = access_token = None <NEW_LINE> if 'error' in request.args and request.args['error'] == ACCESS_DENIED: <NEW_LINE> <INDENT> resp = ACCESS_DENIED <NEW_LINE> <DEDENT> elif 'code' in request.args: <NEW_LINE> <INDENT> key = 'data' <NEW_LINE> if method == 'GET': <NEW_LINE> <INDENT> key='params' <NEW_LINE> <DEDENT> gat_kwargs = { key: { 'code': request.args['code'], 'grant_type': grant_type, 'redirect_uri': session.pop(self._session_key('redirect_uri'), None) } } <NEW_LINE> access_token = self.get_access_token(method=method, decoder=decoder, **gat_kwargs) <NEW_LINE> resp = self.get_session(access_token) <NEW_LINE> <DEDENT> return f(*((resp, access_token) + args), **kwargs) <NEW_LINE> <DEDENT> return decorated <NEW_LINE> <DEDENT> return create_authorized_handler | The decorator to assign a function that will be called after
authorization is complete. By default, a `POST` request is used to
fetch the access token. If you need to send a `GET` request, use the
``authorized_handler(method='GET')`` to do so.
It should be a route that takes two parameters: `response` and
`access_token`.
If `response` is ``access_denied``, then the user denied access to
his/her information. | 625941c115fb5d323cde0a8d |
def save_classifier(self, classifier_name): <NEW_LINE> <INDENT> filename = OUTPUT_PATH + classifier_name + ".sav" <NEW_LINE> joblib.dump(self, filename) | Saves classifier as a .pickle file to the classifier_models directory
:param classifier_name: Name under which to save the classifier | 625941c1d18da76e23532454 |
def create_companion_app_routes(content_db_conn): <NEW_LINE> <INDENT> routes = create_core_routes() <NEW_LINE> routes.update(create_companion_app_routes_v1(content_db_conn)) <NEW_LINE> routes.update(create_companion_app_routes_v2(content_db_conn)) <NEW_LINE> return routes | Create routes and apply content_db_conn to them. | 625941c1046cf37aa974cccb |
def delete(): <NEW_LINE> <INDENT> lightning_client = get_db("lightning_storm") <NEW_LINE> collection_post = lightning_client['post'] <NEW_LINE> query_one = {"author": "sharp"} <NEW_LINE> modify = collection_post.delete_one(query_one) | 删除一条数据
:return: | 625941c1ff9c53063f47c175 |
def set_learning(self): <NEW_LINE> <INDENT> self.learn = True | Set game to learning
Note: by default, the game is not learning | 625941c182261d6c526ab41d |
def compare_models(self, params, context=None): <NEW_LINE> <INDENT> return self._client.run_job('fba_tools.compare_models', [params], self._service_ver, context) | Compare models
:param params: instance of type "ModelComparisonParams"
(ModelComparisonParams object: a list of models and optional
pangenome and protein comparison; mc_name is the name for the new
object. @optional protcomp_ref pangenome_ref) -> structure:
parameter "workspace" of type "workspace_name" (A string
representing a workspace name.), parameter "mc_name" of String,
parameter "model_refs" of list of type "ws_fbamodel_id" (The
workspace ID for a FBAModel data object. @id ws
KBaseFBA.FBAModel), parameter "protcomp_ref" of type
"ws_proteomecomparison_id" (Reference to a Proteome Comparison
object in the workspace @id ws
GenomeComparison.ProteomeComparison), parameter "pangenome_ref" of
type "ws_pangenome_id" (Reference to a Pangenome object in the
workspace @id ws KBaseGenomes.Pangenome)
:returns: instance of type "ModelComparisonResult" -> structure:
parameter "report_name" of String, parameter "report_ref" of type
"ws_report_id" (The workspace ID for a Report object @id ws
KBaseReport.Report), parameter "mc_ref" of String | 625941c155399d3f05588634 |
def _ParseDLSPageHeader(self, file_object, page_offset): <NEW_LINE> <INDENT> page_header_map = self._GetDataTypeMap('dls_page_header') <NEW_LINE> try: <NEW_LINE> <INDENT> page_header, page_size = self._ReadStructureFromFileObject( file_object, page_offset, page_header_map) <NEW_LINE> <DEDENT> except (ValueError, errors.ParseError) as exception: <NEW_LINE> <INDENT> raise errors.ParseError( 'Unable to parse page header at offset: 0x{0:08x} ' 'with error: {1!s}'.format(page_offset, exception)) <NEW_LINE> <DEDENT> return page_header, page_size | Parses a DLS page header from a file-like object.
Args:
file_object (file): file-like object to read the header from.
page_offset (int): offset of the start of the page header, relative
to the start of the file.
Returns:
tuple: containing:
dls_page_header: parsed record structure.
int: header size.
Raises:
ParseError: when the header cannot be parsed. | 625941c132920d7e50b2814f |
def prefixesDivBy5(self, nums): <NEW_LINE> <INDENT> running_sum = 0 <NEW_LINE> for i, num in enumerate(nums): <NEW_LINE> <INDENT> running_sum <<= 1 <NEW_LINE> running_sum += num <NEW_LINE> nums[i] = running_sum % 5 == 0 <NEW_LINE> <DEDENT> return nums | :type nums: List[int]
:rtype: List[bool] | 625941c110dbd63aa1bd2b25 |
def readSettings(self): <NEW_LINE> <INDENT> colors = textformats.formatData('editor').baseColors <NEW_LINE> self._highlightMusicFormat.color = colors['musichighlight'] <NEW_LINE> color = colors['selectionbackground'] <NEW_LINE> color.setAlpha(128) <NEW_LINE> self._highlightFormat.setBackground(color) <NEW_LINE> if QSettings().value("musicview/document_properties", True, bool): <NEW_LINE> <INDENT> self.view.documentPropertyStore.mask = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.view.documentPropertyStore.mask = ('position') | Reads the settings from the user's preferences. | 625941c12ae34c7f2600d0b3 |
def calc_sr(y, sr): <NEW_LINE> <INDENT> return librosa.feature.spectral_rolloff(y=y, sr=sr) | Returns numpy.ndarray with sr from a
librosa audio time series and a sampling rate
Parameters:
y (numpy.ndarray): librosa audio time series
sr (int): sampling rate | 625941c1e64d504609d747c1 |
def write(self, workbook, response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> overtimeReports = response['reports']['overTime'] <NEW_LINE> (reportType, reportData) = overtimeReports.items()[0] <NEW_LINE> potentialPoints = reportData["potential"]["points"] <NEW_LINE> totalPoints = reportData["total"]["points"] <NEW_LINE> servedPoints = reportData["served"]["points"] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> loggers.mainLogger.error("response=%s" % response) <NEW_LINE> raise <NEW_LINE> <DEDENT> numPoints = len(totalPoints) <NEW_LINE> if numPoints > 0: <NEW_LINE> <INDENT> total = float(totalPoints[-1]["value"])/1e9 <NEW_LINE> if total == 0: <NEW_LINE> <INDENT> total = 1e-9 <NEW_LINE> <DEDENT> served = float(servedPoints[-1]["value"])/1e9 <NEW_LINE> potential = float(potentialPoints[-1]["value"])/1e9 <NEW_LINE> if self.endRow - self.startRow == 1: <NEW_LINE> <INDENT> workbook.setNumber(self.startRow, self.startCol+1, total) <NEW_LINE> workbook.setNumber(self.startRow, self.startCol+3, served) <NEW_LINE> if self.endCol > self.startCol+5: <NEW_LINE> <INDENT> workbook.setNumber(self.startRow, self.startCol+5, potential) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> workbook.setNumber(self.startRow+0, self.startCol+1, total) <NEW_LINE> workbook.setNumber(self.startRow+1, self.startCol+1, served) <NEW_LINE> workbook.setNumber(self.startRow+2, self.startCol+1, potential) | Writes response to workbook. Relevant sheet is selected | 625941c166656f66f7cbc12b |
@login_required <NEW_LINE> def file_list_view(request: WSGIRequest, path: str) -> HttpResponse: <NEW_LINE> <INDENT> path = normalize_path(path) <NEW_LINE> user = request.user <NEW_LINE> acc = StorageAccount.objects.filter(user=user) <NEW_LINE> num = '[' <NEW_LINE> cloudclass = '[' <NEW_LINE> for sub_acc in acc: <NEW_LINE> <INDENT> num = num + str(sub_acc.pk) + ',' <NEW_LINE> cloudclass = cloudclass + '"' + str(sub_acc.cloud.class_name) + '"' + ',' <NEW_LINE> <DEDENT> num = num[:-1] + ']' <NEW_LINE> cloudclass = cloudclass[:-1] + ']' <NEW_LINE> return render(request, 'home.html', {'user': user, 'acc': acc, 'path': path, 'num': num, 'cloudclass': cloudclass, 'tour': 'tour' in request.GET}) | Renders the file list HTML with navbar, upload buttons, list of storage accounts (with color legends), and empty
breadcrumb folder list and file list, which will be filled in by AJAX at client side.
:param request: the wsgi request object
:param path: the path of folder to display at beginning; later AJAX will load other folders
:return: a rendered HTML from home.html | 625941c1fb3f5b602dac3612 |
def node_tree_summary(node, indent=" ", prefix=""): <NEW_LINE> <INDENT> name = "{} in {}".format(type(node).__name__, type(node).__module__) <NEW_LINE> tree_string = prefix + name <NEW_LINE> child_trees = Counter() <NEW_LINE> for child in node.children(Node): <NEW_LINE> <INDENT> subtree_string = node_tree_summary(child, prefix=(prefix + indent)) <NEW_LINE> child_trees[subtree_string] += 1 <NEW_LINE> <DEDENT> for subtree_string, count in child_trees.most_common(): <NEW_LINE> <INDENT> indent_length = len(prefix + indent) <NEW_LINE> subtree_string = "{}[{}] {}".format( subtree_string[:indent_length], count, subtree_string[indent_length:] ) <NEW_LINE> tree_string += "\n" + subtree_string <NEW_LINE> <DEDENT> return tree_string | Get a summary of all the the node tree starting from the given node. | 625941c1cb5e8a47e48b7a2e |
def main( argv ): <NEW_LINE> <INDENT> a = read_annotations() <NEW_LINE> get_all_samples( a ) | do all | 625941c17cff6e4e81117907 |
def class_to_struct_dtype(cls, exclude_attrs, exclude_cls): <NEW_LINE> <INDENT> return np.dtype([ trait_to_dtype(name, trait) for name, trait in class_traits( cls, exclude_attrs=exclude_attrs, exclude_cls=exclude_cls )]) | Construct structured numpy.dtype from class with traits.
Args:
cls (type):
exclude_attrs (Callable[str, bool], optional):
Optional function to exclude class attribute names.
exclude_cls (Callable[type, bool], optional):
Optional function to exclude classes
Returns:
numpy.dtype: Numpy structured dtype for the class | 625941c1f7d966606f6a9f83 |
def createTree(self, dataSet, labels): <NEW_LINE> <INDENT> classList = [example[-1] for example in dataSet] <NEW_LINE> if classList.count(classList[0]) == len(classList): <NEW_LINE> <INDENT> return classList[0] <NEW_LINE> <DEDENT> if len(dataSet[0]) == 1: <NEW_LINE> <INDENT> return self.majorityCnt(dataSet) <NEW_LINE> <DEDENT> bestFeature = self.chooseBestFeatureToSplit(dataSet) <NEW_LINE> bestFeatureLabel = labels[bestFeature] <NEW_LINE> myTree = {bestFeatureLabel:{}} <NEW_LINE> del(labels[bestFeature]) <NEW_LINE> featureVals = [example[bestFeature] for example in dataSet] <NEW_LINE> uniqueVals = set(featureVals) <NEW_LINE> for value in uniqueVals: <NEW_LINE> <INDENT> subLabels = labels[:] <NEW_LINE> myTree[bestFeatureLabel][value] = self.createTree( self.splitDataSet(dataSet, bestFeature, value), subLabels) <NEW_LINE> <DEDENT> return myTree | 输入:数据集,特征标签
输出:决策树
描述:递归构建决策树,利用上述的函数 | 625941c1ec188e330fd5a724 |
def group_del_user(self): <NEW_LINE> <INDENT> self.parser.set_usage("group-del-user -g <group_id> -u <user>") <NEW_LINE> self._group_user_options() <NEW_LINE> self._parse() <NEW_LINE> self._group_user_parse() <NEW_LINE> self.vault.group_del_user(self.opts.group_id, self.opts.user) | Remove a user from a group | 625941c167a9b606de4a7e3c |
def from_tabber(self, tabber): <NEW_LINE> <INDENT> table = tabber[1][0] <NEW_LINE> stat_coords = { 'health': [0, 1], 'armor': [0, 3], 'reload': [0, 5], 'luck': [0, 7], 'firepower': [1, 1], 'torpedo': [1, 3], 'evasion': [1, 5], 'speed': [1, 7], 'anti_air': [2, 1], 'aviation': [2, 3], 'oil_consumption': [2, 5], 'accuracy': [2, 7], 'anti_submarine': [3, 1] } <NEW_LINE> stat_coords_alt = { 'health': [0, 1], 'armor': [0, 3], 'reload': [0, 5], 'firepower': [1, 1], 'torpedo': [1, 3], 'evasion': [1, 5], 'anti_air': [2, 1], 'aviation': [2, 3], 'oil_consumption': [2, 5], 'luck': [3, 1], 'speed': [3, 3], 'accuracy': [3, 5], 'anti_submarine': [4, 1] } <NEW_LINE> for stat_coord_key in stat_coords: <NEW_LINE> <INDENT> stat_coord_row, stat_coord_col = stat_coords.get(stat_coord_key) <NEW_LINE> try: <NEW_LINE> <INDENT> stat_val = table[stat_coord_row][stat_coord_col].text <NEW_LINE> stat_val = 0 if not stat_val else stat_val.strip() <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> stat_coord_row, stat_coord_col = stat_coords_alt.get(stat_coord_key) <NEW_LINE> stat_val = table[stat_coord_row][stat_coord_col].text <NEW_LINE> stat_val = 0 if not stat_val else stat_val.strip() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> stat_val = int(stat_val.strip()) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> setattr(self, stat_coord_key, stat_val) | Parses a single tabber instance to get stats from.
:type tabber: lxml.html.HtmlElement | 625941c17d847024c06be23b |
def is_confirmed(request): <NEW_LINE> <INDENT> return request.params.get('confirmed') == "1" | Returns True id the request is confirmed | 625941c150485f2cf553cd1a |
def performUndoOperation(self): <NEW_LINE> <INDENT> operation = InsertTabOperation(self.cursor, self.textStore, self.settings) <NEW_LINE> operation.perform() | Undo the remove tab action | 625941c16fece00bbac2d6be |
def signedFileCheck(self, filename: str) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> signature_filename = TrustBasics.getSignaturePathForFile(filename) <NEW_LINE> with open(signature_filename, "r", encoding = "utf-8") as data_file: <NEW_LINE> <INDENT> json_data = json.load(data_file) <NEW_LINE> signature = json_data.get(TrustBasics.getRootSignatureEntry(), None) <NEW_LINE> if signature is None: <NEW_LINE> <INDENT> self._violation_handler("Can't parse signature file '{0}'.".format(signature_filename)) <NEW_LINE> return False <NEW_LINE> <DEDENT> if not self._verifyFile(filename, signature): <NEW_LINE> <INDENT> self._violation_handler("File '{0}' didn't match with checksum.".format(filename)) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> Logger.log("i", "Verified unbundled file '{0}'.".format(filename)) <NEW_LINE> return True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self._violation_handler(f"Exception during verification of unbundled file '{filename}'.") <NEW_LINE> <DEDENT> return False | In the 'single signed file' case, check whether a file is signed according to the Trust-objects' public key.
:param filename: The path to the file to be checked (not the signature-file).
:return: True if the file is signed (is next to a signature file) and signed correctly. | 625941c160cbc95b062c64c4 |
def shutdown(delay=0.): <NEW_LINE> <INDENT> threading.Thread(target=do_shutdown, args=(delay,)).start() | Shutdown the system after a specified delay. Return immediately. | 625941c1a8ecb033257d304f |
def euclidean_distance_change(position): <NEW_LINE> <INDENT> distance = np.linalg.norm(position[1:] - position[:-1], axis=1) <NEW_LINE> return np.concatenate(([np.nan], distance)) | Distance between position at successive time points
Parameters
----------
position : ndarray, shape (n_time, n_space)
Returns
-------
distance : ndarray, shape (n_time,) | 625941c14e4d5625662d435c |
def _get_blog_obj(id: str) -> Blog: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> blog = Blog.objects.get(pk=id) <NEW_LINE> <DEDENT> except (DoesNotExist, ValidationError) as error: <NEW_LINE> <INDENT> return None, error <NEW_LINE> <DEDENT> return blog, None | function to get a particular blog object or
return error if it doesn't exist.
:param id: id of a blog.
:return: blog object or doesn't exist error. | 625941c1097d151d1a222ddd |
def __init__(self, metainfo=None, impl=None): <NEW_LINE> <INDENT> if impl: <NEW_LINE> <INDENT> self.__metainfomap = impl <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__metainfomap = invoke(lib.serialboxMetainfoCreate) <NEW_LINE> <DEDENT> if metainfo: <NEW_LINE> <INDENT> for key, value in metainfo.items(): <NEW_LINE> <INDENT> self.insert(key, value) | Initialize the Metainfo map.
If `metainfo` is None, an empty map is created. Elements can be added later with
:func:`MetainfoMap.insert <serialbox.MetainfoMap.insert>`.
:param metainfo: Key-value pair dictionary used for initialization
:type metainfo: dict
:param impl: Directly set the implementation pointer [internal use] | 625941c156b00c62f0f145d9 |
def mag_inclination(RAW_IMU, ATTITUDE, declination=None): <NEW_LINE> <INDENT> if declination is None: <NEW_LINE> <INDENT> from . import mavutil <NEW_LINE> declination = degrees(mavutil.mavfile_global.param('COMPASS_DEC', 0)) <NEW_LINE> <DEDENT> r = rotation(ATTITUDE) <NEW_LINE> mag1 = Vector3(RAW_IMU.xmag, RAW_IMU.ymag, RAW_IMU.zmag) <NEW_LINE> mag1 = r * mag1 <NEW_LINE> mag2 = Vector3(cos(radians(declination)), sin(radians(declination)), 0) <NEW_LINE> inclination = degrees(mag1.angle(mag2)) <NEW_LINE> if RAW_IMU.zmag < 0: <NEW_LINE> <INDENT> inclination = -inclination <NEW_LINE> <DEDENT> return inclination | give the magnitude of the discrepancy between observed and expected magnetic field | 625941c156b00c62f0f145da |
def _write_version(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> update_version = self.etcd.write('cobalt/version', self.VERSION, prevExists=False) <NEW_LINE> return update_version.value <NEW_LINE> <DEDENT> except etcd.EtcdException: <NEW_LINE> <INDENT> return False | Utility method to write current version upstream.
Returns:
bool: If the write operation was successful or not | 625941c1e76e3b2f99f3a791 |
def test_read_one_point(self): <NEW_LINE> <INDENT> result = read_bands_at( '16FEB12162517-M1BS-_RB_Rrs.tiff', [[25.932147, -81.735270]], longformat=False ) <NEW_LINE> print(result) <NEW_LINE> np.testing.assert_almost_equal( result, [[ 0.083664, 0.160671, 0.209449, 0.186279, 0.170908, 0.086403, 0.045154, 0.017258 ]], decimal=5 ) | Read one point from middle of the image | 625941c1236d856c2ad44759 |
def __repr__(self): <NEW_LINE> <INDENT> params = { 'class': self.__class__.__name__, 'name': self.name, 'inmod': self.inmod.name, 'outmod': self.outmod.name } <NEW_LINE> return "<%(class)s '%(name)s': '%(inmod)s' -> '%(outmod)s'>" % params | A simple representation (this should probably be expanded by
subclasses). | 625941c163b5f9789fde7067 |
def test_service_protocol(self): <NEW_LINE> <INDENT> class IFoo(Interface): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class IBar(Interface): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @provides(IFoo, IBar) <NEW_LINE> class Foo(HasTraits): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class PluginA(Plugin): <NEW_LINE> <INDENT> id = 'A' <NEW_LINE> foo = Instance(Foo, (), service=True, service_protocol=IBar) <NEW_LINE> <DEDENT> a = PluginA() <NEW_LINE> application = TestApplication(plugins=[a]) <NEW_LINE> application.start() <NEW_LINE> self.assertNotEqual(None, application.get_service(IBar)) <NEW_LINE> self.assertEqual(a.foo, application.get_service(IBar)) <NEW_LINE> application.stop() <NEW_LINE> self.assertEqual(None, application.get_service(IBar)) <NEW_LINE> return | service protocol | 625941c121a7993f00bc7c6e |
def next_id(self, tx): <NEW_LINE> <INDENT> return "TODO isotammi_id value" | Gives next isotammi_id value from reserved pool.
Returns None, if pool is empty.
- Or fethes next key from db? | 625941c1009cb60464c63335 |
def create(T, H, BCv, BCh, Nv, Nh): <NEW_LINE> <INDENT> return State(T, H, BCv, BCh, Nv, Nh) | Creates the elementary tensors for an Ising PEPS with periodic boundary
conditions in one direction and open boundary conditions in the orthogonal
direction.
Parameters
----------
T : double
The temperature of the system in units of the coupling strength.
H : double
The external field in units of the coupling strength.
BCv : int
The boundary conditions for the vertical direction. Use the values
from tnslib.peps2d.square.BC.
BCh : int
The boundary conditions for the horizontal direction. Use the values
from tnslib.peps2d.square.BC.
Nv : int
The number of lattice sites in the vertical direction.
If an infinte lattice is chosen via the BCs, tihs parameter is
ignored.
Nh : int
The number of lattice sites in the horizontal direction.
If an infinte lattice is chosen via the BCs, tihs parameter is
ignored.
Returns
-------
tns : tnslib.peps2d.square.ising.State
The tensor network state. | 625941c1167d2b6e31218b18 |
def getBaseId(self): <NEW_LINE> <INDENT> return CmisId(self._getElementValue(CMIS_NS, 'baseId')) | Getter for cmis:baseId | 625941c13cc13d1c6d3c72fd |
def create(self): <NEW_LINE> <INDENT> tt = TaskType.objects.create(**self.params) <NEW_LINE> for qual in self.quals: <NEW_LINE> <INDENT> tt.qualifications.add(qual) <NEW_LINE> <DEDENT> self.existing.extend( create_keyword_tags(self.newTags) ) <NEW_LINE> for tag in self.existing: <NEW_LINE> <INDENT> tt.keywords.add(tag) <NEW_LINE> <DEDENT> tt.save() <NEW_LINE> return(tt) | Create a new TaskType object (HIT Type). This is invoked after
our other attempts to find an existing task type fail. | 625941c16aa9bd52df036d24 |
def softNormals(): <NEW_LINE> <INDENT> selection = cmds.ls(sl=True, l=True) <NEW_LINE> if selection: <NEW_LINE> <INDENT> objects = list(set(cmds.ls(selection, o=True, l=True) or [])) <NEW_LINE> for obj in objects: <NEW_LINE> <INDENT> edges = [e for e in selection if cmds.ls(e, o=True, l=True)[0] == obj] <NEW_LINE> cmds.polySoftEdge(edges, a=180) | Sets all selected edges to soft | 625941c1ec188e330fd5a725 |
def _find_common_prefix_length ( self ): <NEW_LINE> <INDENT> files = [ abspath( file ) for file in self.files ] <NEW_LINE> if len( files ) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> prefix = join( dirname( files[0] ), '' ) <NEW_LINE> while True: <NEW_LINE> <INDENT> n = len( prefix ) <NEW_LINE> for file in files: <NEW_LINE> <INDENT> if prefix != file[:n]: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> new_prefix = join( dirname( dirname( prefix ) ), '' ) <NEW_LINE> if new_prefix == prefix: <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> prefix = new_prefix | Returns the length of the longest common file prefix shared by all
input files. | 625941c1e5267d203edcdc21 |
def sharedmem_unpack(self): <NEW_LINE> <INDENT> if self._mpshared: <NEW_LINE> <INDENT> self.wave = np.array(self.wave) <NEW_LINE> self.flux = np.array(self.flux) <NEW_LINE> self.ivar = np.array(self.ivar) <NEW_LINE> self.R = scipy.sparse.dia_matrix((np.array(self.R_data), np.array(self.R_offsets)), shape=(self._splen, self._splen)) <NEW_LINE> del self.R_data <NEW_LINE> del self.R_offsets <NEW_LINE> self.Rcsr = scipy.sparse.csr_matrix((np.array(self.Rcsr_data), np.array(self.Rcsr_indices), np.array(self.Rcsr_indptr)), shape=self._csrshape) <NEW_LINE> del self.Rcsr_data <NEW_LINE> del self.Rcsr_indices <NEW_LINE> del self.Rcsr_indptr <NEW_LINE> self._mpshared = False <NEW_LINE> <DEDENT> return | Unpack spectral data from multiprocessing shared memory.
| 625941c121bff66bcd6848d6 |
def test_is_equal(self): <NEW_LINE> <INDENT> self.assertEqual(self.instance1, self.instance2) | Test if both instance are equal | 625941c1bde94217f3682d75 |
def setEncoderPoseInterpNumReadings(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArRobot_setEncoderPoseInterpNumReadings(self, *args) | setEncoderPoseInterpNumReadings(self, size_t numReadings) | 625941c18a349b6b435e80f5 |
def sceneMatrix(self): <NEW_LINE> <INDENT> return QMatrix | QGraphicsItem.sceneMatrix() -> QMatrix | 625941c15f7d997b87174a17 |
def create_export_by_filter_mutation( entity_name: str, *, with_details: bool = None, entities_name: str = None, **kwargs, ): <NEW_LINE> <INDENT> class ExportByFilter(graphene.Mutation, AbstractExportByFilter): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> @require_authentication <NEW_LINE> def mutate(_root, info, filter_string: str = None): <NEW_LINE> <INDENT> gmp = get_gmp(info) <NEW_LINE> get_entities = ( getattr(gmp, f'get_{entities_name}') if entities_name else getattr(gmp, f'get_{entity_name}s') ) <NEW_LINE> if with_details: <NEW_LINE> <INDENT> xml: XmlElement = get_entities( filter_string=filter_string, details=True, **kwargs ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xml: XmlElement = get_entities( filter_string=filter_string, **kwargs ) <NEW_LINE> <DEDENT> serialized_xml = etree.tostring(xml, encoding='unicode') <NEW_LINE> return AbstractExportByFilter(exported_entities=serialized_xml) <NEW_LINE> <DEDENT> <DEDENT> return ExportByFilter | Args:
entity_name (str): Type of the entity in singular. E.g. 'config'
with_details (bool, optional): Should entities be returned with details
entities_name (str, optional): Plural for irregular words
ultimate (bool, optional): Whether to remove entirely, or to the
trashcan. | 625941c1baa26c4b54cb10a4 |
def getStatistics(): <NEW_LINE> <INDENT> pass | Reports on the contents of a cache.
The returned value is a sequence of dictionaries with the
following keys:
`path`, `hits`, `misses`, `size`, `entries` | 625941c17c178a314d6ef3de |
def fce_formatter(sentence): <NEW_LINE> <INDENT> formatted_sentence = [] <NEW_LINE> for token in sentence: <NEW_LINE> <INDENT> token = token.lower() <NEW_LINE> token = re.sub(r'\d', '0', token) <NEW_LINE> formatted_sentence.append(token) <NEW_LINE> <DEDENT> return formatted_sentence | Format sentence
:param sentence: List of tokens
:return: List of tokens, each of which is lowercased, with digits replaced with 0 | 625941c1f7d966606f6a9f84 |
def load_settings_from_file(_file): <NEW_LINE> <INDENT> data = {} <NEW_LINE> converted = {} <NEW_LINE> with open(_file, "r") as file: <NEW_LINE> <INDENT> data = json.loads(file.read()) <NEW_LINE> <DEDENT> objects = data["objects"] <NEW_LINE> actions = data["actions"] <NEW_LINE> for key in actions.keys(): <NEW_LINE> <INDENT> name = str(key) <NEW_LINE> device, event_type = str_to_event_type(actions[name]["type"]) <NEW_LINE> if name.isdigit(): <NEW_LINE> <INDENT> name = int(name) <NEW_LINE> <DEDENT> converted[name] = C.Action(device, [event_type] + actions[key]["data"]) <NEW_LINE> <DEDENT> return converted, objects | Convert a saved dict to a ready to use dict.
Settings structure:
{
"objects": {
BUTTON_NAME: id,
DIRECTIONAL_NAME: {
"x": id,
"y": id
}
},
"actions": {
EVENT_NAME: {
"type": EVENT_TYPE,
"data": DATA
},
EVENT_NAME: {
"type": EVENT_TYPE,
"data": DATA
},
EVENT_NAME: {
"type": EVENT_TYPE,
"data": DATA
}
}
}
EVENT_TYPE structure:
DEVICE_TYPE:EVENT
DATA structure:
[
ACTION_TYPE,
VALUE,
VALUE,
VALUE
] | 625941c126238365f5f0eded |
def update(self,vector): <NEW_LINE> <INDENT> self.update_times_called+=1 <NEW_LINE> nelements=len(vector) <NEW_LINE> self.nvec = nelements <NEW_LINE> if self.data: <NEW_LINE> <INDENT> ncols=len(self.data[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ncols=0 <NEW_LINE> <DEDENT> self.ncols = ncols <NEW_LINE> if nelements<ncols: <NEW_LINE> <INDENT> for i in range(ncols-nelements): <NEW_LINE> <INDENT> vector.append(None) <NEW_LINE> <DEDENT> <DEDENT> if nelements>ncols: <NEW_LINE> <INDENT> for item in self.data: <NEW_LINE> <INDENT> for i in range(nelements-ncols): <NEW_LINE> <INDENT> item.append(None) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.data.append(vector) <NEW_LINE> if nelements == 0: <NEW_LINE> <INDENT> self.ConsecutiveCheck = [] <NEW_LINE> for i in range(ncols): <NEW_LINE> <INDENT> self.ConsecutiveCheck.append(0) <NEW_LINE> <DEDENT> <DEDENT> elif nelements<ncols: <NEW_LINE> <INDENT> for i in range(ncols): <NEW_LINE> <INDENT> self.ConsecutiveCheck[i] += 1 <NEW_LINE> <DEDENT> for i in range(1,ncols-nelements+1): <NEW_LINE> <INDENT> self.ConsecutiveCheck[-i]=0 <NEW_LINE> <DEDENT> <DEDENT> elif nelements>ncols: <NEW_LINE> <INDENT> for i in range(ncols): <NEW_LINE> <INDENT> self.ConsecutiveCheck[i] += 1 <NEW_LINE> <DEDENT> for i in range(nelements-ncols): <NEW_LINE> <INDENT> self.ConsecutiveCheck.append(1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(nelements): <NEW_LINE> <INDENT> self.ConsecutiveCheck[i] += 1 | This update method should NOT return anything
but keeps track of data, a 2D array.
vector MUST be a list.
with rows = #ROIs
with cols = #timepoints
It puts the values from vector into this data, so that later on
when you call data, you can do all kinds of neat-o operations on it.
UPDATE... it seems to be quite incredibly robust. vector can be a
list of ANYTHING!!! | 625941c163d6d428bbe44471 |
def get_path(node): <NEW_LINE> <INDENT> path = [node] <NEW_LINE> while path[0].parent: <NEW_LINE> <INDENT> path = [path[0].parent] + path <NEW_LINE> <DEDENT> return [x.state for x in path] | returns the path that ends in this node according to the parent pointers. | 625941c1fb3f5b602dac3613 |
def getReplicasForJobs(self, lfns, allStatus=False, getUrl=True, diskOnly=False): <NEW_LINE> <INDENT> result = self.getReplicas(lfns, allStatus=allStatus, getUrl=getUrl) <NEW_LINE> if not result["OK"]: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> replicaDict = result["Value"] <NEW_LINE> self.__filterActiveReplicas(replicaDict) <NEW_LINE> self.__filterTapeReplicas(replicaDict, diskOnly=diskOnly) <NEW_LINE> self.__filterReplicasForJobs(replicaDict) <NEW_LINE> return S_OK(replicaDict) | get replicas useful for jobs | 625941c1498bea3a759b9a32 |
def make_span(text: str, color: Optional[str] = None) -> str: <NEW_LINE> <INDENT> if color is None: <NEW_LINE> <INDENT> return f'<span>{text}</span>' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f'<span style="color: {color}">{text}</span>' | make a HTML span with the input text and optionally a css color
**example**:
>>> make_span("Hello there", "green")
'<span style="color: green">'Hello There</span>'
:param text: text of the span element
:type text: a plaintext string
:param color: the color to make the span, or None for black
:type color: Optional[int]
:rtype: str
:returns: The HTML for a span with `text` as input and `color` as the color | 625941c1004d5f362079a2b7 |
def tee(_string, fileobj=None): <NEW_LINE> <INDENT> sys.stdout.write(_string) <NEW_LINE> if fileobj: <NEW_LINE> <INDENT> fileobj.write(_string) | Print both on stdout and in the file. | 625941c191af0d3eaac9b999 |
def calculatePreferedActions(self, location, allowed_actions): <NEW_LINE> <INDENT> prefered_actions = [] <NEW_LINE> x, y = location <NEW_LINE> for action in allowed_actions: <NEW_LINE> <INDENT> direction = action[0] <NEW_LINE> move = action[1] <NEW_LINE> delta = self.dir_move[direction] <NEW_LINE> new_x = x + move * delta[0] <NEW_LINE> new_y = y + move * delta[1] <NEW_LINE> if not self.visitedGrid[new_x][new_y]: <NEW_LINE> <INDENT> prefered_actions.append(action) <NEW_LINE> <DEDENT> <DEDENT> return prefered_actions | This funtion will be passed currect robot's location and all the
allowed actions for the robot in the next step.
This function will calculate, among these actions, which are prefered
actions. A prefered action is the action that will send the robot to a
cell it hasn't visited before.
In other words, this function is a filtering process to keep the
actions that will send the robot to unvisited cells. | 625941c15fc7496912cc3900 |
def test_parse_dois_from_pds4_label(self): <NEW_LINE> <INDENT> pds4_label_util = DOIPDS4LabelUtil() <NEW_LINE> i_filepath = join(self.input_dir, "pds4_bundle_with_doi_and_contributors.xml") <NEW_LINE> with open(i_filepath, "r") as infile: <NEW_LINE> <INDENT> xml_contents = infile.read().encode().decode("utf-8-sig") <NEW_LINE> xml_tree = etree.fromstring(xml_contents.encode()) <NEW_LINE> <DEDENT> self.assertTrue(pds4_label_util.is_pds4_label(xml_tree)) <NEW_LINE> doi = pds4_label_util.get_doi_fields_from_pds4(xml_tree) <NEW_LINE> self.assertIsInstance(doi, Doi) <NEW_LINE> self.assertIsInstance(doi.status, DoiStatus) <NEW_LINE> self.assertEqual(doi.status, DoiStatus.Unknown) <NEW_LINE> self.assertEqual(doi.pds_identifier, "urn:nasa:pds:insight_cameras::1.0") <NEW_LINE> self.assertEqual(doi.doi, "10.17189/29569") <NEW_LINE> self.assertEqual(doi.title, "InSight Cameras Bundle") <NEW_LINE> self.assertEqual( doi.site_url, "https://pds.nasa.gov/ds-view/pds/viewBundle.jsp?identifier=urn%3Anasa%3Apds%3Ainsight_cameras&version=1.0", ) <NEW_LINE> self.assertIsInstance(doi.publication_date, datetime) <NEW_LINE> self.assertEqual(doi.publication_date, datetime.strptime("2020-01-01", "%Y-%m-%d")) <NEW_LINE> self.assertIsInstance(doi.product_type, ProductType) <NEW_LINE> self.assertEqual(doi.product_type, ProductType.Bundle) <NEW_LINE> self.assertEqual(doi.product_type_specific, "PDS4 Refereed Data Bundle") <NEW_LINE> self.assertListEqual(doi.authors, self.expected_authors) <NEW_LINE> self.assertListEqual(doi.editors, self.expected_editors) <NEW_LINE> self.assertSetEqual(doi.keywords, self.expected_keywords) | Test the DOIPDS4LabelUtil.get_doi_fields_from_pds4() method | 625941c10a366e3fb873e79a |
def gen(): <NEW_LINE> <INDENT> for i in range(0, 4): <NEW_LINE> <INDENT> block_in = numpy.vstack([ numpy.arange(-i * 2 * 3, -(i + 1) * 2 * 3, -2), numpy.arange(i * 2 * 3, (i + 1) * 2 * 3, 2) ]).transpose() <NEW_LINE> yield block_in | [[0, 0], [-2, 2], [-4, 4]] [[-6, 6], [-8, 8], [-10, 10]] ... | 625941c129b78933be1e5631 |
def _prepare_ego_vehicles(self, ego_vehicles, wait_for_ego_vehicles=False): <NEW_LINE> <INDENT> if not wait_for_ego_vehicles: <NEW_LINE> <INDENT> for vehicle in ego_vehicles: <NEW_LINE> <INDENT> self.ego_vehicles.append(CarlaActorPool.setup_actor(vehicle.model, vehicle.transform, vehicle.rolename, True)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ego_vehicle_missing = True <NEW_LINE> while ego_vehicle_missing: <NEW_LINE> <INDENT> self.ego_vehicles = [] <NEW_LINE> ego_vehicle_missing = False <NEW_LINE> for ego_vehicle in ego_vehicles: <NEW_LINE> <INDENT> ego_vehicle_found = False <NEW_LINE> carla_vehicles = CarlaDataProvider.get_world().get_actors().filter('vehicle.*') <NEW_LINE> for carla_vehicle in carla_vehicles: <NEW_LINE> <INDENT> if carla_vehicle.attributes['role_name'] == ego_vehicle.rolename: <NEW_LINE> <INDENT> ego_vehicle_found = True <NEW_LINE> self.ego_vehicles.append(carla_vehicle) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not ego_vehicle_found: <NEW_LINE> <INDENT> ego_vehicle_missing = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for i, _ in enumerate(self.ego_vehicles): <NEW_LINE> <INDENT> self.ego_vehicles[i].set_transform(ego_vehicles[i].transform) <NEW_LINE> <DEDENT> <DEDENT> CarlaDataProvider.get_world().tick() | Spawn or update the ego vehicles | 625941c1377c676e9127212b |
def test_transform_vector(self, v): <NEW_LINE> <INDENT> tmp2 = 0.5*v <NEW_LINE> for i in range(len(self.transform_vecs)): <NEW_LINE> <INDENT> dot = abs(tmp2.dot(self.transform_vecs[i]))/(self.transform_vecs[i].dot(self.transform_vecs[i])) <NEW_LINE> if dot > 1-self.halfTol: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> self.transform_vecs=np.append(self.transform_vecs , [v], axis=0) | Test transform vectors.
Parameters
-----------
v : numpy.ndarray
A lattice vector to be tested (Å) | 625941c13617ad0b5ed67e7b |
def _is_shebang(s): <NEW_LINE> <INDENT> return s.startswith("#!/") and "python" in s | Checks if the string potentially is a Python shebang. | 625941c1c432627299f04bc7 |
def get_objects(self, queryset=None): <NEW_LINE> <INDENT> if queryset is None: <NEW_LINE> <INDENT> queryset = self.get_queryset() <NEW_LINE> <DEDENT> return queryset.all() | Returns the objects the view is rendering.
By default this requires ``self.queryset``, but subclasses can
overwrite this to return any list of objects. | 625941c107f4c71912b11403 |
def convert_rankine_to_celcius(temp): <NEW_LINE> <INDENT> return ((temp - 491.67) * 5) / 9 | Convert the temperature from Rankine to Celcius scale.
:param float temp: The temperature in degrees Rankine.
:returns: The temperature in degrees Celcius.
:rtype: float | 625941c155399d3f05588635 |
def write(self, data): <NEW_LINE> <INDENT> _LOGGER.debug("..................Writing a message..............") <NEW_LINE> hex_data = binascii.hexlify(data).decode() <NEW_LINE> url = "http://{:s}:{:d}/3?{:s}=I=3".format(self._host, self._port, hex_data) <NEW_LINE> asyncio.ensure_future(self._async_write(url), loop=self._loop) | Write to modem. | 625941c13346ee7daa2b2ced |
def write_graph(self): <NEW_LINE> <INDENT> if self._checkpoint_dir is not None and self._is_chief: <NEW_LINE> <INDENT> summary_writer = summary_writer_cache.SummaryWriterCache.get( self._checkpoint_dir) <NEW_LINE> training_util.write_graph(self._graph.as_graph_def(add_shapes=True), self._checkpoint_dir, 'graph.pbtxt') <NEW_LINE> summary_writer.add_graph(self._graph) <NEW_LINE> summary_writer.add_session_log(SessionLog(status=SessionLog.START), self._init_step) | Saves current graph. | 625941c1187af65679ca50a0 |
def validate_arguments_against_signature(func, args, kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> signature(func).bind(*(args or []), **(kwargs or {})) <NEW_LINE> <DEDENT> except TypeError as exc: <NEW_LINE> <INDENT> raise InvalidParams(str(exc)) | Check if the request's arguments match a function's signature.
Raises InvalidParams exception if arguments cannot be passed to a
function.
:param func: The function to check.
:param args: Positional arguments.
:param kwargs: Keyword arguments.
:raises InvalidParams: If the arguments cannot be passed to the function. | 625941c150485f2cf553cd1b |
@db_commit <NEW_LINE> def voice_order_handler(orders): <NEW_LINE> <INDENT> order_groups = defaultdict(list) <NEW_LINE> for order in orders: <NEW_LINE> <INDENT> order_groups[order.restaurant_id].append(order) <NEW_LINE> <DEDENT> for restaurant_id, orders in order_groups.items(): <NEW_LINE> <INDENT> orders = _validate_order(orders) <NEW_LINE> if not orders: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> with thrift_client('ers') as ers: <NEW_LINE> <INDENT> restaurant = ers.get(restaurant_id) <NEW_LINE> <DEDENT> restaurant_phone = get_rst_takeout_phone(restaurant) <NEW_LINE> if not restaurant_phone: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> voice_call = VoiceCall.add(restaurant_id=restaurant_id, call_status=VoiceCall.STATUS_NOT_DIAL, created_at=datetime.now(), phone=restaurant_phone, flush=True) <NEW_LINE> for order in orders: <NEW_LINE> <INDENT> VoiceOrder.add(order_id=order.id, status_code=order.status_code, sequence_number=order.restaurant_number, created_at=datetime.fromtimestamp(order.created_at), call_id=voice_call.id) <NEW_LINE> <DEDENT> log.info('voice order received with restaurant_id [{}], call_id [{}]'. format(restaurant_id, voice_call.id)) | save voice-call and voice-order | 625941c1187af65679ca50a1 |
def __init__(self, img, cell_size=8, bin_size=9): <NEW_LINE> <INDENT> self.img = img <NEW_LINE> self.img = np.sqrt(img*1.0 / float(np.max(img))) <NEW_LINE> self.img = self.img * 255 <NEW_LINE> self.cell_size = cell_size <NEW_LINE> self.bin_size = bin_size <NEW_LINE> self.angle_unit = 180 / self.bin_size <NEW_LINE> assert type(self.bin_size) == int, "bin_size should be integer," <NEW_LINE> assert type(self.cell_size) == int, "cell_size should be integer," <NEW_LINE> assert 180 % self.bin_size == 0, "bin_size should be divisible by 180" | 构造函数
默认参数,一个block由2x2个cell组成,步长为1个cell大小
args:
img:输入图像(更准确的说是检测窗口),这里要求为灰度图像 对于行人检测图像大小一般为128x64 即是输入图像上的一小块裁切区域
cell_size:细胞单元的大小 如8,表示8x8个像素
bin_size:直方图的bin个数 | 625941c17b25080760e393dc |
def get_move(self, game, time_left): <NEW_LINE> <INDENT> self.time_left = time_left <NEW_LINE> best_move = (-1, -1) <NEW_LINE> try: <NEW_LINE> <INDENT> for depth in itertools.count(): <NEW_LINE> <INDENT> best_move = self.alphabeta(game, depth) <NEW_LINE> <DEDENT> <DEDENT> except SearchTimeout as instance: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return best_move | Search for the best move from the available legal moves and return a
result before the time limit expires.
**********************************************************************
NOTE: If time_left < 0 when this function returns, the agent will
forfeit the game due to timeout. You must return _before_ the
timer reaches 0.
**********************************************************************
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
-------
(int, int)
Board coordinates corresponding to a legal move; may return
(-1, -1) if there are no available legal moves. | 625941c1a8ecb033257d3050 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.