code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def required_nova_scheduler_filters(): <NEW_LINE> <INDENT> pdf = settings.getValue('pdf_file') <NEW_LINE> filters = pdf['vim_functional']['scheduler_filters'] <NEW_LINE> filters = filters.split(',') <NEW_LINE> map(str.strip, filters) <NEW_LINE> return filters | Required nova scheduler_filters by the PDF | 625941c007f4c71912b113d3 |
def get_summed_scores(df,col): <NEW_LINE> <INDENT> sum_array=[] <NEW_LINE> sums_only=[] <NEW_LINE> for c in col: <NEW_LINE> <INDENT> sum=abs(np.sum(df[df[c]==1]['score'].values)) <NEW_LINE> sum_array.append((c,sum)) <NEW_LINE> sums_only.append(sum) <NEW_LINE> <DEDENT> raw_sum_dict=dict(tuple(sum_array)) <NEW_LINE> normalizer=np.sum(np.array(sums_only)) <NEW_LINE> normalized_sum_dict={i[0]:i[1]/normalizer for i in raw_sum_dict.items()} <NEW_LINE> return raw_sum_dict,normalized_sum_dict | Inputs:
df--dataframe to get sum of scores from. (should be scaled)
col--list of column names
Outputs:
Dictionary containing the mappings of the column names, and the severance score values | 625941c06aa9bd52df036cf4 |
def __imul__(self, other): <NEW_LINE> <INDENT> if isinstance(other, (int, float, str)): <NEW_LINE> <INDENT> other = RationalFrac(other) <NEW_LINE> <DEDENT> if isinstance(other, RationalFrac): <NEW_LINE> <INDENT> self.numer.extend(other.numer) <NEW_LINE> self.denom.extend(other.denom) <NEW_LINE> self.neg = not(self.neg == other.neg) <NEW_LINE> self.simplify() <NEW_LINE> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented | Multiplies self by other(a constant) in-place. | 625941c063b5f9789fde7037 |
def vectorize(**base_kwargs): <NEW_LINE> <INDENT> class _vectorize_desc: <NEW_LINE> <INDENT> def __init__(self, func): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> self.__doc__ = func.__doc__ <NEW_LINE> self.__name__ = func.__name__ <NEW_LINE> self.__module__ = func.__module__ <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> arr = np.vectorize(self.func, **base_kwargs)(*args, **kwargs) <NEW_LINE> if not arr.shape: <NEW_LINE> <INDENT> arr = arr.item() <NEW_LINE> <DEDENT> return arr <NEW_LINE> <DEDENT> def __get__(self, obj, objtype=None): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> new_func = self.func.__get__(obj, objtype) <NEW_LINE> return self.__class__(new_func) <NEW_LINE> <DEDENT> <DEDENT> return _vectorize_desc | An improved vectorization decorator.
Unlike the :class:`np.vectorize` decorator this version works on methods in
addition to functions. It also gives an actual scalar value back for any
scalar input, instead of returning a 0-dimension array.
Parameters
----------
**kwargs
Any keyword arguments accepted by :class:`np.vectorize`
Returns
-------
vectorized_function : func | 625941c04f88993c3716bfbc |
def __getattr__(self, attr): <NEW_LINE> <INDENT> if attr.startswith('__'): <NEW_LINE> <INDENT> raise AttributeError(attr) <NEW_LINE> <DEDENT> ephem_body = _get_ephem_body(self.heavenly_body) <NEW_LINE> if attr in ['rise', 'set', 'transit']: <NEW_LINE> <INDENT> attr = fn_map[attr] <NEW_LINE> observer = self._get_observer(self.sod_djd) <NEW_LINE> try: <NEW_LINE> <INDENT> if attr in ['next_rising', 'next_setting']: <NEW_LINE> <INDENT> time_djd = getattr(observer, attr)(ephem_body, use_center=self.use_center) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time_djd = getattr(observer, attr)(ephem_body) <NEW_LINE> <DEDENT> <DEDENT> except (ephem.AlwaysUpError, ephem.NeverUpError): <NEW_LINE> <INDENT> time_djd = None <NEW_LINE> <DEDENT> return weewx.units.ValueHelper((time_djd, "dublin_jd", "group_time"), context="ephem_day", formatter=self.formatter) <NEW_LINE> <DEDENT> elif attr in ['next_rising', 'next_setting', 'next_transit', 'next_antitransit', 'previous_rising', 'previous_setting', 'previous_transit', 'previous_antitransit']: <NEW_LINE> <INDENT> observer = self._get_observer(self.time_djd) <NEW_LINE> try: <NEW_LINE> <INDENT> if attr in ['next_rising', 'next_setting', 'previous_rising', 'previous_setting']: <NEW_LINE> <INDENT> time_djd = getattr(observer, attr)(ephem_body, use_center=self.use_center) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time_djd = getattr(observer, attr)(ephem_body) <NEW_LINE> <DEDENT> <DEDENT> except (ephem.AlwaysUpError, ephem.NeverUpError): <NEW_LINE> <INDENT> time_djd = None <NEW_LINE> <DEDENT> return weewx.units.ValueHelper((time_djd, "dublin_jd", "group_time"), context="ephem_day", formatter=self.formatter) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> observer = self._get_observer(self.time_djd) <NEW_LINE> ephem_body.compute(observer) <NEW_LINE> if attr in ['az', 'alt', 'a_ra', 'a_dec', 'g_ra', 'ra', 'g_dec', 'dec', 'elong', 'radius', 'hlong', 'hlat', 'sublat', 'sublong']: <NEW_LINE> <INDENT> return math.degrees(getattr(ephem_body, attr)) <NEW_LINE> <DEDENT> elif attr=='moon_fullness': <NEW_LINE> <INDENT> return 100.0 * ephem_body.moon_phase <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return getattr(ephem_body, attr) | Get the requested observation, such as when the body will rise. | 625941c060cbc95b062c6495 |
def autodiscover(self, instance, created, url=None, label=None, user_to=None, user_from=None, read=False): <NEW_LINE> <INDENT> raise NotImplementedError | Automatically discover call from instance. Subclass must override this method. | 625941c08c3a87329515830a |
def assert_get_size( self, filename: str, path: Tuple[str, ...], size: int ) -> None: <NEW_LINE> <INDENT> assert self._get_size(FileItem(filename=filename, path=path)) == size | Assert that given file size is equal to the anticipated size. | 625941c050485f2cf553cceb |
def getSetJson(set_code): <NEW_LINE> <INDENT> address = createSetAddress(set_code) <NEW_LINE> json_stream = getGenericData(address, 'application/json') <NEW_LINE> json_stream = json_stream.decode('utf-8') <NEW_LINE> return json.loads(json_stream) | Downloads the JSON data for the given set and returns it as a dict | 625941c0bf627c535bc13120 |
def write(self): <NEW_LINE> <INDENT> log.info("Writing ...") | This function ...
:return: | 625941c0d164cc6175782ca0 |
def file_len(fname): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> with open(fname) as f: <NEW_LINE> <INDENT> for i, l in enumerate(f): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return i + 1 | Count the number of lines of fname. | 625941c02c8b7c6e89b35714 |
def setTransparency(self, tm): <NEW_LINE> <INDENT> if self._transparent == tm: return <NEW_LINE> self._transparent = tm <NEW_LINE> self.notice(False) <NEW_LINE> return | 半透明モード設定
- tm: 半透明モード | 625941c0462c4b4f79d1d622 |
def __getitem__(self, target): <NEW_LINE> <INDENT> if isinstance(target, tuple): <NEW_LINE> <INDENT> return self.attr_value(*target) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.attr_value(target) | Return the value of the given string attribute node, None if the node
doesn't exist. Can also take a tuple as a parameter, (target, child),
where child is the index of the attribute in the WKT. For example:
>>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]'
>>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
>>> print(srs['GEOGCS'])
WGS 84
>>> print(srs['DATUM'])
WGS_1984
>>> print(srs['AUTHORITY'])
EPSG
>>> print(srs['AUTHORITY', 1]) # The authority value
4326
>>> print(srs['TOWGS84', 4]) # the fourth value in this wkt
0
>>> # For the units authority, have to use the pipe symbole.
>>> print(srs['UNIT|AUTHORITY'])
EPSG
>>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units
9122 | 625941c07c178a314d6ef3ad |
def set_on_click(self, func): <NEW_LINE> <INDENT> self.on_click = func | Sets a function (Pass None if you want to disable it) that will be called when the user clicks in the viewport with the lmb. It will receive two parameters - the x and y (floating point) coordinates of where was clicked. All will be in the unscaled coordinate system. | 625941c071ff763f4b5495da |
def apply_position_component(self, wavepacket, component): <NEW_LINE> <INDENT> D = wavepacket.get_dimension() <NEW_LINE> eps = wavepacket.get_eps() <NEW_LINE> q, p, Q, P, _ = wavepacket.get_parameters(component=component) <NEW_LINE> _, PA = polar(Q, side='left') <NEW_LINE> EW, EV = eigh(real(PA)) <NEW_LINE> G = dot(inv(EV.T), diag(EW)) <NEW_LINE> coeffs = wavepacket.get_coefficients(component=component) <NEW_LINE> K = wavepacket.get_basis_shapes(component=component) <NEW_LINE> Ke = K.extend() <NEW_LINE> size = Ke.get_basis_size() <NEW_LINE> cnew = zeros((size, D), dtype=complexfloating) <NEW_LINE> for k in K.get_node_iterator(): <NEW_LINE> <INDENT> cnew[Ke[k], :] += squeeze(coeffs[K[k]] * q) <NEW_LINE> nbw = Ke.get_neighbours(k, selection="backward") <NEW_LINE> for d, nb in nbw: <NEW_LINE> <INDENT> cnew[Ke[nb], :] += sqrt(eps**2 / 2.0) * sqrt(k[d]) * coeffs[K[k]] * G[:, d] <NEW_LINE> <DEDENT> nfw = Ke.get_neighbours(k, selection="forward") <NEW_LINE> for d, nb in nfw: <NEW_LINE> <INDENT> cnew[Ke[nb], :] += sqrt(eps**2 / 2.0) * sqrt(k[d] + 1.0) * coeffs[K[k]] * G[:, d] <NEW_LINE> <DEDENT> <DEDENT> return (Ke, cnew) | Compute the effect of the position operator :math:`x` on the basis functions :math:`\psi(x)`
of a component :math:`\Phi_i` of the new-kind Hagedorn wavepacket :math:`\Psi`.
:param wavepacket: The wavepacket :math:`\Psi` containing :math:`\Phi_i`.
:type wavepacket: A :py:class:`HagedornWavepacketBase` subclass instance.
:param component: The index :math:`i` of the component :math:`\Phi_i`.
:type component: Integer.
:return: Extended basis shape :math:`\mathfrak{\dot{K}}` and new coefficients :math:`c^\prime`
for component :math:`\Phi_i`. The coefficients are stored column-wise with
one column per dimension :math:`d`. The :math:`c^\prime` array is of shape
:math:`|\mathfrak{\dot{K}}| \times D`. | 625941c099fddb7c1c9de2e4 |
@blueprint.route('/api/ip/<endpoint_id>') <NEW_LINE> @secure <NEW_LINE> def ips(endpoint_id): <NEW_LINE> <INDENT> with session_scope() as db_session: <NEW_LINE> <INDENT> ips_hits = get_ips(db_session, endpoint_id) <NEW_LINE> dicts = [] <NEW_LINE> for ih in ips_hits: <NEW_LINE> <INDENT> dicts.append({'ip': ih[0], 'hits': ih[1]}) <NEW_LINE> <DEDENT> return jsonify(dicts) | :param endpoint_id: integer
:return: A JSON-list with all IP-addresses of a specific endpoint (ip represented by a string) | 625941c0b545ff76a8913d68 |
def mean(self): <NEW_LINE> <INDENT> r = self.shape * (self.scale - self.location) <NEW_LINE> r = r + (((self.shape + 1) * self.location - self.scale) * self.k) <NEW_LINE> return r / (self.shape * self.k) | Gives the arithmetic mean of the sample. | 625941c0d58c6744b4257bb2 |
def run(self) -> None: <NEW_LINE> <INDENT> while self._running: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> future, function = self._tx.get(timeout=0.1) <NEW_LINE> <DEDENT> except Empty: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> LOG.debug("executing %s", function) <NEW_LINE> result = function() <NEW_LINE> LOG.debug("returning %s", result) <NEW_LINE> def set_result(fut, result): <NEW_LINE> <INDENT> if not fut.done(): <NEW_LINE> <INDENT> fut.set_result(result) <NEW_LINE> <DEDENT> <DEDENT> get_loop(future).call_soon_threadsafe(set_result, future, result) <NEW_LINE> <DEDENT> except BaseException as e: <NEW_LINE> <INDENT> LOG.info("returning exception %s", e) <NEW_LINE> def set_exception(fut, e): <NEW_LINE> <INDENT> if not fut.done(): <NEW_LINE> <INDENT> fut.set_exception(e) <NEW_LINE> <DEDENT> <DEDENT> get_loop(future).call_soon_threadsafe(set_exception, future, e) | Execute function calls on a separate thread.
:meta private: | 625941c0a17c0f6771cbdfa5 |
def update(self): <NEW_LINE> <INDENT> N = len(self.dft) <NEW_LINE> del self.lines[:] <NEW_LINE> current_loc = 0 <NEW_LINE> prev_p = c2p(current_loc) <NEW_LINE> current_loc += self.dft[0] <NEW_LINE> current_p = c2p(current_loc) <NEW_LINE> self.lines.append(DFT_Renderer.line_config(prev_p, current_p)) <NEW_LINE> for n in range(1, self.num_vec): <NEW_LINE> <INDENT> prev_p = current_p <NEW_LINE> current_loc += self.dft[n%N]*cmath.exp(n*self.theta*1j) <NEW_LINE> current_p = c2p(current_loc) <NEW_LINE> self.lines.append(DFT_Renderer.line_config(prev_p, current_p)) <NEW_LINE> prev_p = current_p <NEW_LINE> current_loc += self.dft[-n%N]*cmath.exp(-n*self.theta*1j) <NEW_LINE> current_p = c2p(current_loc) <NEW_LINE> self.lines.append(DFT_Renderer.line_config(prev_p, current_p)) <NEW_LINE> <DEDENT> self.loc_pos = current_loc <NEW_LINE> self.theta += self.dtheta | Updates all figures. | 625941c0f9cc0f698b140550 |
def get_jobs(job_id=None, job_state_file=None): <NEW_LINE> <INDENT> if job_id: <NEW_LINE> <INDENT> return _clean_job(_build_job(job_id, job_state_file)) <NEW_LINE> <DEDENT> return [_clean_job(_build_job(job_id)) for job_id in filter(lambda x: not x.startswith('.'), os.listdir(_job_state_dir))] | Return list of tracked jobs or single job.
Kwargs:
job_id (int/None): If int, return jobs resource with corresponding id.
If None, return list of all tracked job resources.
Returns:
OnRamp formatted dict containing job attrs for each job requested. | 625941c0cad5886f8bd26f2c |
def get_page_count(iterator, book_path, page_algorithm): <NEW_LINE> <INDENT> if iterator is None: <NEW_LINE> <INDENT> iterator = _open_epub_file(book_path) <NEW_LINE> <DEDENT> count = 0 <NEW_LINE> if page_algorithm == 0: <NEW_LINE> <INDENT> count = _get_page_count_accurate(iterator) <NEW_LINE> <DEDENT> elif page_algorithm == 1: <NEW_LINE> <INDENT> count = _get_page_count_calibre(iterator) <NEW_LINE> <DEDENT> elif page_algorithm == 2: <NEW_LINE> <INDENT> count = _get_page_count_adobe(iterator, book_path) <NEW_LINE> <DEDENT> print('\tPage count:', count) <NEW_LINE> return iterator, count | Given an iterator for the epub (if already opened/converted), estimate a page count | 625941c0a934411ee37515e6 |
def subchain(self, item: slice, ignore_text_index: bool = False) -> "MessageChain": <NEW_LINE> <INDENT> from .elements.internal import Plain <NEW_LINE> result = copy.copy(self.__root__) <NEW_LINE> if item.start: <NEW_LINE> <INDENT> first_slice = result[item.start[0] :] <NEW_LINE> if item.start[1] is not None and first_slice: <NEW_LINE> <INDENT> if not isinstance(first_slice[0], Plain): <NEW_LINE> <INDENT> if not ignore_text_index: <NEW_LINE> <INDENT> raise TypeError( "the sliced chain does not starts with a Plain: {}".format( first_slice[0] ) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = first_slice <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> final_text = first_slice[0].text[item.start[1] :] <NEW_LINE> result = [ *([Plain(final_text)] if final_text else []), *first_slice[1:], ] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result = first_slice <NEW_LINE> <DEDENT> <DEDENT> if item.stop: <NEW_LINE> <INDENT> first_slice = result[: item.stop[0]] <NEW_LINE> if item.stop[1] is not None and first_slice: <NEW_LINE> <INDENT> if not isinstance(first_slice[-1], Plain): <NEW_LINE> <INDENT> raise TypeError( "the sliced chain does not ends with a Plain: {}".format( first_slice[-1] ) ) <NEW_LINE> <DEDENT> final_text = first_slice[-1].text[: item.stop[1]] <NEW_LINE> result = [ *first_slice[:-1], *([Plain(final_text)] if final_text else []), ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = first_slice <NEW_LINE> <DEDENT> <DEDENT> return MessageChain.create(result) | 对消息链执行分片操作
Args:
item (slice): 这个分片的 `start` 和 `end` 的 Type Annotation 都是 `Optional[MessageIndex]`
Raises:
TypeError: TextIndex 取到了错误的位置
Returns:
MessageChain: 分片后得到的新消息链, 绝对是原消息链的子集. | 625941c0e5267d203edcdbf2 |
def items_by_tag(request, tag, template_name="help_items_by_tag.html"): <NEW_LINE> <INDENT> relevant_tag = urllib.unquote(tag) <NEW_LINE> tagged_items = HelpItem.objects.filter(tag=relevant_tag) <NEW_LINE> return render(request, template_name, { 'tagged_items': tagged_items, 'relevant_tag': relevant_tag } ) | Lists all the items that are tagged with the relevant category | 625941c0a8370b77170527f3 |
def get_arguments() -> Options: <NEW_LINE> <INDENT> opts = Options(description="Converts data stored in a file into sql INSERT statements") <NEW_LINE> opts.add_argument("--table-name", action="store", dest="tablename", help="name of the table for INSERT statements") <NEW_LINE> opts.add_argument("--profile", action="store", dest="profile", help="profile name for input file structure (from profile file)") <NEW_LINE> opts.add_argument("--column-sep", action="store", dest="columnsep", help="input file column separator (profile setting overwrite it)") <NEW_LINE> opts.add_argument("--string-sep", action="store", dest="stringsep", help="input file string delimiter (profile setting overwrite it)") <NEW_LINE> opts.add_argument("--block-size", action="store", dest="blocksize", help="number of VALUE's items for each INSERT statement (profile settings overwrite it)", type=int) <NEW_LINE> opts.add_argument("--source-file", action="store", dest="inputfile", help="source file name") <NEW_LINE> opts.add_argument("--source-file-type", action="store", dest="inputfiletype", help="source file name type (CSV, XLS)") <NEW_LINE> opts.add_argument("--output-file", action="store", dest="outputfile", help="output file name") <NEW_LINE> args = opts.parse_args() <NEW_LINE> args.tablename = args.tablename or "" <NEW_LINE> args.inputfile = args.inputfile or "" <NEW_LINE> args.inputfiletype = (args.inputfiletype or "CSV").upper() <NEW_LINE> args.outputfile = args.outputfile or "" <NEW_LINE> args.stringsep = args.stringsep or "" <NEW_LINE> args.columnsep = args.columnsep or "" <NEW_LINE> args.blocksize = args.blocksize or 1 <NEW_LINE> if args.tablename == "" or args.inputfile == "" or args.outputfile == "": <NEW_LINE> <INDENT> opts.error("Table name, input and output file are required") <NEW_LINE> return None <NEW_LINE> <DEDENT> if not os.path.exists(args.inputfile): <NEW_LINE> <INDENT> opts.error("Input file '%s' not found" % args.inputfile) <NEW_LINE> return None <NEW_LINE> <DEDENT> profile = load_profile(args.profile) <NEW_LINE> if (not profile is None): <NEW_LINE> <INDENT> args.columnsep = profile['column_sep'] if profile['column_sep'] != "" else args.columnsep <NEW_LINE> args.stringsep = profile['string_sep'] if profile['string_sep'] != "" else args.stringsep <NEW_LINE> args.blocksize = profile['block_size'] if profile['block_size'] != "" else args.blocksize <NEW_LINE> <DEDENT> return args | Define the script options, read the command line arguments and check their validity
Returns:
Options -- strinpt options | 625941c063f4b57ef0001072 |
def onClose(self): <NEW_LINE> <INDENT> self._getSchedulable().setNom( self.__varNom.get()) <NEW_LINE> self._getSchedulable().setPeriodeWithName(self.__varPeriode.get()) <NEW_LINE> self._getSchedulable().setColor( self.__colbut.get()) <NEW_LINE> self._getSchedulable().setDescription( self.__textDesc.get("0.0", END)[:-1]) | On change tout ce qu'il faut
@change nom
@change periode (with name)
@change color
@change description | 625941c0ac7a0e7691ed4023 |
def test_run_cmd_qa_trace(self): <NEW_LINE> <INDENT> easybuild.tools.utilities._log.experimental = easybuild.tools.utilities._log.warning <NEW_LINE> init_config(build_options={'trace': True}) <NEW_LINE> self.mock_stdout(True) <NEW_LINE> self.mock_stderr(True) <NEW_LINE> (out, ec) = run_cmd_qa("echo 'n: '; read n; seq 1 $n", {'n: ': '5'}) <NEW_LINE> stdout = self.get_stdout() <NEW_LINE> stderr = self.get_stderr() <NEW_LINE> self.mock_stdout(False) <NEW_LINE> self.mock_stderr(False) <NEW_LINE> self.assertEqual(stderr, '') <NEW_LINE> pattern = "^ >> running interactive command:\n" <NEW_LINE> pattern += "\t\[started at: .*\]\n" <NEW_LINE> pattern += "\t\[output logged in .*\]\n" <NEW_LINE> pattern += "\techo \'n: \'; read n; seq 1 \$n\n" <NEW_LINE> pattern += ' >> interactive command completed: exit 0, ran in .*' <NEW_LINE> self.assertTrue(re.search(pattern, stdout), "Pattern '%s' found in: %s" % (pattern, stdout)) <NEW_LINE> self.mock_stdout(True) <NEW_LINE> self.mock_stderr(True) <NEW_LINE> (out, ec) = run_cmd("echo hello", trace=False) <NEW_LINE> stdout = self.get_stdout() <NEW_LINE> stderr = self.get_stderr() <NEW_LINE> self.mock_stdout(False) <NEW_LINE> self.mock_stderr(False) <NEW_LINE> self.assertEqual(stdout, '') <NEW_LINE> self.assertEqual(stderr, '') | Test run_cmd under --trace | 625941c08e7ae83300e4af1f |
def CheckAllScalePhaseFractions(G2frame): <NEW_LINE> <INDENT> histograms, phases = G2frame.GetUsedHistogramsAndPhasesfromTree() <NEW_LINE> for i,hist in enumerate(histograms): <NEW_LINE> <INDENT> CheckScalePhaseFractions(G2frame,hist,histograms,phases) | Check if scale factor and all phase fractions are refined without a constraint
for all used histograms, if so, offer the user a chance to create a constraint
on the sum of phase fractions | 625941c0a4f1c619b28aff91 |
def ceil(dt, td): <NEW_LINE> <INDENT> return _round_to_func(dt, td, np.ceil, 'ceil') | Round numpy.datetime64 or numpy.timedelta64 to up to nearest
interval.
dt: numpy.datetime64 (or numpy.timedelta64) value to be rounded up.
td: numpy.timedelta64 interval to round up to.
Returns: numpy.datetime64 or numpy.timedelta64 rounded up the
nearest multiple of "td". | 625941c07cff6e4e811178d8 |
def getChild(self, name, request): <NEW_LINE> <INDENT> property = self.context.object.properties[name] <NEW_LINE> return PropertyPage(self.context.extend(property=property)) | Return a subpage to handle /objects/:uuid/properties/:name. | 625941c0cc0a2c11143dcde3 |
def btnPreprocessing(self): <NEW_LINE> <INDENT> if self.fa_path.get() == '': <NEW_LINE> <INDENT> messagebox.showwarning('提示', '请选择fa文件') <NEW_LINE> return <NEW_LINE> <DEDENT> if self.city_path.get() == '': <NEW_LINE> <INDENT> messagebox.showwarning('提示', '请选择城市经纬度文件') <NEW_LINE> return <NEW_LINE> <DEDENT> oper = Operation(self.fa_path.get(), self.city_path.get()) <NEW_LINE> flag = oper.judgeIntegrity() <NEW_LINE> if flag: <NEW_LINE> <INDENT> if len(flag) > UnMatchCityNum: <NEW_LINE> <INDENT> with open(LostLocationCities, 'w') as file: <NEW_LINE> <INDENT> file.write(HelpInfo) <NEW_LINE> for city in flag: <NEW_LINE> <INDENT> file.write(' '*29+city+'\n') <NEW_LINE> <DEDENT> <DEDENT> file.close() <NEW_LINE> messagebox.showinfo('CityName', '请在'+os.getcwd() +'/'+ LostLocationCities +'中查看待添加经纬度信息的城市') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for city in flag: <NEW_LINE> <INDENT> self.addCity(self.city_path.get(), city) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> messagebox.showinfo('Information', '城市经纬度文件完整!') | Complete the city file
| 625941c001c39578d7e74d8e |
def __init__(self, name=None, type=None, repository_id=None, branch=None, environment_id=None): <NEW_LINE> <INDENT> self.openapi_types = { 'name': str, 'type': str, 'repository_id': str, 'branch': str, 'environment_id': str } <NEW_LINE> self.attribute_map = { 'name': 'name', 'type': 'type', 'repository_id': 'repositoryId', 'branch': 'branch', 'environment_id': 'environmentId' } <NEW_LINE> self._name = name <NEW_LINE> self._type = type <NEW_LINE> self._repository_id = repository_id <NEW_LINE> self._branch = branch <NEW_LINE> self._environment_id = environment_id | PipelinePhase - a model defined in OpenAPI
:param name: The name of this PipelinePhase. # noqa: E501
:type name: str
:param type: The type of this PipelinePhase. # noqa: E501
:type type: str
:param repository_id: The repository_id of this PipelinePhase. # noqa: E501
:type repository_id: str
:param branch: The branch of this PipelinePhase. # noqa: E501
:type branch: str
:param environment_id: The environment_id of this PipelinePhase. # noqa: E501
:type environment_id: str | 625941c0c4546d3d9de72984 |
def neighborhood(self, concept): <NEW_LINE> <INDENT> return sorted([(self.graph[self.get_node(concept)][node]['weight'], node.concept) for node in self.graph.neighbors(self.get_node(concept))], reverse=True) | :param concept: The concept that is the focus of this operation.
:return: Returns the "neighborhood" of a concept: a list of `(correlation, concept)` tuples pointing to/from
it, plus itself. The neighborhood of the concept, a list of `(concept, concept, relevance_edge)` tuples
much like the ones returned by `edges()` that contains every edge drawn from the chosen concept to any
other in the graph.
Note that graph theoretic convention does not consider a node to be a neighbor to itself. Thus the
relevance tuple `(1, same_concept, same_concept)` is not included in output. | 625941c03c8af77a43ae36f1 |
def __init__(self, universe): <NEW_LINE> <INDENT> print("BLENDER RENDERER") <NEW_LINE> self.cfg = self.__load_config() <NEW_LINE> self.universe = universe <NEW_LINE> self.curr_frame = self.cfg.getint('Time', 'StartFrame') <NEW_LINE> self.__setup() | :param universe: the Conway universe object | 625941c04e696a04525c939f |
def create_mini_game(row, column): <NEW_LINE> <INDENT> board = np.zeros((row, column)) <NEW_LINE> return board.astype(int) | create empty board for minigames | 625941c0ff9c53063f47c147 |
def polar2cart(r, x0, y0, theta): <NEW_LINE> <INDENT> x = int(x0 + r * math.cos(theta)) <NEW_LINE> y = int(y0 + r * math.sin(theta)) <NEW_LINE> return x, y | Changes polar coordinates to cartesian coordinate system.
:param r: Radius
:param x0: x coordinate of the origin
:param y0: y coordinate of the origin
:param theta: Angle
:return: Cartesian coordinates
:rtype: tuple (int, int) | 625941c0d99f1b3c44c674e7 |
def dumps(data): <NEW_LINE> <INDENT> return json.dumps(data) | Generate a TJSON string form a python dict.: | 625941c04a966d76dd550f60 |
def test_different_table_field_counts(self): <NEW_LINE> <INDENT> ca = Column('A', format='L', array=[True, False]) <NEW_LINE> cb = Column('B', format='L', array=[True, False]) <NEW_LINE> cc = Column('C', format='L', array=[True, False]) <NEW_LINE> ta = BinTableHDU.from_columns([cb]) <NEW_LINE> tb = BinTableHDU.from_columns([ca, cb, cc]) <NEW_LINE> diff = TableDataDiff(ta.data, tb.data) <NEW_LINE> assert not diff.identical <NEW_LINE> assert diff.diff_column_count == (1, 3) <NEW_LINE> assert len(diff.common_columns) == 1 <NEW_LINE> assert diff.common_column_names == set(['b']) <NEW_LINE> assert diff.diff_column_names == ([], ['A', 'C']) <NEW_LINE> assert diff.diff_ratio == 0 <NEW_LINE> assert diff.diff_total == 0 <NEW_LINE> report = diff.report() <NEW_LINE> assert ' Tables have different number of columns:' in report <NEW_LINE> assert ' a: 1\n b: 3' in report | Test tables with some common columns, but different number of columns
overall. | 625941c0004d5f362079a288 |
def __init__(self, exc, serializer=DEFAULT_EXC_SERIALIZER): <NEW_LINE> <INDENT> if isinstance(exc, BaseException): <NEW_LINE> <INDENT> cls = exc.__class__ <NEW_LINE> exc_args = exc.args <NEW_LINE> args = (cls.__module__, cls.__name__, exc_args) <NEW_LINE> args = [dumps(args, serializer=serializer)[2]] <NEW_LINE> <DEDENT> elif isinstance(exc, (list, tuple)): <NEW_LINE> <INDENT> args = exc <NEW_LINE> <DEDENT> elif isinstance(exc, six.string_types): <NEW_LINE> <INDENT> args = [exc] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Need a BaseException object") <NEW_LINE> <DEDENT> super(RemoteException, self).__init__(*args) | :param exc: Exception instance or RemoteException.args
:type exc: BaseException subclass, list or tuple
:param serializer: CELERY_RESULT_SERIALIZER for celery_rpc app
:type serializer: str | 625941c0d8ef3951e3243490 |
def get_queryset(self, queryset=None): <NEW_LINE> <INDENT> if queryset is None: <NEW_LINE> <INDENT> queryset = self.queryset.all() <NEW_LINE> <DEDENT> queryset = queryset.filter(cidade__slug=self.kwargs['cidade']) <NEW_LINE> return super(RetornaONGsCidade, self).get_queryset(queryset) | Sobrescrito para filtrar o queryset por estado e cidade. | 625941c06fb2d068a760efee |
def get_children(self): <NEW_LINE> <INDENT> for child in os.listdir(self.get_abs_path()): <NEW_LINE> <INDENT> assert isinstance(child, str) <NEW_LINE> yield self.clone(url_join(*(self.path + [child]))) | Return an iterator of all direct children of this resource. | 625941c016aa5153ce3623cb |
def interp1d(x, y, xnew, kind='linear', fill_value=np.nan, **kws): <NEW_LINE> <INDENT> kwargs = {'kind': kind.lower(), 'fill_value': fill_value, 'copy': False, 'bounds_error': False} <NEW_LINE> kwargs.update(kws) <NEW_LINE> return scipy_interp1d(x, y, **kwargs)(xnew) | interpolate x, y array onto new x values, using one of
linear, quadratic, or cubic interpolation
> ynew = interp1d(x, y, xnew, kind='linear')
Arguments
---------
x original x values
y original y values
xnew new x values for values to be interpolated to
kind method to use: one of 'linear', 'quadratic', 'cubic'
fill_value value to use to fill values for out-of-range x values
Notes
-----
unlike interp, this version will not extrapolate for values of `xnew`
that are outside the range of `x` -- it will use NaN or `fill_value`.
this is a bare-bones wrapping of scipy.interpolate.interp1d.
see also: interp | 625941c0bd1bec0571d90581 |
def test_load_text(self): <NEW_LINE> <INDENT> create_test_files() <NEW_LINE> (x_train, y_train), (x_test, y_test) = load_text_from_files(TEST_DATA_DIR, test_dataset_ratio=0.2) <NEW_LINE> expected = 5 <NEW_LINE> actual = len(x_train) <NEW_LINE> result = actual == expected <NEW_LINE> self.assertTrue(result, "actual does not match expected. \nActual:\n%s, \nExpected:\n%s" % (actual, expected)) <NEW_LINE> expected = 2 <NEW_LINE> actual = len(x_test) <NEW_LINE> result = actual == expected <NEW_LINE> self.assertTrue(result, "actual does not match expected. \nActual:\n%s, \nExpected:\n%s" % (actual, expected)) | Test loading text | 625941c0b5575c28eb68df51 |
def load_labelmap(path): <NEW_LINE> <INDENT> with tf.gfile.GFile(path, 'r') as fid: <NEW_LINE> <INDENT> print(path) <NEW_LINE> label_map_string = fid.read() <NEW_LINE> label_map = string_int_label_map_pb2.StringIntLabelMap() <NEW_LINE> try: <NEW_LINE> <INDENT> text_format.Merge(label_map_string, label_map) <NEW_LINE> <DEDENT> except text_format.ParseError: <NEW_LINE> <INDENT> label_map.ParseFromString(label_map_string) <NEW_LINE> <DEDENT> <DEDENT> _validate_label_map(label_map) <NEW_LINE> return label_map | Loads label map proto.
Args:
path: path to StringIntLabelMap proto text file.
Returns:
a StringIntLabelMapProto | 625941c04f6381625f114990 |
def __init__(self, model_instance, tns, include_parent=False, parent_tag="root", include_ns=True): <NEW_LINE> <INDENT> assert tns or tns !="" , "'tns' should not be None or an empty string" <NEW_LINE> self.instance = model_instance <NEW_LINE> self.tns = tns <NEW_LINE> self.include_parent= include_parent <NEW_LINE> self.parent_tag = parent_tag <NEW_LINE> self.include_ns = include_ns | @param An instance of a soaplib.core.model.clazz.ClassModel
@parma The target namespace of the model instance.
@param Indicates if a parent element should be returned as the root
element of the xml representation. If true, a root element will be included with
the tag "parent_tag"
@param The tag used for the creation of a root/parent element. | 625941c055399d3f05588606 |
def __init__(self, *, ca: 'ConfigCASigningProfilesCa' = None, tls: 'ConfigCASigningProfilesTls' = None) -> None: <NEW_LINE> <INDENT> self.ca = ca <NEW_LINE> self.tls = tls | Initialize a ConfigCASigningProfiles object.
:param ConfigCASigningProfilesCa ca: (optional) Controls attributes of
intermediate CA certificates.
:param ConfigCASigningProfilesTls tls: (optional) Controls attributes of
intermediate tls CA certificates. | 625941c08a43f66fc4b53fbb |
def is_serializable_descendant(base): <NEW_LINE> <INDENT> if "Serializable" in globals(): <NEW_LINE> <INDENT> return base is not Serializable and issubclass(base, Serializable) | Args:
base (type): Base class to examine
Returns:
(bool): True if `base` is a descendant of `Serializable` (but not `Serializable` itself) | 625941c0b7558d58953c4e6c |
def test_multiple_nics_missing_nic_mode(self): <NEW_LINE> <INDENT> self.data['nic_count'] = 2 <NEW_LINE> self.data['nic_link_0'] = 'br0' <NEW_LINE> self.data['nic_link_1'] = 'br1' <NEW_LINE> user.grant('create_vm', cluster) <NEW_LINE> form = NewVirtualMachineForm(user, self.data) <NEW_LINE> self.assertFalse(form.is_valid()) | tests submitting multiple nics, and that one is missing nic_mode | 625941c076d4e153a657ea83 |
def test_cover(): <NEW_LINE> <INDENT> assert_equals(len(repr(cover('9780156001311'))) > 50, True) <NEW_LINE> assert_equals(cover('9780000000000'), {}) <NEW_LINE> assert_equals(len(repr(cover('9781408835029'))) > 50, True) <NEW_LINE> assert_equals( len(repr(cover('9789727576807'))) < 50, True, ) | Test 'cover' command. | 625941c038b623060ff0ad41 |
def set_current_time(self, timer_value, **kwargs): <NEW_LINE> <INDENT> self.mode.player[self.tick_var] = int(timer_value) <NEW_LINE> if self.max_value and self.mode.player[self.tick_var] > self.max_value: <NEW_LINE> <INDENT> self.mode.player[self.tick_var] = self.max_value | Sets the current amount of time of this timer. This value is
expressed in "ticks" since the interval per tick can be something other
than 1 second).
Args:
timer_value: Integer of the current value you want this timer to be.
**kwargs: Not used in this method. Only exists since this method is
often registered as an event handler which may contain
additional keyword arguments. | 625941c0596a897236089a16 |
def setForeground(self, foreground): <NEW_LINE> <INDENT> self._foreground = foreground | Returns the foreground associated with this drop zone.
:return <QtGui.QColor> | 625941c0097d151d1a222daf |
@app.route('/user/<public_id>', methods=["GET"]) <NEW_LINE> @token_required <NEW_LINE> def get_one_user(current_user, public_id): <NEW_LINE> <INDENT> if not current_user.admin: <NEW_LINE> <INDENT> return jsonify({'Message': 'can not perform that function'}) <NEW_LINE> <DEDENT> user = User.query.filter_by(public_id=public_id).first() <NEW_LINE> if not user: <NEW_LINE> <INDENT> return jsonify({'message': 'No user found'}) <NEW_LINE> <DEDENT> user_data = {} <NEW_LINE> user_data['public_id'] = user.public_id <NEW_LINE> user_data['name'] = user.name <NEW_LINE> user_data['password'] = user.password <NEW_LINE> user_data['admin'] = user.admin <NEW_LINE> return jsonify({'Message': user_data}) | After getting a token, only admin users can perform these operations | 625941c0a05bb46b383ec777 |
def new_load_and_pivot(dataframe): <NEW_LINE> <INDENT> dataframe.drop(['end_sample', 't_offset'], axis=1, inplace=True) <NEW_LINE> return dataframe.groupby('start_sample').max() | New version which assumes the columns where the channel pairs are already columns | 625941c031939e2706e4cdc0 |
def serial_line_endings_to_sublime(text, line_endings): <NEW_LINE> <INDENT> if line_endings == "CR": <NEW_LINE> <INDENT> return text.replace("\r", "\n") <NEW_LINE> <DEDENT> if line_endings == "CRLF": <NEW_LINE> <INDENT> return text.replace("\r", "") <NEW_LINE> <DEDENT> return text | Converts the serial line endings to sublime text line endings
:param text: the text to convert line endings for
:param line_endings: the serial's line endings setting: "CR", "LF", or "CRLF"
:return: the new text | 625941c0ff9c53063f47c148 |
def locate(file, root): <NEW_LINE> <INDENT> avhrr_file_path=None <NEW_LINE> for path, dirs, files in os.walk(os.path.abspath(root)): <NEW_LINE> <INDENT> if file in path: <NEW_LINE> <INDENT> avhrr_file_path=path <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return avhrr_file_path | Locate all files matching supplied filename pattern in and below
supplied root directory. | 625941c04527f215b584c3ad |
def test_get_coord_sys_1D(): <NEW_LINE> <INDENT> if not HAVE_PYMOAB: <NEW_LINE> <INDENT> raise SkipTest <NEW_LINE> <DEDENT> xvals = [0.0, 2.0] <NEW_LINE> yvals = [0.0, 3.0] <NEW_LINE> zvals = [-1.0, 0.0, 1.0] <NEW_LINE> mesh = Mesh(structured_coords=[xvals, yvals, zvals], structured=True, structured_ordering='xyz') <NEW_LINE> igeom_expected = 'slab' <NEW_LINE> bounds_expected = {'z': [-1.0, 0.0, 1.0]} <NEW_LINE> igeom, bounds = partisn._get_coord_sys(mesh) <NEW_LINE> assert(igeom == igeom_expected) <NEW_LINE> assert(bounds == bounds_expected) | Test the _get_coord_sys function for a 1D mesh.
| 625941c05fcc89381b1e1610 |
def check_version(): <NEW_LINE> <INDENT> import requests <NEW_LINE> r = requests.get('https://pypi.python.org/pypi/boss-ingest/json').json() <NEW_LINE> r = r['info']['version'] <NEW_LINE> if r != __version__: <NEW_LINE> <INDENT> print("You are using version {}. A newer version of boss-ingest is available: {} ".format(__version__, r) + "\n\n'pip install -U boss-ingest' to update.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("You are using version {}, which is the latest available.".format(__version__)) | Tells you if you have an old version of boss-ingest. | 625941c015baa723493c3ec7 |
def cmd_init(): <NEW_LINE> <INDENT> scripts.assert_command_exist('mount') <NEW_LINE> scripts.assert_command_exist('umount') <NEW_LINE> scripts.assert_command_exist('systemd-nspawn') <NEW_LINE> oses.assert_root_privilege() <NEW_LINE> bases.make_dir(_get_pod_repo_path(), 0o750, bases.chown_app) <NEW_LINE> bases.make_dir(_get_active_path(), 0o750, bases.chown_app) <NEW_LINE> bases.make_dir(_get_graveyard_path(), 0o750, bases.chown_app) <NEW_LINE> bases.make_dir(_get_tmp_path(), 0o750, bases.chown_app) | Initialize the pod repository. | 625941c024f1403a92600abc |
def importVarious(context): <NEW_LINE> <INDENT> marker_file = 'collective-transform-xtags.txt' <NEW_LINE> if context.readDataFile(marker_file) is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return | Various import step code | 625941c021a7993f00bc7c3f |
def _trim_and_decode(ids, subtokenizer): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> index = list(ids).index(tokenizer.EOS_ID) <NEW_LINE> return subtokenizer.decode(ids[:index]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return subtokenizer.decode(ids) | Trim EOS and PAD tokens from ids, and decode to return a string. | 625941c05510c4643540f33d |
def hard_extract(self, keywords): <NEW_LINE> <INDENT> print(keywords) <NEW_LINE> while True: <NEW_LINE> <INDENT> domain = self.rule_match(keywords,reasoning_root="病症", threshold=0.88, remove=False) <NEW_LINE> if domain is not None and not self.symptom_dic[domain]: <NEW_LINE> <INDENT> if domain != "疼痛": <NEW_LINE> <INDENT> self.symptom_dic[domain] = True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> break | 透過症狀樹,取得可能的症狀實體 | 625941c0d18da76e23532427 |
def setTfluid(path, region, patch_info): <NEW_LINE> <INDENT> os.chdir(path+'/0/'+region) <NEW_LINE> file = path+'/0/'+region+'/T' <NEW_LINE> f = ParsedParameterFile(file) <NEW_LINE> print('\nSetting T (fluid) file..') <NEW_LINE> for key, value in patch_info.items(): <NEW_LINE> <INDENT> if 'adiabatic' in key: <NEW_LINE> <INDENT> if '".*_adiabatic"' not in f['boundaryField']: <NEW_LINE> <INDENT> f['boundaryField']['".*_adiabatic"'] = {'type': 'zeroGradient'} <NEW_LINE> <DEDENT> <DEDENT> if 'interface' in key: <NEW_LINE> <INDENT> if '".*_interface"' not in f['boundaryField']: <NEW_LINE> <INDENT> f['boundaryField']['".*_interface"'] = {'type': 'compressible::turbulentTemperatureCoupledBaffleMixed', 'value': 'uniform 293.15', 'kappaMethod': 'fluidThermo', 'Tnbr': 'T'} <NEW_LINE> <DEDENT> <DEDENT> if 'symmetry' in key: <NEW_LINE> <INDENT> if '".*_symmetry"' not in f['boundaryField']: <NEW_LINE> <INDENT> f['boundaryField']['".*_symmetry"'] = {'type': 'symmetry'} <NEW_LINE> <DEDENT> <DEDENT> if 'inlet' in key: <NEW_LINE> <INDENT> f['boundaryField'][key] = {'type': 'fixedValue', 'value': 'uniform 293.15'} <NEW_LINE> <DEDENT> if 'outlet' in key: <NEW_LINE> <INDENT> f['boundaryField'][key] = {'type': 'zeroGradient'} <NEW_LINE> <DEDENT> if 'heat_in' in key: <NEW_LINE> <INDENT> heat = str(input('\nq [heat flux] value for patch '+str(key)+': ')) <NEW_LINE> f['boundaryField'][key] = {'type': 'externalWallHeatFluxTemperature', 'kappaMethod': 'fluidThermo', 'q': heat, 'value': 'uniform 293.15', 'kappaName': 'none'} <NEW_LINE> <DEDENT> <DEDENT> f.writeFile() | Setup T file for fluid | 625941c0cdde0d52a9e52f84 |
def get_playlist_entries(playlist, entry_type, language=settings.LANGUAGE_CODE): <NEW_LINE> <INDENT> unprepared = filter(lambda e: e["entity_kind"]==entry_type, playlist.entries) <NEW_LINE> prepared = [] <NEW_LINE> for entry in unprepared: <NEW_LINE> <INDENT> new_item = get_node_cache(language=language)[entry_type].get(entry['entity_id'], None) <NEW_LINE> if new_item: <NEW_LINE> <INDENT> prepared.append(new_item) <NEW_LINE> <DEDENT> <DEDENT> return prepared | Given a VanillaPlaylist, inspect its 'entries' attribute and return a list
containing corresponding nodes for each item from the topic tree.
entry_type should be "Exercise" or "Video". | 625941c04c3428357757c27d |
def get_positive_images(image_name,image_names,num_pos_images): <NEW_LINE> <INDENT> random_numbers = np.arange(len(image_names)) <NEW_LINE> np.random.shuffle(random_numbers) <NEW_LINE> if int(num_pos_images)>(len(image_names)-1): <NEW_LINE> <INDENT> num_pos_images = len(image_names)-1 <NEW_LINE> <DEDENT> pos_count = 0 <NEW_LINE> positive_images = [] <NEW_LINE> for random_number in list(random_numbers): <NEW_LINE> <INDENT> if image_names[random_number]!= image_name: <NEW_LINE> <INDENT> positive_images.append(image_names[random_number]) <NEW_LINE> pos_count += 1 <NEW_LINE> if int(pos_count)>(int(num_pos_images)-1): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return positive_images | Returns randomly sampled 'n' positive images from all_images | 625941c0f548e778e58cd4d0 |
def test_default_denylist(tmp_path, denylist): <NEW_LINE> <INDENT> assert denylist == { "IDS": ["fmt/61", "fmt/480"], "FILENAMES": [".DS_Store", "Thumbs.db"], "DIRECTORIES": ["Untitled Folder", "New Folder"], "EXTENSIONS": [".ini", ".cfg"], } | Make sure the denylist is parsed and output correctly. | 625941c06fece00bbac2d691 |
def test_generate_document_barcode(self): <NEW_LINE> <INDENT> for docrule_id, result in generated_barcodes: <NEW_LINE> <INDENT> obj = DocumentTypeRule.objects.get(pk=docrule_id) <NEW_LINE> obj.set_last_document_number(1000) <NEW_LINE> self.assertEquals(obj.allocate_barcode(), result) <NEW_LINE> self.assertEquals(obj.get_last_document_number(), 1001) | This is a test for barcode generation. | 625941c0e5267d203edcdbf3 |
def __reduce_ex__(self, i): <NEW_LINE> <INDENT> return (self.__class__, (self.name, self.dtypes)) | Used by pickle to create an object of this class.
Parameters
----------
i : int
protocol
Results
-------
out : tuple
A tuple of two elements
a callable function that can be called
to create the initial version of the object
and its arguments | 625941c0d164cc6175782ca1 |
def kickoff(self) -> StatusBase: <NEW_LINE> <INDENT> pass | Start a flyer
The status object return is marked as done once flying
has started.
Returns
-------
kickoff_status : StatusBase
Indicate when flying has started. | 625941c07d847024c06be20d |
def logout(self): <NEW_LINE> <INDENT> tmp = self.__send_JSON({"command": "logout"}) <NEW_LINE> return tmp | logouts | 625941c021a7993f00bc7c40 |
def test_check_if_failure(): <NEW_LINE> <INDENT> failure_found = False <NEW_LINE> for entry in json_data: <NEW_LINE> <INDENT> if not entry["success"]: <NEW_LINE> <INDENT> failure_found = True <NEW_LINE> if 'station' in entry: <NEW_LINE> <INDENT> print("Data for stop ", entry['station'], "collection failed.") <NEW_LINE> <DEDENT> if 'route' in entry: <NEW_LINE> <INDENT> print("Data for route ", entry['route'], "collection failed.") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> assert not failure_found | Test if there was no failures | 625941c0627d3e7fe0d68da2 |
def test_contains(self) -> None: <NEW_LINE> <INDENT> source = unittest.mock.Mock(spec_set=CodeSource) <NEW_LINE> container = unittest.mock.MagicMock(spec_set=CodeSourceContainer) <NEW_LINE> container.__getitem__.configure_mock(side_effect=(source, KeyError)) <NEW_LINE> self.assertTrue(CodeSourceContainer.__contains__(container, "Test")) <NEW_LINE> source.close.assert_called() <NEW_LINE> self.assertFalse(CodeSourceContainer.__contains__(container, "Test")) <NEW_LINE> self.assertFalse(CodeSourceContainer.__contains__(container, 1)) | test CodeSourceContainer.__contains__ | 625941c010dbd63aa1bd2afa |
def test_find_dict_item(): <NEW_LINE> <INDENT> example_dictionary = { 'a':{ '1': 'no', '2':[ {'part': 'you win1!', '2': 'no'}, {'2': 'no'} ], '3': 'no' }, 'b': 'no', 'c': {'part': 'you win2!', '2': 'no'}, 'd': {'ffff': {'e': {'part': 'you win3!', '2': 'no'}, '2': 'no'}, '2': 'no'}, 'e': {'part': {'e': {'part': 'you win4!', '2': 'no'}, '2': 'no'}, '2': 'no'} } <NEW_LINE> print('get finds: '+ str(example_dictionary.get('part'))) <NEW_LINE> print('func ONE finds: '+ str(deep_get(example_dictionary, 'part'))) <NEW_LINE> print('func ALL finds: '+ str(deep_get_all(example_dictionary, 'part'))) | lazy test | 625941c066656f66f7cbc0fe |
@csrf_exempt <NEW_LINE> def superuser(request): <NEW_LINE> <INDENT> response_status_code = status.HTTP_403_FORBIDDEN <NEW_LINE> username = request.POST.get('username') <NEW_LINE> user = None <NEW_LINE> user_class = get_user_model() <NEW_LINE> try: <NEW_LINE> <INDENT> service_identifiers = Service.objects.all().values_list('identifier', flat=True) <NEW_LINE> user = user_class.objects.exclude(username__in=service_identifiers).get(username=username, is_active=True) <NEW_LINE> <DEDENT> except user_class.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if user and user.is_superuser: <NEW_LINE> <INDENT> response_status_code = status.HTTP_200_OK <NEW_LINE> <DEDENT> logger.info('MQTT is super user check for user "{}": {}'.format( username, 'True' if response_status_code == status.HTTP_200_OK else 'False')) <NEW_LINE> return HttpResponse(status=response_status_code) | Check if the user with the supplied username is a superuser
Excludes any username that is an identifier of a service because
they could be mixed up and could end in a privilege escalation.
URI-Param username password clientid topic acc
http_superuser_uri Y N N N N | 625941c03346ee7daa2b2cbe |
def fee_per_kb(self, dyn: bool=None, mempool: bool=None, fee_level: float=None) -> Union[int, None]: <NEW_LINE> <INDENT> if dyn is None: <NEW_LINE> <INDENT> dyn = self.is_dynfee() <NEW_LINE> <DEDENT> if mempool is None: <NEW_LINE> <INDENT> mempool = self.use_mempool_fees() <NEW_LINE> <DEDENT> if fee_level is not None: <NEW_LINE> <INDENT> return self._feerate_from_fractional_slider_position(fee_level, dyn, mempool) <NEW_LINE> <DEDENT> if dyn: <NEW_LINE> <INDENT> if mempool: <NEW_LINE> <INDENT> fee_rate = self.depth_to_fee(self.get_depth_level()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fee_rate = self.eta_to_fee(self.get_fee_level()) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> fee_rate = self.get('fee_per_kb', FEERATE_FALLBACK_STATIC_FEE) <NEW_LINE> <DEDENT> return fee_rate | Returns sat/kvB fee to pay for a txn.
Note: might return None.
fee_level: float between 0.0 and 1.0, representing fee slider position | 625941c0fb3f5b602dac35e4 |
def xaccAccountGetHidden(*args): <NEW_LINE> <INDENT> return _gnucash_core_c.xaccAccountGetHidden(*args) | xaccAccountGetHidden(Account acc) -> gboolean | 625941c00fa83653e4656f10 |
def conn_redis(self): <NEW_LINE> <INDENT> host = self.redis_conf['host'] <NEW_LINE> port = self.redis_conf['port'] <NEW_LINE> db = self.redis_conf['db'] <NEW_LINE> password = self.redis_conf['password'] <NEW_LINE> try: <NEW_LINE> <INDENT> pool = redis.ConnectionPool(host=host, port=port, db=db, password=password, decode_responses=True) <NEW_LINE> self.r = redis.StrictRedis(connection_pool=pool) <NEW_LINE> return self.r <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print("连接redis失败".format(e)) | 连接redis | 625941c05f7d997b871749e9 |
def load_enum_kinds_dict(fname: str) -> Dict[str, Set[int]]: <NEW_LINE> <INDENT> d: Dict[str, Set[int]] = { 'onebyte': set(), 'twobytes': set(), 'threebytes': set(), 'fourbytes': set(), 'eightbytes': set(), 'sizedcontent': set(), 'enumblockarray': set(), 'arrayofenumblockarrays': set(), 'authentication': set(), 'salt': set(), 'password': set() } <NEW_LINE> with open(fname, 'r') as f: <NEW_LINE> <INDENT> for enumid, enumtype, _ in csv.reader(f): <NEW_LINE> <INDENT> if enumtype.lower() not in d: <NEW_LINE> <INDENT> raise ParserConfigError() <NEW_LINE> <DEDENT> d[enumtype.lower()].add(int(enumid, 0)) <NEW_LINE> <DEDENT> <DEDENT> return d | Load information about the enumfield types of enum ids | 625941c031939e2706e4cdc1 |
def getProcessInfo(self, name): <NEW_LINE> <INDENT> self._update('getProcessInfo') <NEW_LINE> group, process = self._getGroupAndProcess(name) <NEW_LINE> if process is None: <NEW_LINE> <INDENT> raise RPCError(Faults.BAD_NAME, name) <NEW_LINE> <DEDENT> start = capped_int(process.laststart) <NEW_LINE> stop = capped_int(process.laststop) <NEW_LINE> now = capped_int(self._now()) <NEW_LINE> state = process.get_state() <NEW_LINE> spawnerr = process.spawnerr or '' <NEW_LINE> exitstatus = process.exitstatus or 0 <NEW_LINE> stdout_logfile = process.config.stdout_logfile or '' <NEW_LINE> stderr_logfile = process.config.stderr_logfile or '' <NEW_LINE> info = { 'name': process.config.name, 'group': group.config.name, 'start': start, 'stop': stop, 'now': now, 'state': state, 'statename': getProcessStateDescription(state), 'spawnerr': spawnerr, 'exitstatus': exitstatus, 'logfile': stdout_logfile, 'stdout_logfile': stdout_logfile, 'stderr_logfile': stderr_logfile, 'pid': process.pid, } <NEW_LINE> description = self._interpretProcessInfo(info) <NEW_LINE> info['description'] = description <NEW_LINE> return info | Get info about a process named name
@param string name The name of the process (or 'group:name')
@return struct result A structure containing data about the process | 625941c060cbc95b062c6496 |
def get_state(self, update=True): <NEW_LINE> <INDENT> return { "position": self.cart.pos, "speed": self.cart.speed, "orientation": self.cart.angle, "content": self.cart.content, "pixels": self.get_pixels(update) } | Returns the environment's full state, including the cart's position,
its speed, its orientation and its content, as well as the environment's
pixels
Keyword Arguments:
update {bool} -- Whether to update the representation (default: {True})
Returns:
dict -- dict containing the aforementioned elements | 625941c03539df3088e2e29f |
def genToyData(seed=1234, nDocTotal=52, T=800): <NEW_LINE> <INDENT> nDocTotal = int(nDocTotal) <NEW_LINE> T = int(T) <NEW_LINE> prng = np.random.RandomState(seed) <NEW_LINE> states0toKm1 = np.arange(K) <NEW_LINE> doc_range = np.zeros(nDocTotal + 1, dtype=np.int32) <NEW_LINE> for i in xrange(1, nDocTotal + 1): <NEW_LINE> <INDENT> doc_range[i] = doc_range[i - 1] + T <NEW_LINE> <DEDENT> N = doc_range[-1] <NEW_LINE> allX = np.zeros((N, D)) <NEW_LINE> allXprev = np.zeros((N, D)) <NEW_LINE> allZ = np.zeros(N, dtype=np.int32) <NEW_LINE> for i in xrange(nDocTotal): <NEW_LINE> <INDENT> start = doc_range[i] <NEW_LINE> stop = doc_range[i + 1] <NEW_LINE> T = stop - start <NEW_LINE> Z = np.zeros(T + 1) <NEW_LINE> X = np.zeros((T + 1, D)) <NEW_LINE> Z[0] = startStates[i % len(startStates)] <NEW_LINE> X[0] = np.ones(D) <NEW_LINE> nConsec = 0 <NEW_LINE> for t in xrange(1, T + 1): <NEW_LINE> <INDENT> transPi_t = transPi[Z[t - 1]].copy() <NEW_LINE> if nConsec > 120: <NEW_LINE> <INDENT> transPi_t[Z[t - 1]] = 0 <NEW_LINE> transPi_t /= transPi_t.sum() <NEW_LINE> <DEDENT> Z[t] = prng.choice(states0toKm1, p=transPi_t) <NEW_LINE> X[t] = prng.multivariate_normal(np.dot(A[Z[t]], X[t - 1]), Sigma[Z[t]]) <NEW_LINE> if Z[t] == Z[t - 1]: <NEW_LINE> <INDENT> nConsec += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nConsec = 0 <NEW_LINE> <DEDENT> <DEDENT> allZ[start:stop] = Z[1:] <NEW_LINE> allX[start:stop] = X[1:] <NEW_LINE> allXprev[start:stop] = X[:-1] <NEW_LINE> <DEDENT> return allX, allXprev, allZ, doc_range | TODO
| 625941c030bbd722463cbd17 |
def invokefunction(self, script_hash, operation, params): <NEW_LINE> <INDENT> return self.call('invokefunction', [script_hash, operation, params]) | Invokes a contract's function with given parameters and returns the result.
:param script_hash: contract script hash
:param operation: name of the operation to invoke
:param params: list of paramaters to be passed in to the smart contract
:type script_hash: str
:type operation: str
:type params: list
:return: result of the invocation
:rtype: dictionary
:Example:
>>> explorer = NeoExplorerRPC()
>>> script_hash = "ecc6b20d3ccac1ee9ef109af5a7cdb85706b1df9"
>>> explorer.invokefunction(script_hash, "balanceOf", [{"type": "Hash160", "value": "bfc469dd56932409677278f6b7422f3e1f34481d"}])
{'gas_consumed': '0.338',
'stack': [{'type': 'ByteArray', 'value': '00ab510d'}],
'state': 'HALT, BREAK'}
.. note::
This method is to test your VM script as if they were ran on the blockchain at that point in time. This RPC call does not affect the blockchain in any way.
.. seealso::
http://docs.neo.org/en-us/node/api/invokefunction.html
.. todo::
TESTED | 625941c00a366e3fb873e76c |
def entry_xml_startdate(entry, entryxml): <NEW_LINE> <INDENT> if entry.not_empty('startDate'): <NEW_LINE> <INDENT> sub_element = etree.SubElement(entryxml, 'startDate') <NEW_LINE> sub_element.text = entry['startDate'] | Convert the entry startDate to XML. | 625941c0b57a9660fec337d6 |
def local_attention1d_masked_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): <NEW_LINE> <INDENT> print(x) <NEW_LINE> _, length_dim, model_dim = x.shape.dims <NEW_LINE> for layer in range(hparams.num_decoder_layers): <NEW_LINE> <INDENT> layer_name = "decoder_layer_%d" % layer <NEW_LINE> with tf.variable_scope(layer_name): <NEW_LINE> <INDENT> x += layer_prepostprocess_dropout( mtf.layers.masked_local_attention_1d( mtf.layers.layer_norm(x, model_dim, name="layer_norm_att"), None, kv_dim, heads_dim, block_length=hparams.block_length, name="self_att"), hparams) <NEW_LINE> x += layer_prepostprocess_dropout( mtf.layers.dense_relu_dense( mtf.layers.layer_norm(x, model_dim, name="layer_norm_ffn"), feedforward_dim, hparams.dropout, dropout_broadcast_dims=[length_dim]), hparams) <NEW_LINE> <DEDENT> <DEDENT> output = mtf.layers.layer_norm(x, model_dim, name="final_layer_norm") <NEW_LINE> return output | Image Transformer decoder with local1D masked layers. | 625941c06aa9bd52df036cf6 |
def get_biggest_square(self, size) -> Tuple[Cell, Power]: <NEW_LINE> <INDENT> biggest_power = -99 <NEW_LINE> top_left_corner = (0, 0) <NEW_LINE> side_range = range(self.side - size - 1) <NEW_LINE> for x, y in product(side_range, side_range): <NEW_LINE> <INDENT> square_power = self.get_square_power(x, y, size) <NEW_LINE> if square_power > biggest_power: <NEW_LINE> <INDENT> biggest_power = square_power <NEW_LINE> top_left_corner = (x, y) <NEW_LINE> <DEDENT> <DEDENT> return top_left_corner, biggest_power | Get left cell coordinates of a most powerful grid square. | 625941c030bbd722463cbd18 |
def allowed_attrs(self): <NEW_LINE> <INDENT> return ( ("access_rules", Struct), ) | Allowed attributes, as accepted by
:func:`course.validation.validate_struct`.
Subclasses should only add to, not remove entries from this. | 625941c060cbc95b062c6497 |
def create_school_interface(sku_name, sku_addr, admin_name): <NEW_LINE> <INDENT> sku_obj = models.School.select(sku_name) <NEW_LINE> if sku_obj: <NEW_LINE> <INDENT> return False, '该校区已存在' <NEW_LINE> <DEDENT> admin_obj = models.Admin.select(admin_name) <NEW_LINE> admin_obj.create_school(sku_name, sku_addr) <NEW_LINE> return True, f'学校:【{sku_name}】创建成功' | 创建校区接口
:param admin_name: 创建的管理员
:param sku_name: 学校名
:param sku_addr: 学校地址 | 625941c045492302aab5e215 |
def glInitCopyImageARB(): <NEW_LINE> <INDENT> from OpenGL import extensions <NEW_LINE> return extensions.hasGLExtension( _EXTENSION_NAME ) | Return boolean indicating whether this extension is available | 625941c0cc40096d615958a5 |
def test_application_windows_icon_attribute(self): <NEW_LINE> <INDENT> self.assertRegexpMatches(UiConstants.application_windows_icon, "\w+") <NEW_LINE> self.assertRegexpMatches(UiConstants.application_windows_icon, "\.[pP][nN][gG]$") | Tests :attr:`umbra.globals.ui_constants.UiConstants.application_windows_icon` attribute. | 625941c07c178a314d6ef3af |
def check_classes(gtype, section): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return sabnzbd.config.get_config(section, '%s_prio_%s' % (section, gtype))() > 0 <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> logging.debug('Incorrect Notify option %s:%s_prio_%s', section, section, gtype) <NEW_LINE> return False | Check if `gtype` is enabled in `section` | 625941c071ff763f4b5495dc |
def ident_akt(self): <NEW_LINE> <INDENT> return self._tokens[5] | getIdentAkt | 625941c0a934411ee37515e7 |
def test_sync_all_blacklist(self): <NEW_LINE> <INDENT> expected_return = {'engines': [], 'clouds': [], 'grains': [], 'beacons': [], 'utils': [], 'returners': [], 'modules': ['modules.override_test', 'modules.runtests_helpers', 'modules.salttest'], 'renderers': [], 'log_handlers': [], 'states': [], 'sdb': [], 'proxymodules': [], 'output': [], 'thorium': []} <NEW_LINE> ret = self.run_function('saltutil.sync_all', extmod_blacklist={'modules': ['runtests_decorators']}) <NEW_LINE> self.assertEqual(ret, expected_return) | Test syncing all ModuleCase with blacklist | 625941c07047854f462a1360 |
def resize(self, *args): <NEW_LINE> <INDENT> return _runtime_swig.void_start_vector_t_resize(self, *args) | resize(void_start_vector_t self, std::vector< void * >::size_type new_size)
resize(void_start_vector_t self, std::vector< void * >::size_type new_size, std::vector< void * >::value_type x) | 625941c0cc40096d615958a6 |
def upgrade_to_85(context): <NEW_LINE> <INDENT> logger.info('Reimporting steps for plone.app.caching') <NEW_LINE> context.runAllImportStepsFromProfile('profile-plone.app.caching:default') <NEW_LINE> logger.info('Finished reimporting steps for plone.app.caching') | Manual step for plone.app.caching in order to reimport the profiles
| 625941c0b545ff76a8913d6a |
def deleteVersions(self, version_ids): <NEW_LINE> <INDENT> pass | Not implemented as it's not required, yet.
| 625941c0566aa707497f44c1 |
def set_estado_interno(self): <NEW_LINE> <INDENT> for id in range(10): <NEW_LINE> <INDENT> if self.tipo_llamada_interno[id] is None: <NEW_LINE> <INDENT> self.estado_int[id] = "Libre" <NEW_LINE> <DEDENT> elif self.tipo_llamada_interno[id]: <NEW_LINE> <INDENT> self.estado_int[id] = f"Atendiendo int. {self.num_llamada_a_int[id]}" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.estado_int[id] = f"Atendiendo ext. {self.num_llamada_a_int[id]}" | Devuelve el estado de los internos con el numero y tipo de llamada que esta atendiendo | 625941c001c39578d7e74d8f |
def is_alive(self): <NEW_LINE> <INDENT> return self._is_alive | is_alive() -> returns true if download is active | 625941c091af0d3eaac9b96b |
def do_prev_release(self, log, connect): <NEW_LINE> <INDENT> if self.result.exited == 0: <NEW_LINE> <INDENT> self.sequence = 4 <NEW_LINE> with open(log, 'a') as f: <NEW_LINE> <INDENT> f.write('[INFO]------正在执行部署前的工作[%s]------\n' % (self.sequence)) <NEW_LINE> <DEDENT> target_release_version = "%s/%s" % (self.target_releases, self.release_version) <NEW_LINE> command = '[ -d %s ] || mkdir -p %s' % (target_release_version, target_release_version) <NEW_LINE> if self.result.exited == 0: <NEW_LINE> <INDENT> self.result = connect.run(command, write=log) <NEW_LINE> <DEDENT> self.file = '%s/%s' % (self.local_project_path.rstrip('/'), self.release_version + '.tar') <NEW_LINE> if self.result.exited == 0: <NEW_LINE> <INDENT> with open(log, 'a') as f: <NEW_LINE> <INDENT> f.write('[INFO]------正在上传压缩包至远程服务器------\n') <NEW_LINE> <DEDENT> self.result = connect.put(self.file, remote=target_release_version, write=log) <NEW_LINE> <DEDENT> self.localhost.local('rm -f %s' % (self.file)) <NEW_LINE> with connect.cd(self.target_releases): <NEW_LINE> <INDENT> command = 'ls -l |grep "^d"|wc -l' <NEW_LINE> if self.result.remote: <NEW_LINE> <INDENT> self.result = connect.run(command, write=log) <NEW_LINE> <DEDENT> releases_num = int(self.result.stdout.strip()) <NEW_LINE> if releases_num >= self.version_num: <NEW_LINE> <INDENT> command = "ls -t |sort -t '_' -k 2 |head -1" <NEW_LINE> if self.result.exited == 0: <NEW_LINE> <INDENT> self.result = connect.run(command, write=log) <NEW_LINE> <DEDENT> last_record_id = self.result.stdout.strip() <NEW_LINE> command = 'rm -rf %s/%s' % (self.target_releases, last_record_id) <NEW_LINE> if self.result.exited == 0: <NEW_LINE> <INDENT> self.result = connect.run(command, write=log) <NEW_LINE> DeployRecord.objects.filter(record_id=last_record_id).update(is_rollback=False) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> with connect.cd(target_release_version): <NEW_LINE> <INDENT> command = 'tar xf %s && rm -f %s' % (self.release_version + '.tar', self.release_version + '.tar') <NEW_LINE> if self.result.exited == 0: <NEW_LINE> <INDENT> self.result = connect.run(command, write=log) <NEW_LINE> <DEDENT> <DEDENT> commands = self.prev_release <NEW_LINE> if commands: <NEW_LINE> <INDENT> for command in commands.split('\n'): <NEW_LINE> <INDENT> if command.strip().startswith('#') or not command.strip(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> with connect.cd(target_release_version): <NEW_LINE> <INDENT> if self.result.exited == 0: <NEW_LINE> <INDENT> self.result = connect.run(command, write=log) | 部署代码到目标机器前执行 | 625941c06fb2d068a760efef |
def _exists(image): <NEW_LINE> <INDENT> if image['url'] not in image_urls: <NEW_LINE> <INDENT> image_urls.append(image['url']) <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | return boolean if image exists in the image_urls list | 625941c023e79379d52ee4ba |
def __init__(self, tasks, worker_name='Worker'): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.logger = colorlog.getLogger(worker_name) <NEW_LINE> self.tasks = tasks <NEW_LINE> self.daemon = True <NEW_LINE> self.start() | Initializes an asynchronous worker
:tasks: TODO | 625941c0a17c0f6771cbdfa7 |
def sample(self, batch_size): <NEW_LINE> <INDENT> idxes = [ random.randint(0, len(self._storage) - 1) for _ in range(batch_size) ] <NEW_LINE> self._num_sampled += batch_size <NEW_LINE> return self._encode_sample(idxes) | Sample a batch of experiences.
Parameters
----------
batch_size: int
How many transitions to sample.
Returns
-------
batch in dictionary form | 625941c01f5feb6acb0c4aa8 |
def copy(self): <NEW_LINE> <INDENT> copy = FallinSolver() <NEW_LINE> for column_index in range(9): <NEW_LINE> <INDENT> for row_index in range(9): <NEW_LINE> <INDENT> copy.cells[column_index][row_index] = self.cells[column_index][row_index] <NEW_LINE> copy.count[column_index][row_index] = self.count[column_index][row_index] <NEW_LINE> copy.known = self.known <NEW_LINE> <DEDENT> <DEDENT> return copy | Makes col copy of the sudoku data
return col matrix with data of current game as col simple array-of-arrays | 625941c0f9cc0f698b140552 |
def call(self, inputs, state): <NEW_LINE> <INDENT> with vs.variable_scope("gates"): <NEW_LINE> <INDENT> bias_ones = self._bias_initializer <NEW_LINE> if self._bias_initializer is None: <NEW_LINE> <INDENT> dtype = [a.dtype for a in [inputs, state]][0] <NEW_LINE> bias_ones = init_ops.constant_initializer(1.0, dtype=dtype) <NEW_LINE> <DEDENT> value = math_ops.sigmoid( _linear([inputs, state], 2 * self._num_units, True, bias_ones, self._kernel_initializer)) <NEW_LINE> r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1) <NEW_LINE> <DEDENT> with vs.variable_scope("candidate"): <NEW_LINE> <INDENT> c = self._activation(_linear([inputs, r * state], self._num_units, False)) <NEW_LINE> <DEDENT> new_h = u * state + (1 - u) * c <NEW_LINE> return new_h, new_h | Gated recurrent unit (GRU) with nunits cells. | 625941c0e5267d203edcdbf4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.