code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@contextmanager <NEW_LINE> def disable_pipeline(): <NEW_LINE> <INDENT> PipelineMeta.disable = True <NEW_LINE> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> PipelineMeta.disable = False | Disable PipelineMeta class from storing pipelines. | 625941c366673b3332b92054 |
def __repr__(self): <NEW_LINE> <INDENT> string = "Node: \n" <NEW_LINE> string += "\tData:\n" <NEW_LINE> string += str(self.data) <NEW_LINE> string += "\tf(n):\n" <NEW_LINE> string += str(self.fn) <NEW_LINE> return string | repr to help with debugging | 625941c3a05bb46b383ec7e7 |
def _convert_module_in_cookbook(self, module: _module_api.CookbooksModuleInterface) -> Type[cookbook.CookbookBase]: <NEW_LINE> <INDENT> module_name, name = module.__name__.rsplit(".", 1) <NEW_LINE> try: <NEW_LINE> <INDENT> title = module.__title__.splitlines()[0] <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> logger.debug("Unable to detect title for module %s: %s", module.__name__, e) <NEW_LINE> title = CookbookItem.fallback_title <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> run = module.run <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> raise CookbookError(f"Unable to find run function in module {module.__name__}") from e <NEW_LINE> <DEDENT> runner_name = f"{name}Runner" <NEW_LINE> runner = type( runner_name, (_module_api.CookbookModuleRunnerBase,), {"_run": staticmethod(run)}, ) <NEW_LINE> runner.__module__ = module_name <NEW_LINE> attributes = { "__module__": module_name, "__name__": name, "spicerack_name": name, "spicerack_path": module_name.split(".", 1)[1] if "." in module_name else "", "title": title, "get_runner": lambda _, args: runner(args, self.spicerack), } <NEW_LINE> try: <NEW_LINE> <INDENT> args_parser = module.argument_parser <NEW_LINE> attributes["argument_parser"] = lambda _: args_parser() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> attributes["argument_parser"] = lambda _: argparse.ArgumentParser( description=module.__doc__, formatter_class=cookbook.ArgparseFormatter ) <NEW_LINE> <DEDENT> cookbook_class = type(name, (cookbook.CookbookBase,), attributes) <NEW_LINE> return cookbook_class | Convert a module API based cookbook into a class API cookbook.
Arguments:
module (spicerack._module_api.CookbooksModuleInterface): the module to convert.
Returns:
type: a dynamically generated class derived from :py:class:`spicerack.cookbook.CookbookBase`. | 625941c330c21e258bdfa45f |
def header(self, ext=0): <NEW_LINE> <INDENT> return self.hdu[ext].header | Header of the object at extension `ext` | 625941c3d7e4931a7ee9dee0 |
def refresh_progress_bars(self, now_percent): <NEW_LINE> <INDENT> total_percent = int(((now_percent * self.step) / 100) + self.min_value) <NEW_LINE> if now_percent > self.nowQPBar.value() and not (now_percent > 100): <NEW_LINE> <INDENT> self.nowQPBar.setValue(now_percent) <NEW_LINE> <DEDENT> if (total_percent > self.totalQPBar.value() and not (total_percent > self.max_value)): <NEW_LINE> <INDENT> self.totalQPBar.setValue(total_percent) | Refresh the values of self.nowQPBar and self.totalQPBar. | 625941c399fddb7c1c9de355 |
def getEnv(key): <NEW_LINE> <INDENT> if key in os.environ: <NEW_LINE> <INDENT> return os.environ[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(KEYS) == 0: <NEW_LINE> <INDENT> setup() <NEW_LINE> <DEDENT> if key in KEYS: <NEW_LINE> <INDENT> return KEYS[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise IOError(f'Key: {key} not found in global variable or in `.env` file') | Get env value from global env or `.env` file | 625941c366656f66f7cbc16e |
def action(switch_dict): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> user_input = main_prompt() <NEW_LINE> try: <NEW_LINE> <INDENT> switch_dict.get(user_input)() <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> print("Invalid input, {} please try again.".format(user_input)) | Takes in a user input as a parameter, enters a donation, prints a report,
prints list, exit, prompts again if the input is bad
If the user types exit it'll go back to the main prompt | 625941c3bde94217f3682db6 |
def format_example(image_name=None, img_size=256): <NEW_LINE> <INDENT> global status <NEW_LINE> train = status <NEW_LINE> image = tf.io.read_file(image_name) <NEW_LINE> image = tf.io.decode_jpeg(image, channels=3) <NEW_LINE> image = tf.cast(image, tf.float32) <NEW_LINE> image = (image/127.5) - 1 <NEW_LINE> image = tf.image.resize(image, (img_size, img_size)) <NEW_LINE> if train is True: <NEW_LINE> <INDENT> image = tf.image.random_flip_left_right(image) <NEW_LINE> image = tf.image.random_flip_up_down(image) <NEW_LINE> image = tf.image.random_hue(image, 0.08) <NEW_LINE> image = tf.image.random_saturation(image, 0.6, 1.6) <NEW_LINE> image = tf.image.random_brightness(image, 0.05) <NEW_LINE> image = tf.image.random_contrast(image, 0.7, 1.3) <NEW_LINE> <DEDENT> image = tf.reshape(image, (img_size, img_size, 3)) <NEW_LINE> return image | Apply any image preprocessing here
:param image_name: the specific filename of the image
:param img_size: size that images should be reshaped to
:return: image | 625941c35e10d32532c5eeeb |
def start(self): <NEW_LINE> <INDENT> return self._start | Return the starting point of the geodesic.
EXAMPLES::
sage: g = HyperbolicPlane().UHP().get_geodesic(I, 3*I)
sage: g.start()
Point in UHP I | 625941c35166f23b2e1a511d |
def remove(sub, s): <NEW_LINE> <INDENT> pass | >>> remove('an', 'banana')
'bana'
>>> remove('cyc', 'bicycle')
'bile'
>>> remove('iss', 'Mississippi')
'Missippi'
>>> remove('egg', 'bicycle')
'bicycle' | 625941c3ac7a0e7691ed4093 |
def open(self): <NEW_LINE> <INDENT> self.browser.get(self.url) <NEW_LINE> email = self.wait.until(EC.presence_of_element_located((By.XPATH, '//form/div[1]//input'))) <NEW_LINE> pwd = self.wait.until(EC.presence_of_element_located((By.XPATH, '//form/div[2]//input'))) <NEW_LINE> email.send_keys(self.email) <NEW_LINE> pwd.send_keys(self.pwd) | 打开页面,输入用户名密码
:return: | 625941c391f36d47f21ac4b4 |
def parse_current_buffer(f): <NEW_LINE> <INDENT> def wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.refresh_cache or vim.eval("&mod") == '1': <NEW_LINE> <INDENT> self.parser.feed(v.buf()) <NEW_LINE> if self.parser.success: <NEW_LINE> <INDENT> self.cache = self.parser.tree <NEW_LINE> self.refresh_cache = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v.clear_hl('BreezeJumpMark', 'BreezeShade') <NEW_LINE> self.refresh_cache = True <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.parser.tree = self.cache <NEW_LINE> <DEDENT> return f(self, *args, **kwargs) <NEW_LINE> <DEDENT> return wrapper | To provide some naive form of caching.
This decorator ensures that the wrapped method will have access to
a fully parsed DOM tree structure for the current buffer. | 625941c32c8b7c6e89b35785 |
def rotate(self, matrix: List[List[int]]) -> None: <NEW_LINE> <INDENT> if Solution.angle == 90: <NEW_LINE> <INDENT> self.rightleftMatrix(self.Transpose(matrix)) <NEW_LINE> <DEDENT> elif Solution.angle == 180: <NEW_LINE> <INDENT> self.updownMatrix(self.rightleftMatrix(matrix)) <NEW_LINE> <DEDENT> elif Solution.angle == 270: <NEW_LINE> <INDENT> self.updownMatrix(self.Transpose(matrix)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> matrix | Do not return anything, modify matrix in-place instead. | 625941c321bff66bcd684918 |
def GetClangOptionsFromCommandLine(clang_commandline, out_dir, additional_flags): <NEW_LINE> <INDENT> clang_flags = [] + additional_flags <NEW_LINE> def abspath(path): <NEW_LINE> <INDENT> return os.path.normpath(os.path.join(out_dir, path)) <NEW_LINE> <DEDENT> clang_tokens = shlex.split(clang_commandline) <NEW_LINE> include_pattern = re.compile(r'^(-I|-isystem)(.+)$') <NEW_LINE> for flag_index, flag in enumerate(clang_tokens): <NEW_LINE> <INDENT> include_match = include_pattern.match(flag) <NEW_LINE> if include_match: <NEW_LINE> <INDENT> path = abspath(include_match.group(2)) <NEW_LINE> clang_flags.append(include_match.group(1) + path) <NEW_LINE> <DEDENT> elif flag.startswith('-std') or flag == '-nostdinc++': <NEW_LINE> <INDENT> clang_flags.append(flag) <NEW_LINE> <DEDENT> elif flag.startswith('-') and flag[1] in 'DWFfmO': <NEW_LINE> <INDENT> if flag == '-Wno-deprecated-register' or flag == '-Wno-header-guard': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> clang_flags.append(flag) <NEW_LINE> <DEDENT> elif flag == '-isysroot' or flag == '-isystem' or flag == '-I': <NEW_LINE> <INDENT> if flag_index + 1 < len(clang_tokens): <NEW_LINE> <INDENT> clang_flags.append(flag) <NEW_LINE> clang_flags.append(abspath(clang_tokens[flag_index + 1])) <NEW_LINE> <DEDENT> <DEDENT> elif flag.startswith('--sysroot='): <NEW_LINE> <INDENT> sysroot_path = flag.lstrip('--sysroot=') <NEW_LINE> if sysroot_path.startswith('/'): <NEW_LINE> <INDENT> clang_flags.append(flag) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> clang_flags.append('--sysroot=' + abspath(sysroot_path)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return clang_flags | Extracts relevant command line options from |clang_commandline|
Args:
clang_commandline: (String) Full Clang invocation.
out_dir: (String) Absolute path to ninja build directory. Relative paths in
the command line are relative to |out_dir|.
additional_flags: (List of String) Additional flags to return.
Returns:
(List of Strings) The list of command line flags for this source file. Can
be empty. | 625941c3091ae35668666f25 |
def branch_and_bound_subestimation_graph_search(problem): <NEW_LINE> <INDENT> return graph_search(problem, HeuristicOrderQueue(problem)) | Search the nodes with the lowest path_cost +
Heuristic (straight-line distance) first | 625941c363f4b57ef00010e1 |
def __init__( self, *, control_plane_profile: "ManagedClusterPoolUpgradeProfile", agent_pool_profiles: List["ManagedClusterPoolUpgradeProfile"], **kwargs ): <NEW_LINE> <INDENT> super(ManagedClusterUpgradeProfile, self).__init__(**kwargs) <NEW_LINE> self.id = None <NEW_LINE> self.name = None <NEW_LINE> self.type = None <NEW_LINE> self.control_plane_profile = control_plane_profile <NEW_LINE> self.agent_pool_profiles = agent_pool_profiles | :keyword control_plane_profile: Required. The list of available upgrade versions for the
control plane.
:paramtype control_plane_profile:
~azure.mgmt.containerservice.v2020_07_01.models.ManagedClusterPoolUpgradeProfile
:keyword agent_pool_profiles: Required. The list of available upgrade versions for agent pools.
:paramtype agent_pool_profiles:
list[~azure.mgmt.containerservice.v2020_07_01.models.ManagedClusterPoolUpgradeProfile] | 625941c3fbf16365ca6f6184 |
def _SetucGALandBDSSignals(self): <NEW_LINE> <INDENT> self._ucMyGALandBDSSignals = self._posbuff[70] | Sets Log position Galileo and BDS signals | 625941c32c8b7c6e89b35786 |
def generate(self,problemList,solverParams=None): <NEW_LINE> <INDENT> if solverParams is None: solverParams = IKSolverParams() <NEW_LINE> t0 = time.time() <NEW_LINE> solutionList = [self.solveRaw(p,solverParams) for p in problemList] <NEW_LINE> t1 = time.time() <NEW_LINE> numSolved = len([s for s in solutionList if s is not None]) <NEW_LINE> print ("IKDatabase: Solved %d/%d problems in %fs"%(numSolved,len(problemList),t1-t0)) <NEW_LINE> with self.lock: <NEW_LINE> <INDENT> self.solutions += solutionList <NEW_LINE> if self.ikTemplate is None: <NEW_LINE> <INDENT> self.problems += problemList <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.problemFeatures += [self.problemToFeatures(p) for p in problemList] <NEW_LINE> <DEDENT> <DEDENT> self.buildNNDataStructure() <NEW_LINE> t2 = time.time() <NEW_LINE> print ("IKDatabase: Built query data structure in %fs"%(t2-t1,)) | Generates additional instances to the problem database.
- problemList: a list of IK problem instances
- solverParams: an IKSolverParams structure passed to self.solveRaw(),
or none for default parameters (see self.solveRaw() for more details) | 625941c301c39578d7e74dff |
def visitDir(self, path): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> for t in self.types: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> temp += [os.path.abspath(p) for p in Path(path).glob(f'**/*{t}')] <NEW_LINE> <DEDENT> except PermissionError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self.filepath += self.filtrated(temp) <NEW_LINE> def func(x, y): return x if y in x else x + [y] <NEW_LINE> self.filepath = reduce(func, [[], ] + self.filepath) | 筛选文件 | 625941c357b8e32f5248345d |
def get_relative_pose(self, pose1, pose2): <NEW_LINE> <INDENT> H_pose1 = np.zeros((4, 4)) <NEW_LINE> H_pose2 = np.zeros((4, 4)) <NEW_LINE> H_pose1[3, 3] = 1 <NEW_LINE> H_pose2[3, 3] = 1 <NEW_LINE> pose1_rot = Quaternion(pose1['rotation']).rotation_matrix <NEW_LINE> pose1_tran = pose1['translation'] <NEW_LINE> H_pose1[0:3, 0:3] = pose1_rot <NEW_LINE> H_pose1[0:3, 3] = pose1_tran <NEW_LINE> pose2_rot = Quaternion(pose2['rotation']).rotation_matrix <NEW_LINE> pose2_tran = pose2['translation'] <NEW_LINE> H_pose2[0:3, 0:3] = pose2_rot <NEW_LINE> H_pose2[0:3, 3] = pose2_tran <NEW_LINE> H_pose1_inv = np.linalg.inv(H_pose1) <NEW_LINE> relative_pose_matrix = np.dot(H_pose1_inv, H_pose2) <NEW_LINE> return relative_pose_matrix | calculate relative from pose1 to pose2 in the global frame
:param from_pose:
:param to_pose:
:return: | 625941c3956e5f7376d70e32 |
def __RQ(self, matrix): <NEW_LINE> <INDENT> Q, R = qr(np.flipud(matrix).T) <NEW_LINE> R = np.flipud(R.T) <NEW_LINE> Q = Q.T <NEW_LINE> return R[:, ::-1], Q[::-1, :] | Estimate the factor first 3*3 part. | 625941c37b25080760e3941e |
def lower_next_func(self, lower): <NEW_LINE> <INDENT> lower.setup_function(self.gendesc) <NEW_LINE> assert self.gendesc.argtypes[0] == self.gentype <NEW_LINE> builder = lower.builder <NEW_LINE> function = lower.function <NEW_LINE> genptr, = self.call_conv.get_arguments(function) <NEW_LINE> for i, ty in enumerate(self.gentype.arg_types): <NEW_LINE> <INDENT> argptr = cgutils.gep(builder, genptr, 0, 1, i) <NEW_LINE> lower.fnargs[i] = self.context.unpack_value(builder, ty, argptr) <NEW_LINE> <DEDENT> self.resume_index_ptr = cgutils.gep(builder, genptr, 0, 0, name='gen.resume_index') <NEW_LINE> self.gen_state_ptr = cgutils.gep(builder, genptr, 0, 2, name='gen.state') <NEW_LINE> prologue = function.append_basic_block("generator_prologue") <NEW_LINE> entry_block_tail = lower.lower_function_body() <NEW_LINE> stop_block = function.append_basic_block("stop_iteration") <NEW_LINE> builder.position_at_end(stop_block) <NEW_LINE> self.call_conv.return_stop_iteration(builder) <NEW_LINE> builder.position_at_end(prologue) <NEW_LINE> first_block = self.resume_blocks[0] = lower.blkmap[lower.firstblk] <NEW_LINE> switch = builder.switch(builder.load(self.resume_index_ptr), stop_block) <NEW_LINE> for index, block in self.resume_blocks.items(): <NEW_LINE> <INDENT> switch.add_case(index, block) <NEW_LINE> <DEDENT> builder.position_at_end(entry_block_tail) <NEW_LINE> builder.branch(prologue) <NEW_LINE> self.context.post_lowering(function) | Lower the generator's next() function (which takes the
passed-by-reference generator structure and returns the next
yielded value). | 625941c39b70327d1c4e0d98 |
def dump_gephi_format(mindata, tsdata): <NEW_LINE> <INDENT> mindata = np.loadtxt(mindata) <NEW_LINE> tsdata = np.loadtxt(tsdata) <NEW_LINE> edge_df = pd.DataFrame(columns=['min1', 'min2']) <NEW_LINE> edge_df['min1'] = tsdata[:, 3].astype('int') <NEW_LINE> edge_df['min2'] = tsdata[:, 4].astype('int') <NEW_LINE> edge_df.to_csv('csvs/gephi_edge_connections.csv') | Create gephi-style csv format files from a min.data and ts.data file. | 625941c3fb3f5b602dac3655 |
def update_hand(hand, word): <NEW_LINE> <INDENT> updated_dict = hand.copy() <NEW_LINE> for letter in word.lower(): <NEW_LINE> <INDENT> if (updated_dict.get(letter, 0) > 0): <NEW_LINE> <INDENT> updated_dict[letter] -= 1 <NEW_LINE> <DEDENT> <DEDENT> return updated_dict | Does NOT assume that hand contains every letter in word at least as
many times as the letter appears in word. Letters in word that don't
appear in hand should be ignored. Letters that appear in word more times
than in hand should never result in a negative count; instead, set the
count in the returned hand to 0 (or remove the letter from the
dictionary, depending on how your code is structured).
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int) | 625941c3009cb60464c63377 |
def get_table_header (self, table_name): <NEW_LINE> <INDENT> table_num = pkb.get_TableNbr(self.table_def, table_name) - 1 <NEW_LINE> units = {} <NEW_LINE> intervals = {} <NEW_LINE> fields = self.table_def[table_num]['Fields'] <NEW_LINE> for item in fields: <NEW_LINE> <INDENT> units[item['FieldName']] = item['Units'] <NEW_LINE> intervals[item['FieldName']] = item['Processing'] <NEW_LINE> <DEDENT> return units, intervals | Function doc | 625941c38e71fb1e9831d76e |
def __init__(self, request, auth_model=None): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> if auth_model: <NEW_LINE> <INDENT> self.auth_model = auth_model <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from config import auth <NEW_LINE> self.auth_model = auth.AUTH['model'] | Auth constructor.
Arguments:
request {masonite.request.Request} -- The Request object.
Keyword Arguments:
auth_model {object} -- The model you want to authenticate with (default: {None}) | 625941c3d53ae8145f87a237 |
def fix_orientation(img, save_over=False): <NEW_LINE> <INDENT> path = None <NEW_LINE> if not isinstance(img, Image.Image): <NEW_LINE> <INDENT> path = img <NEW_LINE> img = Image.open(path) <NEW_LINE> <DEDENT> elif save_over: <NEW_LINE> <INDENT> raise ValueError("You can't use `save_over` when passing an Image instance. Use a file path instead.") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> orientation = img._getexif()[EXIF_ORIENTATION_TAG] <NEW_LINE> if orientation in [3, 6, 8]: <NEW_LINE> <INDENT> degrees = ORIENTATIONS[orientation][1] <NEW_LINE> img = img.rotate(degrees) <NEW_LINE> if save_over and path is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> img.save(path, quality=95, optimize=1) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> img.save(path, quality=95) <NEW_LINE> <DEDENT> <DEDENT> return (img, degrees) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (img, 0) <NEW_LINE> <DEDENT> <DEDENT> except (TypeError, AttributeError, KeyError): <NEW_LINE> <INDENT> None | `img` can be an Image instance or a path to an image file.
`save_over` indicates if the original image file should be replaced by the new image.
* Note: `save_over` is only valid if `img` is a file path. | 625941c34e696a04525c9410 |
def _log_handle_ses_reputation_request(self, metrics, status): <NEW_LINE> <INDENT> critical_count = len(metrics.critical) <NEW_LINE> warning_count = len(metrics.warning) <NEW_LINE> ok_count = len(metrics.ok) <NEW_LINE> self.logger.debug('SES account reputation metrics - critical: %s, warning: %s, ok: %s, status is %s!', critical_count, warning_count, ok_count, status) <NEW_LINE> self.logger.info( json_dump_request_event(class_name=self.__class__.__name__, method_name='handle_ses_reputation', details={ 'critical': metrics.critical, 'warning': metrics.warning, 'ok': metrics.ok})) | Log the SES account reputation handler request. | 625941c355399d3f05588677 |
def __init__(self, backend_url_prefix=None, name=None, description=None, labels=None): <NEW_LINE> <INDENT> self.backend_url_prefix = backend_url_prefix <NEW_LINE> self.name = name <NEW_LINE> self.description = description <NEW_LINE> self.labels = labels <NEW_LINE> self._user = "" <NEW_LINE> self._id = "" | Args:
backend_url_prefix {str} -- Required URL prefix pointing to the metadata
backend, e.g. "127.0.0.1:8080".
name {str} -- Required name for the workspace.
description {str} -- Optional string for description of the workspace.
labels {object} Optional key/value string pairs to label the workspace. | 625941c331939e2706e4ce30 |
def test_b_pass_user(self): <NEW_LINE> <INDENT> self.udp(self.getParam().pass_user_b) | 设置参数为空 | 625941c321a7993f00bc7cb1 |
def get_timeseries(self, from_date: datetime, to_date: datetime, instrument: str, timeframe: Timeframe) -> Timeseries: <NEW_LINE> <INDENT> data = quandl.get(instrument) <NEW_LINE> return Timeseries(instrument, timeframe, data) | Retrieve a given timeseries from the datasource.
Args:
from_date: timeseries starting date.
to_date: timeseries last date.
instrument: target instrument.
timeframe: target timeframe.
Returns:
An Mercury Timeseries.
Raises:
IndexError: The requested time range cannot be satisfied. | 625941c36aa9bd52df036d67 |
def get_prime_factors(self, value): <NEW_LINE> <INDENT> self.__ensure_primes(value) <NEW_LINE> for prime in self.__primes: <NEW_LINE> <INDENT> while value % prime == 0: <NEW_LINE> <INDENT> yield prime <NEW_LINE> value = value // prime <NEW_LINE> <DEDENT> if value < 2: <NEW_LINE> <INDENT> break | Get the prime factors for a specified value | 625941c357b8e32f5248345e |
def compute_features_collection(snaps, pic_dir, cache=None): <NEW_LINE> <INDENT> if cache is None: <NEW_LINE> <INDENT> cache = {} <NEW_LINE> <DEDENT> snaps_with_features = [] <NEW_LINE> features_list = [] <NEW_LINE> for snap in snaps: <NEW_LINE> <INDENT> snap_id = snap.filename <NEW_LINE> features = cache.get(snap_id) <NEW_LINE> if features is not None: <NEW_LINE> <INDENT> snaps_with_features.append(snap) <NEW_LINE> features_list.append(features) <NEW_LINE> continue <NEW_LINE> <DEDENT> if not snap.get('warped', False): <NEW_LINE> <INDENT> logger.warning('Cannot compute feature for unwarped %s', snap_id) <NEW_LINE> continue <NEW_LINE> <DEDENT> warped_file_path = os.path.join(pic_dir, snap.warped_filename) <NEW_LINE> new_features = compute_features(warped_file_path) <NEW_LINE> cache[snap_id] = new_features <NEW_LINE> snaps_with_features.append(snap) <NEW_LINE> features_list.append(new_features) <NEW_LINE> <DEDENT> return snaps_with_features, np.array(features_list) | Compute the features for every element in the paths | 625941c3bd1bec0571d905f3 |
def tensor_zip(fn): <NEW_LINE> <INDENT> def _zip( out, out_shape, out_strides, a_storage, a_shape, a_strides, b_storage, b_shape, b_strides, ): <NEW_LINE> <INDENT> raise NotImplementedError('Need to implement for Task 3.1') <NEW_LINE> <DEDENT> return njit(parallel=True)(_zip) | NUMBA higher-order tensor zipWith (or map2) function ::
fn_zip = tensor_zip(fn)
fn_zip(out, ...)
Args:
fn: function maps two floats to float to apply.
out (array): storage for `out` tensor.
out_shape (array): shape for `out` tensor.
out_strides (array): strides for `out` tensor.
a_storage (array): storage for `a` tensor.
a_shape (array): shape for `a` tensor.
a_strides (array): strides for `a` tensor.
b_storage (array): storage for `b` tensor.
b_shape (array): shape for `b` tensor.
b_strides (array): strides for `b` tensor.
Returns:
None : Fills in `out` | 625941c367a9b606de4a7e7f |
def parse_cli_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description="PowerballPy.") <NEW_LINE> group = parser.add_mutually_exclusive_group() <NEW_LINE> group.add_argument("--", help="define n of sets to generate", nargs='+', type=float) <NEW_LINE> args = parser.parse_args() <NEW_LINE> if args.n_sets is None: <NEW_LINE> <INDENT> parser.error("Argument required. None given.") <NEW_LINE> <DEDENT> return args | Define command line parser w/arguments.
| 625941c3293b9510aa2c325c |
def connect_to_db(app): <NEW_LINE> <INDENT> app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///testdb' <NEW_LINE> app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False <NEW_LINE> db.app = app <NEW_LINE> db.init_app(app) | Connecting the database to our Flask Application | 625941c3090684286d50eca8 |
def mkfs(device, ftype): <NEW_LINE> <INDENT> if not ismounted('%(device)s' % locals()): <NEW_LINE> <INDENT> run_as_root('mkfs.%(ftype)s %(device)s' % locals()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> abort("Partition is mounted") | Format filesystem
Example::
from fabtools.disk import mkfs
mkfs('/dev/sda2', 'ext4') | 625941c373bcbd0ca4b2c03b |
def test_enter_exit_overriding_generator(): <NEW_LINE> <INDENT> @ContextManagerType <NEW_LINE> def MyBaseContextManager(value): <NEW_LINE> <INDENT> raise Exception('This code is supposed to be overridden.') <NEW_LINE> yield <NEW_LINE> <DEDENT> class MyContextManager(MyBaseContextManager): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self._former_values = [] <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> global flag <NEW_LINE> self._former_values.append(flag) <NEW_LINE> flag = self.value <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, type_=None, value=None, traceback=None): <NEW_LINE> <INDENT> global flag, exception_type_caught <NEW_LINE> flag = self._former_values.pop() <NEW_LINE> if type_: <NEW_LINE> <INDENT> exception_type_caught = type_ <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> check_context_manager_type(MyContextManager, self_returning=True, error_catching=True) | Test an enter/exit context manager overriding one made from generator. | 625941c3507cdc57c6306c9b |
def get_entity_for_mid(self, mid): <NEW_LINE> <INDENT> return self.surface_index.get_entity_for_mid(mid) | Returns the entity object for the MID or None
if the MID is unknown. Forwards to surface index.
:param mid:
:return: | 625941c34527f215b584c41d |
@cli.command() <NEW_LINE> @click.argument('definition', type=DEFINITION) <NEW_LINE> @click.argument('version', callback=validate_version) <NEW_LINE> @click.argument('parameter', nargs=-1) <NEW_LINE> @region_option <NEW_LINE> @click.option('--disable-rollback', is_flag=True, help='Disable Cloud Formation rollback on failure') <NEW_LINE> @click.option('--dry-run', is_flag=True, help='No-op mode: show what would be created') <NEW_LINE> @click.option('-f', '--force', is_flag=True, help='Ignore failing validation checks') <NEW_LINE> def update(definition, region, version, parameter, disable_rollback, dry_run, force): <NEW_LINE> <INDENT> data = create_cf_template(definition, region, version, parameter, force) <NEW_LINE> cf = boto3.client('cloudformation', region) <NEW_LINE> with Action('Updating Cloud Formation stack {}..'.format(data['StackName'])) as act: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if dry_run: <NEW_LINE> <INDENT> info('**DRY-RUN** {}'.format(data['NotificationARNs'])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> del(data['Tags']) <NEW_LINE> cf.update_stack(**data) <NEW_LINE> <DEDENT> <DEDENT> except ClientError as e: <NEW_LINE> <INDENT> act.fatal_error('ClientError: {}'.format(pformat(e.response))) | Update an existing Cloud Formation stack from the given Senza definition file | 625941c3460517430c39414e |
def lookup(self, key): <NEW_LINE> <INDENT> super()._check_lookup(key) <NEW_LINE> try: <NEW_LINE> <INDENT> return os.environ["key"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return None | Dummy 'secret' lookup that checks env-vars | 625941c307f4c71912b11445 |
def process_batch(self, samples): <NEW_LINE> <INDENT> states = [] <NEW_LINE> actions = [] <NEW_LINE> rewards = [] <NEW_LINE> next_states = [] <NEW_LINE> terminals = [] <NEW_LINE> for sample in samples: <NEW_LINE> <INDENT> num_agents = sample.state.shape[0] <NEW_LINE> assert num_agents == sample.action.shape[0] <NEW_LINE> for i in xrange(num_agents): <NEW_LINE> <INDENT> states.append(sample.state[i].astype('float32') / 255.) <NEW_LINE> actions.append(sample.action[i]) <NEW_LINE> rewards.append(sample.reward[i]) <NEW_LINE> next_states.append(sample.next_state[i].astype('float32') / 255.) <NEW_LINE> terminals.append(0. if sample.is_terminal else 1.) <NEW_LINE> <DEDENT> <DEDENT> return np.array(states, dtype='float32'), np.array(actions), np.array(rewards), np.array(next_states, dtype='float32'), np.array(terminals) | The batches from replay memory will be uint8, convert to float32.
Same as process_state_for_network but works on a batch of
samples from the replay memory. Meaning you need to convert
both state and next state values. | 625941c323e79379d52ee52a |
@project.command() <NEW_LINE> @options.data() <NEW_LINE> @click.pass_context <NEW_LINE> @handle_errors <NEW_LINE> def create(ctx, data): <NEW_LINE> <INDENT> get_session_client().project.create(data=data) <NEW_LINE> click.echo('Project created') | Creates a project | 625941c392d797404e30414e |
def activate(self, _oWidget): <NEW_LINE> <INDENT> sCSName = create_card_set(self.parent) <NEW_LINE> if sCSName: <NEW_LINE> <INDENT> oCardSet = self.make_cs_from_filter(sCSName) <NEW_LINE> if oCardSet: <NEW_LINE> <INDENT> self.open_cs(sCSName, True) | Create the dialog.
Prompt the user for Card Set Properties, and so forth. | 625941c3f548e778e58cd541 |
def apply_fields(self, args): <NEW_LINE> <INDENT> assert len(args) == 2 <NEW_LINE> input = args[0] <NEW_LINE> start_output = args[1] <NEW_LINE> output = self.rshift_bv(input, start_output) <NEW_LINE> args[1] = output | Bitshifts a single field right by n.
Expects two arguments, both z3 BitVecs of same sizes. | 625941c32eb69b55b151c872 |
def __add__(self, other): <NEW_LINE> <INDENT> ax = other <NEW_LINE> if type(other) is float: <NEW_LINE> <INDENT> ax = dectofr(other) <NEW_LINE> <DEDENT> return Fraction(self.numerator * ax.denominator + self.denominator * ax.numerator, self.denominator * ax.denominator) | Adds to values
:param other:
:return:
>>> Fraction(1,4) + Fraction(2,4)
3/4
>>> Fraction(1,2) + Fraction(3,4)
5/4
>>> Fraction(1,2) + 2
5/2
>>> Fraction(1,2) + 2.5
3/1 | 625941c33539df3088e2e30f |
def get_all(): <NEW_LINE> <INDENT> return dao.get_all() | Get all contract items from the database..
Returns:
All contract items. | 625941c331939e2706e4ce31 |
@raises(ChemSpiPyAuthError) <NEW_LINE> def test_token_needed(): <NEW_LINE> <INDENT> cs2.get_extended_compound_info(263) | Test ChemSpiPyAuthError is raised for certain endpoints if no security_token provided. | 625941c329b78933be1e5673 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ScanPage): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941c3d8ef3951e3243501 |
def get_learning_rate_warmup(global_step, learning_rate, warmup_steps, warmup_scheme="t2t"): <NEW_LINE> <INDENT> print(" learning_rate=%g, warmup_steps=%d, warmup_scheme=%s" % (learning_rate, warmup_steps, warmup_scheme)) <NEW_LINE> if warmup_scheme == "t2t": <NEW_LINE> <INDENT> warmup_factor = tf.exp(tf.log(0.01) / warmup_steps) <NEW_LINE> inv_decay = warmup_factor ** ( tf.to_float(warmup_steps - global_step)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Unknown warmup scheme %s" % warmup_scheme) <NEW_LINE> <DEDENT> return tf.cond( global_step < warmup_steps, lambda: inv_decay * learning_rate, lambda: learning_rate, name="learning_rate_warump_cond") | Get learning rate warmup. | 625941c3cdde0d52a9e52ff6 |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self.curr_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW_LINE> length = len(_x) <NEW_LINE> <DEDENT> buff.write(struct.pack('<I%ss'%length, length, _x)) <NEW_LINE> _x = self.prev_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW_LINE> length = len(_x) <NEW_LINE> <DEDENT> buff.write(struct.pack('<I%ss'%length, length, _x)) <NEW_LINE> _x = self <NEW_LINE> buff.write(_get_struct_3d().pack(_x.x, _x.y, _x.z)) <NEW_LINE> _x = self.action <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW_LINE> length = len(_x) <NEW_LINE> <DEDENT> buff.write(struct.pack('<I%ss'%length, length, _x)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) <NEW_LINE> except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941c3adb09d7d5db6c755 |
def double_reaction_deletion(cobra_model, reaction_list1=None, reaction_list2=None, method="fba", return_frame=False, solver=None, zero_cutoff=1e-12, **kwargs): <NEW_LINE> <INDENT> if solver is None: <NEW_LINE> <INDENT> solver = get_solver_name(qp=(method == "moma")) <NEW_LINE> kwargs["solver"] = solver <NEW_LINE> <DEDENT> kwargs["zero_cutoff"] = zero_cutoff <NEW_LINE> if reaction_list1 is None: <NEW_LINE> <INDENT> reaction_indexes1 = range(len(cobra_model.reactions)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reaction_indexes1 = [cobra_model.reactions.index(r) for r in reaction_list1] <NEW_LINE> <DEDENT> if reaction_list2 is None: <NEW_LINE> <INDENT> reaction_indexes2 = reaction_indexes1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reaction_indexes2 = [cobra_model.reactions.index(r) for r in reaction_list2] <NEW_LINE> <DEDENT> reaction_to_result = generate_matrix_indexes(reaction_indexes1, reaction_indexes2) <NEW_LINE> wt_solution = solver_dict[solver].solve(cobra_model) <NEW_LINE> if wt_solution.status == "optimal": <NEW_LINE> <INDENT> kwargs["wt_growth_rate"] = wt_solution.f <NEW_LINE> kwargs["no_flux_reaction_indexes"] = {i for i, v in enumerate(wt_solution.x) if abs(v) < zero_cutoff} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> warn("wild-type solution status is '%s'" % wt_solution.status) <NEW_LINE> <DEDENT> if method == "fba": <NEW_LINE> <INDENT> results = _double_reaction_deletion_fba( cobra_model, reaction_indexes1, reaction_indexes2, reaction_to_result, **kwargs) <NEW_LINE> <DEDENT> elif method == "moma": <NEW_LINE> <INDENT> results = _double_reaction_deletion_moma( cobra_model, reaction_indexes1, reaction_indexes2, reaction_to_result, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Unknown deletion method '%s'" % method) <NEW_LINE> <DEDENT> full_result = format_upper_triangular_matrix( [reaction_to_result[i] for i in reaction_indexes1], [reaction_to_result[i] for i in reaction_indexes2], results) <NEW_LINE> row_ids = [cobra_model.reactions[i].id for i in reaction_indexes1] <NEW_LINE> column_ids = [cobra_model.reactions[i].id for i in reaction_indexes2] <NEW_LINE> return format_results_frame(row_ids, column_ids, full_result, return_frame) | sequentially knocks out pairs of reactions in a model
cobra_model : :class:`~cobra.core.Model.Model`
cobra model in which to perform deletions
reaction_list1 : [:class:`~cobra.core.Reaction.Reaction`:] (or their id's)
Reactions to be deleted. These will be the rows in the result.
If not provided, all reactions will be used.
reaction_list2 : [:class:`~cobra.core.Reaction`:] (or their id's)
Reactions to be deleted. These will be the rows in the result.
If not provided, reaction_list1 will be used.
method: "fba" or "moma"
Procedure used to predict the growth rate
solver: str for solver name
This must be a QP-capable solver for MOMA. If left unspecified,
a suitable solver will be automatically chosen.
zero_cutoff: float
When checking to see if a value is 0, this threshold is used.
return_frame: bool
If true, formats the results as a pandas.Dataframe. Otherwise
returns a dict of the form:
{"x": row_labels, "y": column_labels", "data": 2D matrix} | 625941c3a934411ee3751658 |
def test_init_app(self): <NEW_LINE> <INDENT> simon = Simon() <NEW_LINE> with mock.patch('simon.connection.connect') as connect: <NEW_LINE> <INDENT> simon.init_app(self.app) <NEW_LINE> connect.assert_called_with('localhost:27017', name='test', alias=None, username=None, password=None, replica_set=None) <NEW_LINE> simon.init_app(self.app, prefix='SIMON', alias='simon') <NEW_LINE> connect.assert_called_with('localhost:27017', name='test', alias='simon', username=None, password=None, replica_set=None) | Test the `init_app()` method. | 625941c30fa83653e4656f80 |
def __init__(self, max_code_size=(2**DEFAULT_MAX_BITS)): <NEW_LINE> <INDENT> self.closed = False <NEW_LINE> self._max_code_size = max_code_size <NEW_LINE> self._buffer = '' <NEW_LINE> self._clear_codes() <NEW_LINE> if max_code_size < self.code_size(): <NEW_LINE> <INDENT> raise ValueError("Max code size too small, (must be at least {0})".format(self.code_size())) | When the encoding codebook grows larger than max_code_size,
the Encoder will clear its codebook and emit a CLEAR_CODE | 625941c34a966d76dd550fd3 |
def get_posterier(frequency_dict, d_less, d_greater): <NEW_LINE> <INDENT> posterier = {} <NEW_LINE> for name, feature_value in frequency_dict.items(): <NEW_LINE> <INDENT> N_i = len(feature_value) <NEW_LINE> for value, counts in feature_value.items(): <NEW_LINE> <INDENT> posterier[value] = {} <NEW_LINE> posterier[value]['<=50K.'] = (counts[0] + 1) / (d_less + N_i) <NEW_LINE> posterier[value]['>50K.'] = (counts[1] + 1) / (d_greater + N_i) <NEW_LINE> <DEDENT> <DEDENT> return posterier | input the frequency dict of the train set
return a dict
posterier[feature_name][label] = p(xi|label)
Use Laplacian correction | 625941c3566aa707497f4530 |
def get_from_addrs(self, batch_id, asc=False): <NEW_LINE> <INDENT> return [] | Return a set of all known from_addrs sorted by timestamp. | 625941c33539df3088e2e310 |
def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu, freeze_layers=None): <NEW_LINE> <INDENT> global_step = tf.train.get_or_create_global_step() <NEW_LINE> learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32) <NEW_LINE> learning_rate = tf.train.polynomial_decay( learning_rate, global_step, num_train_steps, end_learning_rate=0.0, power=1.0, cycle=False ) <NEW_LINE> if num_warmup_steps: <NEW_LINE> <INDENT> global_steps_int = tf.cast(global_step, tf.int32) <NEW_LINE> warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32) <NEW_LINE> global_steps_float = tf.cast(global_steps_int, tf.float32) <NEW_LINE> warmup_steps_float = tf.cast(warmup_steps_int, tf.float32) <NEW_LINE> warmup_percent_done = global_steps_float / warmup_steps_float <NEW_LINE> warmup_learning_rate = init_lr * warmup_percent_done <NEW_LINE> is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32) <NEW_LINE> learning_rate = ((1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate) <NEW_LINE> <DEDENT> tf.summary.scalar('final_learning_rate', learning_rate) <NEW_LINE> optimizer = AdamWeightDecayOptimizer( learning_rate=learning_rate, weight_decay_rate=0.01, beta_1=0.9, beta_2=0.999, epsilon=1e-6, exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"] ) <NEW_LINE> if use_tpu: <NEW_LINE> <INDENT> optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer) <NEW_LINE> <DEDENT> tvars = tf.trainable_variables() <NEW_LINE> if freeze_layers is not None: <NEW_LINE> <INDENT> new_tvars = [] <NEW_LINE> for v in tvars: <NEW_LINE> <INDENT> flag = False <NEW_LINE> for fl in freeze_layers: <NEW_LINE> <INDENT> if "/{}/".format(fl) in v.name: <NEW_LINE> <INDENT> flag = True <NEW_LINE> <DEDENT> <DEDENT> if not flag: <NEW_LINE> <INDENT> new_tvars.append(v) <NEW_LINE> <DEDENT> <DEDENT> tvars = new_tvars <NEW_LINE> <DEDENT> print("train vars:") <NEW_LINE> for v in tvars: <NEW_LINE> <INDENT> print(v) <NEW_LINE> <DEDENT> grads = tf.gradients(loss, tvars) <NEW_LINE> (grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0) <NEW_LINE> train_op = optimizer.apply_gradients(zip(grads, tvars), global_step=global_step) <NEW_LINE> new_global_step = global_step + 1 <NEW_LINE> train_op = tf.group(train_op, [global_step.assign(new_global_step)]) <NEW_LINE> return train_op, learning_rate, global_step | Creates an optimizer training op. | 625941c3fbf16365ca6f6185 |
def dN(x, mu, sigma): <NEW_LINE> <INDENT> z = (x - mu) / sigma <NEW_LINE> pdf = np.exp(-0.5 * z ** 2) / math.sqrt(2 * math.pi * sigma ** 2) <NEW_LINE> return pdf | Probability density function of a normal random variable x.
Parameters
==========
mu: float
expected value
sigma: float
standard deviation
Returns
=======
pdf: float
value of probability density function | 625941c36fece00bbac2d701 |
def get_params_values_list(self, paramstring, env): <NEW_LINE> <INDENT> leftcount = paramstring.count('{{') <NEW_LINE> rightcount = paramstring.count('}}') <NEW_LINE> if leftcount > 0 and rightcount > 0: <NEW_LINE> <INDENT> params = {} <NEW_LINE> for i in range(0, leftcount): <NEW_LINE> <INDENT> start = paramstring.find('{{') <NEW_LINE> end = paramstring.find('}}',start) <NEW_LINE> if (start == -1 and end == -1): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> params_key = paramstring[start + 2:end] <NEW_LINE> params_record = Parms_Enviroment.query.filter( and_(Parms_Enviroment.parms_key == params_key, Parms_Enviroment.parms_env == env)).order_by(Parms_Enviroment.create_time.desc()).first() <NEW_LINE> if params_record is not None: <NEW_LINE> <INDENT> if params_record.parms_type == 'user': <NEW_LINE> <INDENT> params_value = params_record.parms_value <NEW_LINE> if len(params_value.split(',')) == 1: <NEW_LINE> <INDENT> paramstring = paramstring.replace("{{" + params_key + "}}",params_value) <NEW_LINE> params[params_key] = params_value.split(',') <NEW_LINE> <DEDENT> elif len(params_value.split(',')) > 1: <NEW_LINE> <INDENT> paramstring = paramstring.replace("{{" + params_key + "}}",params_value.split(',')[0]) <NEW_LINE> params[params_key] = params_value.split(',') <NEW_LINE> <DEDENT> <DEDENT> elif params_record.parms_type == 'sys': <NEW_LINE> <INDENT> tmp_parms_value = params_record.parms_value.split(';') <NEW_LINE> print("初始系统变量值为:",tmp_parms_value) <NEW_LINE> try: <NEW_LINE> <INDENT> num = int(tmp_parms_value[2]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> num = 0 <NEW_LINE> <DEDENT> if tmp_parms_value[0] == 'curr_date': <NEW_LINE> <INDENT> params_value = SysParams().curr_date(tmp_parms_value[1],tmp_parms_value[3],num) <NEW_LINE> <DEDENT> elif tmp_parms_value[0] == 'curr_time': <NEW_LINE> <INDENT> params_value = SysParams().curr_time(tmp_parms_value[1],tmp_parms_value[3],num) <NEW_LINE> <DEDENT> elif tmp_parms_value[0] == 'curr_month': <NEW_LINE> <INDENT> params_value = SysParams().curr_month(tmp_parms_value[1],tmp_parms_value[3],num) <NEW_LINE> <DEDENT> print("处理后的系统变量值为:",params_value) <NEW_LINE> paramstring = paramstring.replace("{{" + params_key + "}}",params_value) <NEW_LINE> params[params_key] = params_value.split(',') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print("未取到要参数化的变量值,请检查表数据") <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return paramstring, params <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> params = {} <NEW_LINE> return paramstring, params | 根据入参中 变量名分别获取变量值 列表信息
:param paramstring: 用来接收请求参数字符串
:param env: 使用变量所属环境
:return: paramstring(原始请求参数,或 参数化后的参数串), params -- 获取到的由“变量:变量值"(params_key:params_value)组成的字典,变量值为多个时,得到是list类型 | 625941c3c432627299f04c09 |
def show_tree(t, rules, show_nf = True, ignore_seen = False, bfs = False): <NEW_LINE> <INDENT> show_tree_(t, t.applyrec_(rules, ignore_seen = ignore_seen, bfs = bfs), rules, show_nf) | Show tree of applications. | 625941c32ae34c7f2600d0f6 |
def doobieMult (self, a, b): <NEW_LINE> <INDENT> return a * b | Multiplies two integers quite fantastically
a - the first integer
b - the second integer
idl: long doobieMultv ([in] long a, [in] long b); | 625941c3099cdd3c635f0c20 |
@app.route('/movie/<imdb_id>', methods=['GET']) <NEW_LINE> def render_movie_page(imdb_id): <NEW_LINE> <INDENT> return render_template('index.html', imdb_id=imdb_id) | Render the movie's data page | 625941c330dc7b766590192d |
def description(self, step_num=0): <NEW_LINE> <INDENT> result = dict( (k, getattr(self, k)) for k in self._STEP_ATTRS if k not in self._HIDDEN_ATTRS ) <NEW_LINE> result['type'] = self._STEP_TYPE <NEW_LINE> return result | Return a dictionary representation of this step. See
:ref:`steps-format` for examples. | 625941c30fa83653e4656f81 |
def run(): <NEW_LINE> <INDENT> if getuid() != 0: <NEW_LINE> <INDENT> print("setup_img.py is not running as root. Would you like to exit now, or elevate to root here?") <NEW_LINE> choice = input("exit or elevate: ").lower() <NEW_LINE> if choice == "elevate": <NEW_LINE> <INDENT> argv.insert(0, "sudo") <NEW_LINE> leave(check_call(argv)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Exiting . . .") <NEW_LINE> leave(0) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> config = download_config() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> eprint("Your internet is either slow or non-existant. Internet is necessary for setup. Please try again later.") <NEW_LINE> leave(2) <NEW_LINE> <DEDENT> setup(config) | Do the thing | 625941c38da39b475bd64f36 |
def user_chpass(user, host='localhost', password=None, password_hash=None, allow_passwordless=False, unix_socket=None, **connection_args): <NEW_LINE> <INDENT> args = {} <NEW_LINE> if password is not None: <NEW_LINE> <INDENT> password_sql = 'PASSWORD(%(password)s)' <NEW_LINE> args['password'] = password <NEW_LINE> <DEDENT> elif password_hash is not None: <NEW_LINE> <INDENT> password_sql = '%(password)s' <NEW_LINE> args['password'] = password_hash <NEW_LINE> <DEDENT> elif not salt.utils.is_true(allow_passwordless): <NEW_LINE> <INDENT> log.error('password or password_hash must be specified, unless ' 'allow_passwordless=True') <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> password_sql = '\'\'' <NEW_LINE> <DEDENT> dbc = _connect(**connection_args) <NEW_LINE> if dbc is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> cur = dbc.cursor() <NEW_LINE> qry = ('UPDATE mysql.user SET password=' + password_sql + ' WHERE User=%(user)s AND Host = %(host)s;') <NEW_LINE> args['user'] = user <NEW_LINE> args['host'] = host <NEW_LINE> if salt.utils.is_true(allow_passwordless) and salt.utils.is_true(unix_socket): <NEW_LINE> <INDENT> if host == 'localhost': <NEW_LINE> <INDENT> qry += ' IDENTIFIED VIA unix_socket' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.error('Auth via unix_socket can be set only for host=localhost') <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> result = _execute(cur, qry, args) <NEW_LINE> <DEDENT> except MySQLdb.OperationalError as exc: <NEW_LINE> <INDENT> err = 'MySQL Error {0}: {1}'.format(*exc) <NEW_LINE> __context__['mysql.error'] = err <NEW_LINE> log.error(err) <NEW_LINE> return False <NEW_LINE> <DEDENT> if result: <NEW_LINE> <INDENT> _execute(cur, 'FLUSH PRIVILEGES;') <NEW_LINE> log.info( 'Password for user \'{0}\'@\'{1}\' has been {2}'.format( user, host, 'changed' if any((password, password_hash)) else 'cleared' ) ) <NEW_LINE> return True <NEW_LINE> <DEDENT> log.info( 'Password for user \'{0}\'@\'{1}\' was not {2}'.format( user, host, 'changed' if any((password, password_hash)) else 'cleared' ) ) <NEW_LINE> return False | Change password for a MySQL user
host
Host for which this user/password combo applies
password
The password to set for the new user. Will take precedence over the
``password_hash`` option if both are specified.
password_hash
The password in hashed form. Be sure to quote the password because YAML
doesn't like the ``*``. A password hash can be obtained from the mysql
command-line client like so::
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
1 row in set (0.00 sec)
allow_passwordless
If ``True``, then ``password`` and ``password_hash`` can be omitted (or
set to ``None``) to permit a passwordless login.
.. versionadded:: 0.16.2
The ``allow_passwordless`` option was added.
CLI Examples:
.. code-block:: bash
salt '*' mysql.user_chpass frank localhost newpassword
salt '*' mysql.user_chpass frank localhost password_hash='hash'
salt '*' mysql.user_chpass frank localhost allow_passwordless=True | 625941c385dfad0860c3ae1f |
def compose(self): <NEW_LINE> <INDENT> response = { 'status': self.status, 'message': self.message, 'data': self.data } <NEW_LINE> return jsonify(response) | Create a response json object
Return:
jwonifyed response | 625941c396565a6dacc8f690 |
def add_vertex(self, v, label = ''): <NEW_LINE> <INDENT> if v in self.vertices_: return <NEW_LINE> self.vertices_.add(v) <NEW_LINE> self.adjacency_lists_[v] = set () <NEW_LINE> self.vertex_labels_[v] = label <NEW_LINE> self.edge_labels_[v] = {} | Add the vertex v to the graph and associate a label if one is given | 625941c3ad47b63b2c509f44 |
def raw_filename(length, ext_list=None): <NEW_LINE> <INDENT> char_table = re.sub(r'[/\?%*:|"<>]', '', ASCII_TABLE) <NEW_LINE> if ext_list is not None: <NEW_LINE> <INDENT> ext = choice(ext_list) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ext = '' <NEW_LINE> <DEDENT> name = raw_string(length - len(ext), char_table) <NEW_LINE> return name + ext | Creates a random filename with length up to `max_length`
and one of the given extensions. Make sure the biggest extension
length is smaller than `length`.
Keyword arguments:
length -- length for the new filename
ext_list -- list of valid extensions.
ref: http://en.wikipedia.org/wiki/Filename | 625941c3d486a94d0b98e10a |
def collect_used_devices(storage): <NEW_LINE> <INDENT> used_devices = [] <NEW_LINE> for root in storage.roots: <NEW_LINE> <INDENT> for device in list(root.mounts.values()) + root.swaps: <NEW_LINE> <INDENT> if device not in storage.devices: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> used_devices.extend(device.ancestors) <NEW_LINE> <DEDENT> <DEDENT> for new in [d for d in storage.devicetree.leaves if not d.format.exists]: <NEW_LINE> <INDENT> if new.format.mountable and not new.format.mountpoint: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> used_devices.extend(new.ancestors) <NEW_LINE> <DEDENT> for device in storage.partitions: <NEW_LINE> <INDENT> if getattr(device, "is_logical", False): <NEW_LINE> <INDENT> extended = device.disk.format.extended_partition.path <NEW_LINE> used_devices.append(storage.devicetree.get_device_by_path(extended)) <NEW_LINE> <DEDENT> <DEDENT> return used_devices | Collect devices used in existing or new installations.
:param storage: an instance of Blivet
:return: a list of devices | 625941c301c39578d7e74e00 |
def test_list_of_non_empty_non_blank_string(self): <NEW_LINE> <INDENT> self.assertEqual(count_lines(['dada ']), 1, 'list of one non-blank, non-empty string') <NEW_LINE> self.assertEqual(count_lines(['dada ', 'daa']), 2, 'list of multiple non-blank, non-empty lines') | Test the list of non-blank, non-empty strings.
| 625941c3a79ad161976cc10a |
def majority_filter(self, i, output, filterx=11, filtery=11, callback=None): <NEW_LINE> <INDENT> args = [] <NEW_LINE> args.append("--input='{}'".format(i)) <NEW_LINE> args.append("--output='{}'".format(output)) <NEW_LINE> args.append("--filterx={}".format(filterx)) <NEW_LINE> args.append("--filtery={}".format(filtery)) <NEW_LINE> return self.run_tool('majority_filter', args, callback) | Assigns each cell in the output grid the most frequently occurring value (mode) in a moving window centred on each grid cell in the input raster.
Keyword arguments:
i -- Input raster file.
output -- Output raster file.
filterx -- Size of the filter kernel in the x-direction.
filtery -- Size of the filter kernel in the y-direction.
callback -- Custom function for handling tool text outputs. | 625941c3d18da76e23532499 |
def build_model(self): <NEW_LINE> <INDENT> if (self.base == 'resnet101'): <NEW_LINE> <INDENT> self.model = models.resnet101(pretrained = self.pretrained) <NEW_LINE> self.set_parameter_requires_grad(not self.retrain_base) <NEW_LINE> num_ftrs = self.model.fc.in_features <NEW_LINE> self.model.fc = nn.Linear(num_ftrs, self.n_classes) <NEW_LINE> self.input_size = 224 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert "Model {} is not supported! ".format(self.base) | Build model architecture
| 625941c3cad5886f8bd26f9f |
def getObservationProb(self, noisyDistance, pacmanPosition, ghostPosition, jailPosition): <NEW_LINE> <INDENT> trueDistance = manhattanDistance(pacmanPosition,ghostPosition) <NEW_LINE> if ghostPosition == jailPosition: <NEW_LINE> <INDENT> if noisyDistance==None: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> if noisyDistance == None: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> return busters.getObservationProbability(noisyDistance,trueDistance) | Return the probability P(noisyDistance | pacmanPosition, ghostPosition). | 625941c399cbb53fe6792bac |
def is_selected(self, sid): <NEW_LINE> <INDENT> return | Check if Shape with <sid> is selected.
Returns:
(Boolean) True if Shape with <sid> is selected False otherwise | 625941c3e64d504609d74805 |
def breakit(stri,sep): <NEW_LINE> <INDENT> return stri.split(sep) | Break strings based on defined separators for different columns
Args:
stri: input text
sep: separator of the text
returns:
returns the list containing split parts of the input text
>>> import text_preprocessing as tp
>>> tp.breakit('small breed;large breed;medium breed',';')
['small breed', 'large breed', 'medium breed'] | 625941c316aa5153ce36243e |
def __init__(self, busId = 1, sa0 = SA0_HIGH): <NEW_LINE> <INDENT> super(LPS25H, self).__init__(busId) <NEW_LINE> self.pressEnabled = False | Set up I2C connection and initialize some flags and values.
| 625941c31f5feb6acb0c4b18 |
def di(x, y, delta=0): <NEW_LINE> <INDENT> return y.First > x.stime and x.Last > y.Last | X di Y
inverse x during y (y during x) | 625941c3d268445f265b4e33 |
def insert_to_sized_sorted_list(lst: list, x: int, max_size: int) -> bool: <NEW_LINE> <INDENT> i = bisect_left(lst, x) <NEW_LINE> if i or len(lst) < max_size: <NEW_LINE> <INDENT> lst.insert(i, x) <NEW_LINE> return True | Function to insert new value to sorted list with fixed size.
If size of lst less than max_size, or if x greatest then minimum
value in x, then insert x into lst. Else do nothing.
Important! Function edit input list
Args:
lst (list): list of integers.
x (int): value to insert.
max_size (int): max_size of input list
Returns:
bool: True, if the item was added | 625941c30a50d4780f666e56 |
def __init__(self, name): <NEW_LINE> <INDENT> super().__init__(name) | Constructor | 625941c3cb5e8a47e48b7a71 |
def addFacesGivenVertices( triangleMesh, vertexIndexTable, vertices ): <NEW_LINE> <INDENT> for vertexIndex in xrange( 0, len( vertices ), 3 ): <NEW_LINE> <INDENT> triangleMesh.faces.append( getFaceGivenLines( triangleMesh, vertexIndex, vertexIndexTable, vertices ) ) | Add faces given stl text. | 625941c3dc8b845886cb54f9 |
def colorize(string, color, bold=False, highlight = False): <NEW_LINE> <INDENT> attr = [] <NEW_LINE> num = color2num[color] <NEW_LINE> if highlight: num += 10 <NEW_LINE> attr.append(str(num)) <NEW_LINE> if bold: attr.append('1') <NEW_LINE> attrs = ';'.join(attr) <NEW_LINE> return '\x1b[%sm%s\x1b[0m' % (attrs, string) | Return string surrounded by appropriate terminal color codes to
print colorized text. Valid colors: gray, red, green, yellow,
blue, magenta, cyan, white, crimson | 625941c38da39b475bd64f37 |
def _get_top_global (self, days = 0, metric_filters = None): <NEW_LINE> <INDENT> top = None <NEW_LINE> closers = ITS.get_metrics("closers", ITS) <NEW_LINE> if closers is None: <NEW_LINE> <INDENT> closers = Closers(self.db, self.filters) <NEW_LINE> top = closers._get_top(days, metric_filters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> afilters = closers.filters <NEW_LINE> closers.filters = self.filters <NEW_LINE> top = closers._get_top(days, metric_filters) <NEW_LINE> closers.filters = afilters <NEW_LINE> <DEDENT> top['name'] = top.pop('closers') <NEW_LINE> return top | Implemented using Closers | 625941c3d4950a0f3b08c315 |
def empty(self): <NEW_LINE> <INDENT> if self.stack == []: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Returns whether the queue is empty.
:rtype: bool | 625941c34e696a04525c9411 |
def prioritypolicysets_status(self, prioritypolicyset_id, tenant_id=None, api_version="v2.0"): <NEW_LINE> <INDENT> if tenant_id is None and self._parent_class.tenant_id: <NEW_LINE> <INDENT> tenant_id = self._parent_class.tenant_id <NEW_LINE> <DEDENT> elif not tenant_id: <NEW_LINE> <INDENT> raise TypeError("tenant_id is required but not set or cached.") <NEW_LINE> <DEDENT> cur_ctlr = self._parent_class.controller <NEW_LINE> url = str(cur_ctlr) + "/{}/api/tenants/{}/prioritypolicysets/{}/status".format(api_version, tenant_id, prioritypolicyset_id) <NEW_LINE> api_logger.debug("URL = %s", url) <NEW_LINE> return self._parent_class.rest_call(url, "get") | Get a specific priority policy set status of tenant.
**Parameters:**:
- **prioritypolicyset_id**: Priority Policy Set ID
- **tenant_id**: Tenant ID
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended with cgx_status and cgx_content properties. | 625941c3090684286d50eca9 |
def _get_sync_floating_ips(self, context, router_ids, gw_port_ids): <NEW_LINE> <INDENT> if not router_ids: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> query = context.session.query(FloatingIP, models_v2.SubnetPool.address_scope_id) <NEW_LINE> query = query.join(models_v2.Port, FloatingIP.fixed_port_id == models_v2.Port.id) <NEW_LINE> query = query.outerjoin(models_v2.Subnet, models_v2.Subnet.network_id == models_v2.Port.network_id) <NEW_LINE> query = query.filter(models_v2.Subnet.ip_version == 4) <NEW_LINE> query = query.outerjoin(models_v2.SubnetPool, models_v2.Subnet.subnetpool_id == models_v2.SubnetPool.id) <NEW_LINE> query = query.filter(FloatingIP.router_id.in_(router_ids)) <NEW_LINE> query = query.filter(FloatingIP.floating_port_id.notin_(gw_port_ids)) <NEW_LINE> return [self._make_floatingip_dict_with_scope(*row) for row in self._unique_floatingip_iterator(query)] | Query floating_ips that relate to list of router_ids with scope.
This is different than the regular get_floatingips in that it finds the
address scope of the fixed IP. The router needs to know this to
distinguish it from other scopes.
There are a few redirections to go through to discover the address
scope from the floating ip. | 625941c3d164cc6175782d13 |
def get_my_order_status(self, currency_type=None): <NEW_LINE> <INDENT> self.exception_Currency(currency_type) <NEW_LINE> time.sleep(1) <NEW_LINE> endpoint ="/info/orders" <NEW_LINE> url_path = self.BASE_API_URL + endpoint <NEW_LINE> rgParams = { "currency": currency_type, } <NEW_LINE> api = XCoinAPI(self.CLIENT_ID,self.CLIENT_SECRET) <NEW_LINE> response = api.xcoinApiCall(endpoint, rgParams) <NEW_LINE> return response | 사용자의 현재 예약 중인 주문 현황을 조회하는 메서드 입니다.
:type currency_type: object
:param currency_type: 코인 이름
:return:
거래 중인 현황을 리스트로 반환합니다. | 625941c3c432627299f04c0a |
def get_subject_page(self, cookies, url): <NEW_LINE> <INDENT> subject_grade_response = requests.get(url, cookies=cookies) <NEW_LINE> return subject_grade_response.text | Returns the HTML site of the grades OR absences of the subject provided | 625941c3bf627c535bc13194 |
def PurpleAccountDisconnect(self, arg_account, *arg, **kw): <NEW_LINE> <INDENT> return self._dbus_object.PurpleAccountDisconnect( arg_account, *arg, **kw) | PurpleAccountDisconnect method:
Parameters
----------
account:
type: i,
direction: in;
| 625941c3d58c6744b4257c25 |
def test_combine_lists(self): <NEW_LINE> <INDENT> marxes_local = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] <NEW_LINE> marxes = list(marxes_local) <NEW_LINE> to_be_added = ["Gummo"] <NEW_LINE> marxes_local += to_be_added <NEW_LINE> ch3_pyfilling.combine_list(marxes, to_be_added) <NEW_LINE> self.assertEqual(marxes, marxes_local) | See title | 625941c3283ffb24f3c558c8 |
def print_kernel(self, kerneldef): <NEW_LINE> <INDENT> pass | Print the current kernel for the Gaussian process model.
.. note :: Not implemented yet | 625941c3925a0f43d2549e3b |
def _FillInputQueue(self): <NEW_LINE> <INDENT> start_id = self._vocab.WordToId(data.SENTENCE_START) <NEW_LINE> end_id = self._vocab.WordToId(data.SENTENCE_END) <NEW_LINE> pad_id = self._vocab.WordToId(data.PAD_TOKEN) <NEW_LINE> input_gen = self._TextGenerator(data.ExampleGen(self._data_path)) <NEW_LINE> pad_para = [0]*self._hps.sent_embed_dimensions <NEW_LINE> while True: <NEW_LINE> <INDENT> (article, abstract) = input_gen.next() <NEW_LINE> article_sentences = [] <NEW_LINE> abstract_sentences = [sent.strip() for sent in data.ToSentences(abstract, include_token=False)] <NEW_LINE> enc_inputs = np.reshape(article, [-1, self._hps.sent_embed_dimensions]).tolist() <NEW_LINE> dec_inputs = [start_id] <NEW_LINE> for i in xrange(min(self._max_abstract_sentences, len(abstract_sentences))): <NEW_LINE> <INDENT> dec_inputs += data.GetWordIds(abstract_sentences[i], self._vocab) <NEW_LINE> <DEDENT> if (len(enc_inputs) < self._hps.min_input_len or len(dec_inputs) < self._hps.min_input_len): <NEW_LINE> <INDENT> tf.logging.warning('Drop an example - too short.\nenc:%d\ndec:%d', len(enc_inputs), len(dec_inputs)) <NEW_LINE> continue <NEW_LINE> <DEDENT> if not self._truncate_input: <NEW_LINE> <INDENT> if (len(enc_inputs) > self._hps.enc_timesteps or len(dec_inputs) > self._hps.dec_timesteps): <NEW_LINE> <INDENT> tf.logging.warning('Drop an example - too long.\nenc:%d\ndec:%d', len(enc_inputs), len(dec_inputs)) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if len(enc_inputs) > self._hps.enc_timesteps: <NEW_LINE> <INDENT> enc_inputs = enc_inputs[:self._hps.enc_timesteps] <NEW_LINE> <DEDENT> if len(dec_inputs) > self._hps.dec_timesteps: <NEW_LINE> <INDENT> dec_inputs = dec_inputs[:self._hps.dec_timesteps] <NEW_LINE> <DEDENT> <DEDENT> targets = dec_inputs[1:] <NEW_LINE> targets.append(end_id) <NEW_LINE> enc_input_len = len(enc_inputs) <NEW_LINE> dec_output_len = len(targets) <NEW_LINE> while len(enc_inputs) < self._hps.enc_timesteps: <NEW_LINE> <INDENT> enc_inputs.append(pad_para) <NEW_LINE> <DEDENT> while len(dec_inputs) < self._hps.dec_timesteps: <NEW_LINE> <INDENT> dec_inputs.append(end_id) <NEW_LINE> <DEDENT> while len(targets) < self._hps.dec_timesteps: <NEW_LINE> <INDENT> targets.append(end_id) <NEW_LINE> <DEDENT> element = ModelInput(enc_inputs, dec_inputs, targets, enc_input_len, dec_output_len, ' '.join(article_sentences), ' '.join(abstract_sentences)) <NEW_LINE> self._input_queue.put(element) | Fill input queue with ModelInput. | 625941c33346ee7daa2b2d30 |
def test_fallback_noloader(self): <NEW_LINE> <INDENT> filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_import') <NEW_LINE> tmpl = get_template(filename, {'cachedir': TEMPLATES_DIR}, env='other') <NEW_LINE> self.assertEqual(tmpl.render(), 'Hey world !a b !') | A Template with a filesystem loader is returned as fallback
if the file is not contained in the searchpath | 625941c3baa26c4b54cb10e6 |
def ts_compare( dta, *args, x_key=None, y_key=None, y_key_list=None, y_highlight_key=None, savefig=None, title=None, ylabel=None, figsize=(12, 8), legend=True, **kwargs ): <NEW_LINE> <INDENT> assert y_key is None or y_key_list is None <NEW_LINE> if y_highlight_key is None: <NEW_LINE> <INDENT> if y_key_list is not None: <NEW_LINE> <INDENT> assert len(y_key_list) > 0 <NEW_LINE> _ts_compare_keylist(dta, x_key, y_key_list, figsize) <NEW_LINE> <DEDENT> elif y_key is not None: <NEW_LINE> <INDENT> dta.plot(x=x_key, y=y_key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dta.plot(x=x_key, legend=legend) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> _ts_compare_highlight( dta, x_key, y_highlight_key, figsize, legend ) <NEW_LINE> <DEDENT> if title is not None: <NEW_LINE> <INDENT> plt.title(title) <NEW_LINE> <DEDENT> if ylabel is not None: <NEW_LINE> <INDENT> plt.ylabel(ylabel) <NEW_LINE> <DEDENT> if savefig is not None: <NEW_LINE> <INDENT> plt.savefig(savefig, bbox_inches='tight') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> plt.show() | Parameters
----------
dta : pandas.DataFrame
dataframe containing all columns
x_key : str
x-axis column name
y_key : str
y-axis column name
y_key_list : str[]
y-axis column names (for multiple y_key)
savefig : str
filepath to save output, else show | 625941c3046cf37aa974cd0f |
def schwefel_function(X, Y): <NEW_LINE> <INDENT> output = np.zeros(X.shape) <NEW_LINE> for i in range(len(X[0])): <NEW_LINE> <INDENT> for j in range(len(Y[0])): <NEW_LINE> <INDENT> output[i][j] = (schwefel(X[i][j], Y[i][j])) <NEW_LINE> <DEDENT> <DEDENT> return output | Generates Z-values for the schwefel function.
:param X: x values
:param Y: y values
:return: z values for schwefel function | 625941c3bd1bec0571d905f4 |
def best_model_for_generation(self, generation_name, only_finished=True): <NEW_LINE> <INDENT> if only_finished: <NEW_LINE> <INDENT> if not self.is_finished_generation(generation_name): raise RuntimeError("The generation '" + generation_name + "' is not yet finished") <NEW_LINE> <DEDENT> chi_squared_table = self.chi_squared_table_for_generation(generation_name) <NEW_LINE> best_simulation_name = chi_squared_table.best_simulation_name <NEW_LINE> parameters_table = self.parameters_table_for_generation(generation_name) <NEW_LINE> chi_squared = chi_squared_table.chi_squared_for(best_simulation_name) <NEW_LINE> parameter_values = parameters_table.parameter_values_for_simulation(best_simulation_name) <NEW_LINE> return RTModel(self.model_definition, simulation_name=best_simulation_name, chi_squared=chi_squared, free_parameter_values=parameter_values, center=self.galaxy_center) | This function ...
:param generation_name:
:param only_finished:
:return: | 625941c397e22403b379cf5f |
def to_cs(self, guide_vec): <NEW_LINE> <INDENT> from .dc_cs import CS <NEW_LINE> y_vec = self.normal.cross(guide_vec) <NEW_LINE> x_vec = self.normal.cross(y_vec).inverted() <NEW_LINE> return CS(self.origin, x_vec, y_vec) | Returns a CS aligned with this Plane, with the x-axis oriented toward the given guide Vec.
:param guide_vec: Vec that guides the orientation of the x-axis of the resulting CS.
:type p: Vec | 625941c3293b9510aa2c325d |
def clips(self): <NEW_LINE> <INDENT> return Clip.latest_from_user(self) | Gets the latest clips made by this user
:returns: Iterator of :class:`~xbox.Clip` instances | 625941c33317a56b86939c22 |
def view_list(self): <NEW_LINE> <INDENT> if self.to_do_list: <NEW_LINE> <INDENT> print('To-do list:') <NEW_LINE> for index, item in enumerate(self.to_do_list, start=1): <NEW_LINE> <INDENT> print(index, item) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print('To-do list is empty.') | Shows all items in the list. | 625941c31f037a2d8b9461c4 |
def splitCompositeSource(self,compName): <NEW_LINE> <INDENT> sv = pyLike.StringVector() <NEW_LINE> specFunc = self.logLike.splitCompositeSource(compName,sv) <NEW_LINE> l = [sv[i] for i in range(sv.size())] <NEW_LINE> return (l,specFunc) | break apart a composite source and return a tuple with
the names of new sources and the spectral function | 625941c366673b3332b92056 |
def update(self): <NEW_LINE> <INDENT> instance, valid = common.json_from_path(self._path) <NEW_LINE> self._latest = instance["link"]["latest"] <NEW_LINE> self._history = instance["link"]["history"] <NEW_LINE> self._moments = instance["link"]["moments"] <NEW_LINE> self._relations = instance["link"]["relations"] <NEW_LINE> self._count = instance["link"]["count"] | Calls the rest api and updates the instance attributes | 625941c30c0af96317bb81ad |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.