code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def isdone(node_dict): <NEW_LINE> <INDENT> zdiff = depth_target - node_dict['pn'].depth <NEW_LINE> return abs(zdiff) < abs(tol)
Are we at desired depth?
625941eeff9c53063f47c745
def twoSum(self, nums, target): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for i, num in enumerate(nums): <NEW_LINE> <INDENT> x = target - num <NEW_LINE> if x in d: <NEW_LINE> <INDENT> return d[x], i <NEW_LINE> <DEDENT> d[num] = i <NEW_LINE> <DEDENT> d = {} <NEW_LINE> for i, num in enumerate(nums): <NEW_LINE> <INDENT> if nu...
:type nums: List[int] :type target: int :rtype: List[int]
625941eeb545ff76a891436a
def syslog_err(msg): <NEW_LINE> <INDENT> for message in msg.split('\n'): <NEW_LINE> <INDENT> if message: <NEW_LINE> <INDENT> syslog.syslog(syslog.LOG_ERR, 'vs_resource_backend: %s' % message)
Logs msg to syslog.
625941ee7b180e01f3dc4d46
def test_update_record_contains_invalid(self): <NEW_LINE> <INDENT> library = create_library(get_random_name(), 2) <NEW_LINE> sample = create_sample(get_random_name(), 2) <NEW_LINE> index_type = IndexType(name=get_random_name()) <NEW_LINE> index_type.save() <NEW_LINE> response = self.client.post('/api/index_generator/ed...
Ensure update library/sample containing invalid objects behaves correctly.
625941ee851cf427c661aa5f
def get_parents_for(self, container): <NEW_LINE> <INDENT> if IStorageFacility.providedBy(container): <NEW_LINE> <INDENT> return [container] <NEW_LINE> <DEDENT> def predicate(obj): <NEW_LINE> <INDENT> return IStorageFacility.providedBy(obj) <NEW_LINE> <DEDENT> return get_parents(container, predicate=predicate)
Get the parent objects for the container
625941eefb3f5b602dac3bee
def get_metrics( self, day, aws_conn_id=DEFAULT_AWS_CONN_ID, region_name=None, metrics=None): <NEW_LINE> <INDENT> aws_hook = AwsHook(aws_conn_id) <NEW_LINE> region_name = region_name or aws_hook.get_session().region_name <NEW_LINE> if not day or (isinstance(day, str) and day.lower() == 'yesterday'): <NEW_LINE> <INDENT>...
Get the metrics :param day: Date to be exported as string in YYYY-MM-DD format or date/datetime instance (default: yesterday) :type day: str, date or datetime :param aws_conn_id: AWS connection id (default: aws_default) :type aws_conn_id: str :param region_name: AWS Region :type r...
625941ee596a89723608a00e
def first_bad_version(n): <NEW_LINE> <INDENT> start = 1 <NEW_LINE> end = n <NEW_LINE> last_bad = None <NEW_LINE> while start <= end: <NEW_LINE> <INDENT> mid_point = (start + end) // 2 <NEW_LINE> if isBadVersion(mid_point): <NEW_LINE> <INDENT> last_bad = mid_point <NEW_LINE> end = mid_point - 1 <NEW_LINE> <DEDENT> else:...
Given a function whose calls are to be limited, identify the first bad version
625941ee0a50d4780f6673ec
@transaction.atomic <NEW_LINE> def delete_dataset_entry(dataset_id: int) -> Optional[DatasetInfoDTO]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dataset = Dataset.objects.get(pk=dataset_id) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> dataset.delete() <NEW_LINE> i...
Delete selected dataset
625941eead47b63b2c50a4d4
def check_can_live_migrate_destination(self, context, instance, src_compute_info, dst_compute_info, block_migration=False, disk_over_commit=False): <NEW_LINE> <INDENT> disk_available_gb = dst_compute_info['disk_available_least'] <NEW_LINE> disk_available_mb = ( (disk_available_gb * units.Ki) - CONF.reserved_host_disk_m...
Check if it is possible to execute live migration. This runs checks on the destination host, and then calls back to the source host to check the results. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance :param block_migration: if true, prepare for block migration :param disk_over_c...
625941ee5fc7496912cc3ed2
def write_simple_superlog(self): <NEW_LINE> <INDENT> superlog = open(self.tmpsuperlog, 'w') <NEW_LINE> e1 = str('''{"dependent_labels": [], "start_dpid": 8, "class": "LinkFailure",''' ''' "start_port_no": 3, "end_dpid": 15, "end_port_no": 2, "label": "e1", "time": [0,0], "round": 0}''') <NEW_LINE> superlog.write(e1 + '...
Returns the file. Make sure to close afterwards!
625941ee956e5f7376d713c0
def __init__(self, *sub_distributions, num_experts=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.sub_distributions = [] <NEW_LINE> if len(sub_distributions) == 0: <NEW_LINE> <INDENT> sub_distributions = ["multivariate-normal"] <NEW_LINE> <DEDENT> if len(sub_distributions) == 1 and num_experts is not Non...
Args: sub_distributions (List[Union[string,Distribution]]): The type-strings or actual Distribution objects that define the n sub-distributions of this MixtureDistribution. num_experts (Optional[int]): If provided and len(`sub_distributions`) == 1, clone the given single sub_distribution `num_e...
625941eef548e778e58cdad5
def PendingUpdatesChanges(directory): <NEW_LINE> <INDENT> mani_file = None <NEW_LINE> conf = Configuration.Configuration() <NEW_LINE> try: <NEW_LINE> <INDENT> mani_file = VerifyUpdate(directory) <NEW_LINE> <DEDENT> except UpdateBusyCacheException: <NEW_LINE> <INDENT> log.debug("Cache directory %s is busy, so no update ...
Return a list (a la CheckForUpdates handler right now) of changes between the currently installed system and the downloaded contents in <directory>. If <directory>'s values are incomplete or invalid for whatever reason, return None. "Incomplete" means a necessary file for upgrading from the current system is not pres...
625941eed268445f265b53c4
def decouple_overlap(w, y): <NEW_LINE> <INDENT> n_cuts = 11 <NEW_LINE> w_c = pd.qcut(w, n_cuts, labels=False) <NEW_LINE> av_ovs = {k: np.mean(y[w_c == k]) for k in range(n_cuts)} <NEW_LINE> w_c = w_c.map(av_ovs) <NEW_LINE> y_r = y/w_c <NEW_LINE> return y_r
Decouple w and y by rescaling y according to similar w values (for a binning of w, we obtain the average overlap of the bin; we rescale all overlap values according to this)
625941eea4f1c619b28b0581
def list(self, status=None, completed=False): <NEW_LINE> <INDENT> return self._endpoint._api.todos.list(todolist=self, project=self.project_id, status=status, completed=completed)
Returns an iterable of all Todos directly under this TodoList. Use the TodoList.list_groups function to get TodoListGroups, and then call the list function on those TodoListGroups to get the Todos nested under them. :param status: set this to "archived" or "trashed" for only TodoItems that match that status :type stat...
625941ee293b9510aa2c37e5
def _scan(self): <NEW_LINE> <INDENT> return self._scan_factory.single_file( filename=self._image_file, exposure_times=self.detectorbase.parameters["TIME"], osc_start=self.detectorbase.osc_start, osc_width=self.detectorbase.deltaphi, epoch=None, )
Return the scan information for this image.
625941ee10dbd63aa1bd30f7
def view_shape_models_widget(self, n_parameters=5, parameters_bounds=(-3.0, 3.0), mode='multiple', figure_size=(7, 7)): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from menpowidgets import visualize_shape_model_2d <NEW_LINE> visualize_shape_model_2d( [sm.model for sm in self.shape_models], n_parameters=n_parameters, p...
Visualizes the shape models of the CLM object using an interactive widget. Parameters ---------- n_parameters : `int` or `list` of `int` or ``None``, optional The number of shape principal components to be used for the parameters sliders. If `int`, then the number of sliders per scale is the minimum betwee...
625941ee796e427e537b0b20
def name(self): <NEW_LINE> <INDENT> if self.__name is None: <NEW_LINE> <INDENT> return str(hash(tuple([self.address, self.user, self.env_loader] + list(frozenset(self.env_vars))))) <NEW_LINE> <DEDENT> return self.__name
Return the set machine name (self.__name) if set or generate name as hash of all relevant members. :return: Machine name as string
625941ee0a366e3fb873ed74
def create_tables(self): <NEW_LINE> <INDENT> tables = migrations.tables() <NEW_LINE> try: <NEW_LINE> <INDENT> for query in tables: <NEW_LINE> <INDENT> self.cursor.execute(query) <NEW_LINE> <DEDENT> self.connection.commit() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("Fail")
create tables in the database
625941eefbf16365ca6f6725
def counter(): <NEW_LINE> <INDENT> update = {'quarter': start.get('quarter', []) + 1} <NEW_LINE> start.update(update)
Counting quarters
625941eeb830903b967e9e5a
def lcms(*numbers): <NEW_LINE> <INDENT> return reduce(lcm, numbers)
Returns the lowest common multiple among all its arguments.
625941eed10714528d60023f
def _format(self, ans, q): <NEW_LINE> <INDENT> if 'fmt' in q: <NEW_LINE> <INDENT> fmt = q['fmt'][0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fmt = 'json' <NEW_LINE> <DEDENT> fmt = fmt.lower() <NEW_LINE> if fmt in self._formatters: <NEW_LINE> <INDENT> return (200, self._formatters[fmt](ans, q), 'application/json') ...
Returns the response tuple according to the selected format. A format is available if the method "_format_xxx" is callable. The default format is json.
625941ee0a366e3fb873ed75
def forward(speed, time=-1): <NEW_LINE> <INDENT> printDebug("In forward, speed is " + str(speed) + " and time is " + str(time), DEBUG_INFO) <NEW_LINE> speed = float(speed) <NEW_LINE> if speed < 0: <NEW_LINE> <INDENT> printDebug("In forward, speed < 0, calling backward", DEBUG_WARN) <NEW_LINE> backward(-speed, time) <NE...
Moves forward at speed for time; time is optional arguments: speed - a float between -1.0 and 1.0 time - the number of seconds to move; negative numbers will cause the robot to move without stopping returns: nothing
625941ee07f4c71912b119da
def org_notification(self, organizations_data): <NEW_LINE> <INDENT> assert organizations_data <NEW_LINE> for org in organizations_data: <NEW_LINE> <INDENT> oid = org["id"] <NEW_LINE> organization_name = org["name"] <NEW_LINE> assert oid <NEW_LINE> assert organization_name <NEW_LINE> self.gateway.organizations[oid] = or...
Processes 'org' notifications.
625941ee55399d3f05588c0d
def timer(logger=None, *func_or_func_args, **timer_kwargs): <NEW_LINE> <INDENT> def wrapped_f(f): <NEW_LINE> <INDENT> @functools.wraps(f) <NEW_LINE> def wrapped(*args, **kwargs): <NEW_LINE> <INDENT> with Timer(**timer_kwargs) as t: <NEW_LINE> <INDENT> out = f(*args, **kwargs) <NEW_LINE> <DEDENT> if logger: <NEW_LINE> <...
Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor.
625941eea219f33f34628eb7
def _set_utilized_bandwidth(self, v, load=False): <NEW_LINE> <INDENT> if hasattr(v, "_utype"): <NEW_LINE> <INDENT> v = v._utype(v) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass( v, base=utilized_bandwidth.utilized_bandwidth, is_container="container", yang_name="utilized-bandwidth", parent=self, path_hel...
Setter method for utilized_bandwidth, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/mt_isn/neighbors/neighbor/subTLVs/subTLVs/utilized_bandwidth (container) If this variable is read-only (config: false) in the source YANG file, then _...
625941ee099cdd3c635f11ae
def __init__(self, monitor_id, monitor_name): <NEW_LINE> <INDENT> self._monitor_id = monitor_id <NEW_LINE> self._monitor_name = monitor_name <NEW_LINE> self._state = None
Initialize monitor sensor.
625941ee4f6381625f114f90
def retrieveStructNum(self, structFile): <NEW_LINE> <INDENT> fileChars = list(structFile) <NEW_LINE> i = len(fileChars) - 1 <NEW_LINE> while fileChars[i] != '.': <NEW_LINE> <INDENT> i -= 1 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> structNum = int(''.join(fileChars[i + 1:])) <NEW_LINE> <DEDENT> except: <NEW_LINE> <IN...
Returns the structure number from the name of the pseudo-POSCAR file. For example, the file "vasp.000478" would return 478 as the structure number.
625941eed7e4931a7ee9e475
def draw_rect(im, cords, color=None): <NEW_LINE> <INDENT> im = im.copy() <NEW_LINE> cords = cords[:, :4] <NEW_LINE> cords = cords.reshape(-1, 4) <NEW_LINE> if not color: <NEW_LINE> <INDENT> color = [255, 255, 255] <NEW_LINE> <DEDENT> for cord in cords: <NEW_LINE> <INDENT> pt1, pt2 = (cord[0], cord[1]), (cord[2], cord[3...
Draw the rectangle on the image Parameters ---------- im : numpy.ndarray numpy image cords: numpy.ndarray Numpy array containing bounding boxes of shape `N X 4` where N is the number of bounding boxes and the bounding boxes are represented in the format `x1 y1 x2 y2` Returns ------- numpy.ndarray ...
625941ee99cbb53fe679313a
def generate_cores(family, database): <NEW_LINE> <INDENT> cores_dir = os.path.join("cores", "pumbaa") <NEW_LINE> mkdir_p(cores_dir) <NEW_LINE> with open(os.path.join(cores_dir, "Arduino.h"), "w") as fout: <NEW_LINE> <INDENT> fout.write(ARDUINO_H) <NEW_LINE> <DEDENT> pumbaa_root = os.environ["PUMBAA_ROOT"] <NEW_LINE> co...
Generate the cores directory, shared among all boards.
625941eebd1bec0571d90b84
def UserNotValidated(self, app_name, email): <NEW_LINE> <INDENT> d.errback(UserNotValidatedError(email))
User is not validated.
625941ee7cff6e4e81117edb
def cluster_data_by_sample(self): <NEW_LINE> <INDENT> Z = linkage(self.__data, method = 'average') <NEW_LINE> tree = to_tree(Z) <NEW_LINE> id_list = [] <NEW_LINE> self.__get_l2r_base_node_order(tree, id_list, self.__sample_count) <NEW_LINE> temp = np.zeros(self.__data.shape) <NEW_LINE> temp_dict = dict() <NEW_LINE> for...
Cluster the data by sample
625941ee1f037a2d8b946752
@contract_epydoc <NEW_LINE> def _pack_path_settings(path_settings): <NEW_LINE> <INDENT> assert set(path_settings.iterkeys()) <= set(('f+', 'f-')), repr(path_settings) <NEW_LINE> new_settings = dict(path_settings) <NEW_LINE> _pack_filters = lambda filters: (['all'] if 'all' in filters else filters) <NEW_LINE> ...
Given all the path-specific settings, pack it into a more compact form to store in the DB. @type path_settings: dict @rtype: dict
625941ee26238365f5f0f3cb
def stage_input(self, id): <NEW_LINE> <INDENT> found = None <NEW_LINE> if self.requirements: <NEW_LINE> <INDENT> for r in self.requirements: <NEW_LINE> <INDENT> if r.class_ == 'InitialWorkDirRequirement': <NEW_LINE> <INDENT> found = r <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> stage = '$(inputs.{})'.format(...
Stages input file specified by its ``id`` into current working dir. :param id: input file id
625941ee236d856c2ad44d38
def convert_param_to_numpy(param, no_atoms): <NEW_LINE> <INDENT> if isinstance(param, RandomDistribution): <NEW_LINE> <INDENT> param_value = param.next(n=no_atoms) <NEW_LINE> if hasattr(param_value, '__iter__'): <NEW_LINE> <INDENT> return numpy.array(param_value, dtype="float") <NEW_LINE> <DEDENT> return numpy.array([p...
Convert parameters into numpy arrays. :param param: the param to convert :type param: ~pyNN.random.NumpyRNG or int or float or list(int) or list(float) or ~numpy.ndarray :param int no_atoms: the number of atoms available for conversion of param :return: the converted param as an array of floats :rtype: ~numpy.ndar...
625941ee925a0f43d254a3d2
def __init__(self, request_url, client, options): <NEW_LINE> <INDENT> super(ThumbnailSetRequest, self).__init__(request_url, client, options)
Constructs a new ThumbnailSetRequest. Args: request_url (str): The url to perform the ThumbnailSetRequest on client (:class:`GraphClient<microsoft.msgraph.request.graph_client.GraphClient>`): The client which will be used for the request options (list of :class:`Option<microsoft.msgraph.opt...
625941ee1b99ca400220b009
def includeme(config): <NEW_LINE> <INDENT> def add_json_view(obj, **kw): <NEW_LINE> <INDENT> kw['renderer'] = 'json' <NEW_LINE> kw['xhr'] = True <NEW_LINE> kw.setdefault('permission', 'edit_competence') <NEW_LINE> config.add_view(obj, **kw) <NEW_LINE> <DEDENT> add_routes(config) <NEW_LINE> config.add_view( competence_i...
Pyramid's inclusion mechanism
625941eebaa26c4b54cb1670
def send(self, evt: Any) -> None: <NEW_LINE> <INDENT> self.logger.log(self.logger.level, str(evt))
Sends the supplied event. Strictly, anything can be an event. It is the responsibility of the event being sent to be appropriately serializable.
625941ee4e696a04525c99a3
def write_to_temp_file(iterable, path): <NEW_LINE> <INDENT> with open(path, 'w', encoding='utf-8') as file_handle: <NEW_LINE> <INDENT> for each in iterable: <NEW_LINE> <INDENT> file_handle.write(each + "\n") <NEW_LINE> <DEDENT> <DEDENT> return path
Write iterable to temporary file, an item per line. :param iterable: list or tuples of contents to write to file :param path: absolute path to file. We use a tempdir as parent. :return: path to temporary file
625941ee9f2886367277addf
def flatten(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> left = root.left <NEW_LINE> right = root.right <NEW_LINE> self.pre.left = None <NEW_LINE> self.pre.right = root <NEW_LINE> self.pre = root <NEW_LINE> self.flatten(left) <NEW_LINE> self.flatten(right)
:type root: TreeNode :rtype: void Do not return anything, modify root in-place instead.
625941ee379a373c97cfb09d
def __init__(self, object_count=0, init_function=None): <NEW_LINE> <INDENT> self.queue = [] <NEW_LINE> self.objects_in_pool = 0 <NEW_LINE> self.active_objects = 0 <NEW_LINE> self.init_function = init_function <NEW_LINE> for i in range(object_count): <NEW_LINE> <INDENT> self.__init_object()
object_count is the number of objects we want to store in our pool. init_function is an optional delegate that specifies how the object should be inited. init_function should return the type of object that we want to use.
625941eed164cc61757832a5
def searchMatrix(self, matrix, target): <NEW_LINE> <INDENT> M, N = len(matrix), len(matrix[0]) <NEW_LINE> if M == 0 or N == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> i,j = 0, N-1 <NEW_LINE> while i<=M-1 and j>=0: <NEW_LINE> <INDENT> if matrix[i][j] == target: <NEW_LINE> <INDENT> return True <NEW_LINE> <DE...
:type matrix: List[List[int]] :type target: int :rtype: bool
625941eee64d504609d74d96
def run_context_simulation(id, contexts, utterances, meanings, p_utterances, n_true): <NEW_LINE> <INDENT> matrices = generate_all_boolean_matrices(len(utterances), len(meanings), n_true) <NEW_LINE> matrices = [(idxs, m) for idxs, m in matrices if all_meanings_available_filter(m)] <NEW_LINE> all_languages = [] <NEW_LINE...
Run a simulation over language instantiations with context. Note that p_meanings is not expicitly passed because we defined p(m|c) instead of just p(m) \sum_c p(c) * \sum_{u,m}S(u|m)p(m|c)*log[L(m|u,c)p(u)p(c)] = E_c[CE(S,L)] Parameters ---------- id: int Simulation id for logging. contexts: array of str C...
625941ee7c178a314d6ef9be
def get_constraint_value(self): <NEW_LINE> <INDENT> if self.data is None: <NEW_LINE> <INDENT> LOGGER.warn("data must be computed first using 'compute_data' method.") <NEW_LINE> return {} <NEW_LINE> <DEDENT> distances = self._get_constraint_value() <NEW_LINE> output = {} <NEW_LINE> for idx, pair in enumerate(self.__type...
Get constraint's formatted dictionary data. :Returns: #. data (dictionary): Formatted dictionary data. Keys are type pairs and values constraint data.
625941ee796e427e537b0b21
@app.task(track_started=True) <NEW_LINE> def calculate_md5_hash(url, email_to=''): <NEW_LINE> <INDENT> logger.info("Start to process: %s", url) <NEW_LINE> if not url: <NEW_LINE> <INDENT> raise ValueError(f'Bad url `{url}`') <NEW_LINE> <DEDENT> hash_processor = MD5HashProcessor() <NEW_LINE> hash_value = hash_processor.g...
Celery-task for calculating hash
625941ee3d592f4c4ed1d5b4
def _GetBinaryDirectoryFilename(filename): <NEW_LINE> <INDENT> for bindir in ['bin', 'bazel-bin']: <NEW_LINE> <INDENT> bindir_sep = bindir + os.sep <NEW_LINE> if filename.startswith(bindir_sep): <NEW_LINE> <INDENT> filename = filename[len(bindir_sep):] <NEW_LINE> return bindir, filename <NEW_LINE> <DEDENT> <DEDENT> for...
Find a match for the binary filename and its path. If the binary directory isn't known, search the program's filename for a binary directory. Args: filename: The name of the binary file. Returns: A tuple of the binary directory, and the filename relative to that directory. If the binary directory isn't known...
625941ee63d6d428bbe44a47
def p_convertdist(p): <NEW_LINE> <INDENT> if len(p) == 9: <NEW_LINE> <INDENT> p[0] = Node("convertdist", [p[3], p[5], p[7]], None, "convertdist(%s, %s, %s)") <NEW_LINE> <DEDENT> elif len(p) == 7: <NEW_LINE> <INDENT> p[0] = Node("convertdist", [p[3], p[5]], None, "convertdist(%s, %s)")
convertdist : CONVERTDIST LPAREN atom COMMA atom COMMA atom RPAREN | CONVERTDIST LPAREN atom COMMA atom RPAREN
625941eecc0a2c11143dd3e8
def setup_menu_course_list(self,courses): <NEW_LINE> <INDENT> center_x = MARGIN_WIDTH/2 <NEW_LINE> center_y = MARGIN_HEIGHT/2 <NEW_LINE> self.menu_exit = buttons.Button(center_x,center_y,imageFilename="data/close_icon.png",imageScale=EXIT_BUTTON_SCALING) <NEW_LINE> center_x = 0.5*SCREEN_WIDTH <NEW_LINE> center_y = SCRE...
Set's up buttons in main menu.
625941ee07f4c71912b119db
def get_interface(self, uuid): <NEW_LINE> <INDENT> return self._execute_interface_request( lambda: self.client.interface.get(uuid))
Sends a request to the vswitch requesting the attributes of a interface object instance.
625941ee7d43ff24873a31fb
def data_path(self, file_id) -> dict: <NEW_LINE> <INDENT> file_attributes = self._manifest.data_file_attributes(file_id) <NEW_LINE> exists = self._file_exists(file_attributes) <NEW_LINE> local_path = file_attributes.local_path <NEW_LINE> output = {'local_path': local_path, 'exists': exists, 'file_attributes': file_attr...
Return the local path to a data file, and test for the file's existence Parameters ---------- file_id: The unique identifier of the file to be accessed Returns ------- dict 'local_path' will be a pathlib.Path pointing to the file's location 'exists' will be a boolean indicating if the file exists in...
625941ee5fdd1c0f98dc078c
def integer_programming_solver(puzzle: NumberMindPuzzle, persist=False, max_sol_count=2, verbose=True): <NEW_LINE> <INDENT> solver = pywraplp.Solver('SolveIntegerProblem', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) <NEW_LINE> n = puzzle.length <NEW_LINE> vars_array = [] <NEW_LINE> vars_list = [] <NEW_LINE> for a in...
Solves a number-mind puzzle using mixed-integer programming from Google's OR tools. :param puzzle: A number-mind puzzle object :param persist: Whether the solver should continue finding additional solutions after finding one :param max_sol_count: The maximum number of solutions to find before stopping. 2 is a useful de...
625941eea219f33f34628eb8
@task <NEW_LINE> @roles('web') <NEW_LINE> def collectstatic(): <NEW_LINE> <INDENT> with cd(env.project_src_dir): <NEW_LINE> <INDENT> dj('collectstatic --noinput') <NEW_LINE> <DEDENT> with cd('{static_dir}'.format(**env)): <NEW_LINE> <INDENT> fix_permissions()
Collect static files from apps and other locations in a single location.
625941eefb3f5b602dac3bef
def layer_embedding(self): <NEW_LINE> <INDENT> with tf.variable_scope('embeddings'): <NEW_LINE> <INDENT> self.word_mat = tf.get_variable( 'word_embeddings', shape=[self.vocab.word_size(), self.vocab.word_embed_dim], initializer=tf.constant_initializer(self.vocab.word_embeddings), trainable=False) <NEW_LINE> self.char_m...
Layer embedding Default fuse word and char embeddings
625941ee67a9b606de4a840d
def channel_shuffle(x, group_num): <NEW_LINE> <INDENT> if group_num == 1: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> B, C, H, W = x.shape <NEW_LINE> x = tensor.reshape(x, (B, group_num, C//group_num, H, W)) <NEW_LINE> x = x.dimshuffle(0, 2, 1, 3, 4) <NEW_LINE> x = tensor.reshape(x, (B, -1, H, W)) <NEW_LINE> retur...
Pseudo shuffle channel by dimshuffle & reshape, first introduced in [ShuffleNet](https://arxiv.org/abs/1610.02357) :param x: (B, C, H, W) :param group_num: int scalar, C must be divisible by group_num :return:
625941ee15fb5d323cde106e
def set_company_carrier_name(self, carrier_name_prefix): <NEW_LINE> <INDENT> is_set = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.logger.info('Start: set company carrier name') <NEW_LINE> self._carrier_page.set_company_carrier_name(carrier_name_prefix) <NEW_LINE> is_set = True <NEW_LINE> <DEDENT> except WebDriverExce...
Returning set company carrier name Implementing logging for set company carrier name functionality :param carrier_name_prefix: :return: True/False
625941ee5166f23b2e1a56af
def test_product_installed(self): <NEW_LINE> <INDENT> self.assertTrue(self.installer.isProductInstalled( 'bgetem.hautschutz'))
Test if bgetem.hautschutz is installed.
625941ee656771135c3ebdcc
def test_skip_gram_sample_skips_2(self): <NEW_LINE> <INDENT> input_tensor = constant_op.constant( [b"the", b"quick", b"brown", b"fox", b"jumps"]) <NEW_LINE> tokens, labels = text.skip_gram_sample( input_tensor, min_skips=2, max_skips=2) <NEW_LINE> expected_tokens, expected_labels = self._split_tokens_labels([ (b"the", ...
Tests skip-gram with min_skips = max_skips = 2.
625941ee4527f215b584c9a8
def assemble_frags(decoded_frags): <NEW_LINE> <INDENT> decoded_frags_lengths = [len(frag) for frag in decoded_frags] <NEW_LINE> fixed_substring_len = Counter(decoded_frags_lengths).most_common(1)[0][0] <NEW_LINE> first_assemble = True <NEW_LINE> while first_assemble: <NEW_LINE> <INDENT> no_matches_info = [] <NEW_LINE> ...
Description: Used to reassemble a text file that has been fragmented into a series of fixed length substrings which are guaranteed to overlap by at least 3 characters and not to be identical. The final fragment is likely to have less characters than the other substrings. The order of the fragments can also be shuffled....
625941ee01c39578d7e75392
@log <NEW_LINE> @get_user <NEW_LINE> def display_album_formats(update: Update, context: CallbackContext) -> int: <NEW_LINE> <INDENT> language = context.user_data["bot_lang"] <NEW_LINE> msg = context.bot_data["texts"][language]["display_album_formats"] <NEW_LINE> chat_id = update.effective_chat.id <NEW_LINE> if update.c...
Displays available formats to get album lyrics
625941ee167d2b6e312190eb
def test_cleanlines(self): <NEW_LINE> <INDENT> words = lex.cleanlines(self.path) <NEW_LINE> self.assertEqual(len(words), 4) <NEW_LINE> self.assertEqual(words[0], u'word1') <NEW_LINE> self.assertEqual(words[1], u'word2') <NEW_LINE> self.assertEqual(words[2], u'αχιλλεύς') <NEW_LINE> self.assertEqual(words[3], u'αχιλλεύ...
Test the cleanline function.
625941eea4f1c619b28b0582
def min_val(to_evaluate): <NEW_LINE> <INDENT> if '[' in to_evaluate or ']' in to_evaluate: <NEW_LINE> <INDENT> raise SyntaxError(b'ERR: SYNTAX') <NEW_LINE> <DEDENT> to_evaluate = to_evaluate.split(',') <NEW_LINE> return str(min([float(x) for x in to_evaluate]))
Accepts any number of inputs and returns the one number that has the lowest value.
625941ee66656f66f7cbc703
def affichage_init(plateau, THEME = {}) : <NEW_LINE> <INDENT> l=plateau.Jeu.largeur <NEW_LINE> h=plateau.Jeu.hauteur <NEW_LINE> liste_cases = [] <NEW_LINE> principal = Frame() <NEW_LINE> graphical_grid=[[0 for j in range(l)]for i in range(h) ] <NEW_LINE> for i in range(h) : <NEW_LINE> <INDENT> for j in range(l) : <NEW_...
Returns a Tkinter widget in which the game is displayed with THEME
625941ee377c676e912726fd
def xml_attribute_removed(self, attr_node): <NEW_LINE> <INDENT> return
called after the attribute has been removed `self.xml_attributes`
625941ee1f037a2d8b946753
def reverseKGroup(self, head, k): <NEW_LINE> <INDENT> if head == None or k == 1: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> curr = head <NEW_LINE> count = 0 <NEW_LINE> while curr != None and count < k: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> curr = curr.next <NEW_LINE> <DEDENT> if count == k: <NEW_LINE> <IND...
:type head: ListNode :type k: int :rtype: ListNode
625941eec432627299f051a0
def _prune_control_edges_of_debug_ops(self, device_name): <NEW_LINE> <INDENT> for node in self._node_ctrl_inputs[device_name]: <NEW_LINE> <INDENT> ctrl_inputs = self._node_ctrl_inputs[device_name][node] <NEW_LINE> debug_op_inputs = [] <NEW_LINE> for ctrl_inp in ctrl_inputs: <NEW_LINE> <INDENT> if is_debug_node(ctrl_inp...
Prune control edges related to the debug ops.
625941ee3346ee7daa2b32c7
def center_small_inscrit(cercleA,cercleB,cercleC): <NEW_LINE> <INDENT> k1=1/(cercle.get_radius(cercleA)) <NEW_LINE> k2=1/(cercle.get_radius(cercleB)) <NEW_LINE> k3=(1/(cercle.get_radius(cercleC))) <NEW_LINE> z1=pointplan.coord_to_complex(cercle.get_center(cercleA)) <NEW_LINE> z2=pointplan.coord_to_complex(cercle.get_ce...
return a center of small circle when two circles it are inscribed and tangent together . :param cercleA: it is a circle :type cercleA: a circle :param cercleB: it is a circle :type cercleB: a circle :param cercleC: it is a circle :type cercleC: a circle :return: a center (with coord) of small circle when two circles ...
625941ee4f88993c3716c5b8
def test_scrubber_handles_swift_missing(self): <NEW_LINE> <INDENT> config_path = os.environ.get('GLANCE_TEST_SWIFT_CONF') <NEW_LINE> if not config_path: <NEW_LINE> <INDENT> msg = "GLANCE_TEST_SWIFT_CONF environ not set." <NEW_LINE> self.skipTest(msg) <NEW_LINE> <DEDENT> raw_config = read_config(config_path) <NEW_LINE> ...
Test that the scrubber handles the case where the image to be scrubbed is missing from swift
625941eee1aae11d1e74a213
def kerja(self, jam_kerja): <NEW_LINE> <INDENT> pass
Panggil fungsi tambah_jam_kerja milik parent class untuk menambah jam kerja pegawai, lalu cetak sesuai format
625941ee16aa5153ce3629cf
def CopyConstructor(self, other): <NEW_LINE> <INDENT> self._data = {} <NEW_LINE> for name, (obj, serialized, t_info) in iteritems(other.GetRawData()): <NEW_LINE> <INDENT> if serialized is None: <NEW_LINE> <INDENT> serialized = t_info.ConvertToWireFormat(obj) <NEW_LINE> <DEDENT> self._data[name] = (None, serialized, t_i...
Efficiently copy from other into this object. Basic RDFStruct objects are fully represented by their internal raw data. We can easily copy it by simply making a direct copy of the wire format of each field, and not preserving the python format. On access in the copy the field will be re-parsed into a python object. A...
625941eed4950a0f3b08c89e
def db_value(self, value: Enum) -> Optional[str]: <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return value.name if self.use_name else value.value
Coerce enumeration value for database.
625941eea05bb46b383ecd73
def test_position_after_end(self, client, root): <NEW_LINE> <INDENT> c1 = root.add("c1", position=100) <NEW_LINE> c2 = root.add("c2", position=101) <NEW_LINE> c3 = root.add("c3", after=c2) <NEW_LINE> children = list(root.children()) <NEW_LINE> assert children == [c1, c2, c3] <NEW_LINE> assert children[0].position < chi...
insert a node at the end
625941ee3cc13d1c6d3c78ce
def AddPolyline(points, replace_id=None): <NEW_LINE> <INDENT> return rc
Adds a polyline curve to the current model Parameters: points = list of 3D points. Duplicate, consecutive points will be removed. The list must contain at least two points. If the list contains less than four points, then the first point and last point must be different. replace_id[...
625941ee26068e7796caf23e
@route(bp, '/<group_id>/delete') <NEW_LINE> def delete(group_id): <NEW_LINE> <INDENT> _groups.delete(_groups.get_or_404(group_id)) <NEW_LINE> return None, 204
Deletes a group. Returns a 204 response.
625941ee7b180e01f3dc4d48
def test_format_static_locale_params(self): <NEW_LINE> <INDENT> pod = _mock_pod(podspec={ 'root': 'root_path', }) <NEW_LINE> path_format = grow_path_format.PathFormat(pod) <NEW_LINE> self.assertEquals( '/root_path/test/:locale', path_format.format_static( '/{root}/test/{locale}', locale='es', parameterize=True))
Test doc paths with locale and keeping params.
625941ee8e7ae83300e4b525
def setObjective(self, reactionName, objectiveCoefficient, objective_sense='maximize', temporary=False): <NEW_LINE> <INDENT> if self.objective_sense and self.objective_sense != objective_sense: <NEW_LINE> <INDENT> print('Adding an objective function with different sense, inverting objective coefficient') <NEW_LINE> obj...
Set the objective in the cobra model More reactions can be added as objectives
625941ee627d3e7fe0d693a8
def get_package_remote_version(self, package_name): <NEW_LINE> <INDENT> with settings(warn_only=True): <NEW_LINE> <INDENT> result = self.execute("pip freeze | tr '[A-Z]' '[a-z]' | grep %s" % package_name.lower(), stdout=False, sudo=self.use_sudo) <NEW_LINE> if result: <NEW_LINE> <INDENT> package, version = result.split...
Returns the version of the package currently installed via PIP in the remote server. If package is not installed, returns :data:`None`. :param package_name: Name of the package to verify :type package_name: :class:`str` :return: The package version. :rtype: :class:`str` Example: :: class MySampleRole(Role): ...
625941ee6fb2d068a760f5fd
def test_workflow_transition_execute_view_no_access(self): <NEW_LINE> <INDENT> response = self._request_test_workflow_transition_execute_view() <NEW_LINE> self.assertEqual(response.status_code, 404) <NEW_LINE> self.assertEqual( self.test_workflow_instance.get_current_state(), self.test_workflow_state_1 )
Test transitioning a workflow without the transition workflow permission.
625941eee5267d203edce1ed
def test_unallowed_transition(self): <NEW_LINE> <INDENT> self.message.status = self.message.SENT <NEW_LINE> with self.assertRaises(django_fsm.TransitionNotAllowed): <NEW_LINE> <INDENT> self.message.save()
NEW -> SENT
625941ee4c3428357757c87b
def _checkForDuplicates(self, paths): <NEW_LINE> <INDENT> existingPaths = list(getNamespaces(paths=paths).values(Namespace.path)) <NEW_LINE> if existingPaths: <NEW_LINE> <INDENT> raise DuplicatePathError( 'Paths already exist: %s' % ', '.join(existingPaths))
Make sure L{Namespace} or L{Tag} paths don't exist before trying to create new namespaces. @param values: A sequence of C{(path, description)} 2-tuples. @raises DuplicatePathError: Raised if the path for a new L{Namespace} collides with an existing one.
625941ee187af65679ca5677
def get_parameters(self, *args, **kwargs): <NEW_LINE> <INDENT> return { 'InvalidParameters': [], 'Parameters': [ { "Type": "String", "Name": "my_param", "Value": "abc123", "Version": 1 }, ], }
Mock method
625941eeeab8aa0e5d26e0b1
def masked_tensor(tensor0, tensor1, mask): <NEW_LINE> <INDENT> s = tensor0.size() <NEW_LINE> assert s[0] == mask.size()[0] <NEW_LINE> m = mask <NEW_LINE> for i in range(len(s) - 1): <NEW_LINE> <INDENT> m = mask.unsqueeze(-1) <NEW_LINE> <DEDENT> m = m.repeat(1, *s[1:]) <NEW_LINE> m = m.float() <NEW_LINE> out = ((1.0 - m...
Compute a tensor by combining two tensors with a mask :param tensor0: a Bx(N) tensor :type tensor0: torch.Tensor :param tensor1: a Bx(N) tensor :type tensor1: torch.Tensor :param mask: a B tensor :type mask: torch.Tensor :return: (1-m) * tensor 0 + m *tensor1 (averafging is made ine by line) :rtype: tensor0.dtype
625941ee63f4b57ef0001660
def getLong(value): <NEW_LINE> <INDENT> return long(value)
Get the long.
625941eef548e778e58cdad7
def Require(condition): <NEW_LINE> <INDENT> if not condition: <NEW_LINE> <INDENT> Revert() <NEW_LINE> <DEDENT> return True
If condition is not satisfied, return false :param condition: required condition :return: True or false
625941ee21bff66bcd684ea4
def clear(self): <NEW_LINE> <INDENT> self.head = self.last = None <NEW_LINE> self.size = 0
将队列清空
625941ee8c3a873295158918
def rate(event, time, mass, flux, JFC, HTC): <NEW_LINE> <INDENT> lat = event['lat'] <NEW_LINE> lon = event['lon'] <NEW_LINE> p = event['p'] <NEW_LINE> modelind = 0 <NEW_LINE> SA = 10.64009356 <NEW_LINE> for model in [JFC, HTC]: <NEW_LINE> <INDENT> if modelind == 0: <NEW_LINE> <INDENT> mod = 'JFC' <NEW_LINE> <DEDENT> el...
infer rates for impact events for all MCMC data THIS RUNS LIKE LITERAL MOLASSES A BETTER SEARCH TOOL IS DEFINITELY NEEDED EITHER TRY BINARY SEARCH OR FIT A BETTER CURVE TO APPROX THE INITIAL INDEX GUESS
625941eecad5886f8bd2752f
def end(self): <NEW_LINE> <INDENT> LOG.info('Done with creating code reference') <NEW_LINE> os.chdir(self.orgWorkingDir)
Make sure we are back in the original working directory.
625941ee23e79379d52eeab4
def _show_item(self, library_id, item_id): <NEW_LINE> <INDENT> url = '/'.join((self._make_url(library_id, contents=True), item_id)) <NEW_LINE> return self._get(url=url)
Get details about a given library item.
625941ee293b9510aa2c37e7
def _ContainsExactlyElementsIn(self, expected, warn_elements_in=False): <NEW_LINE> <INDENT> if not expected: <NEW_LINE> <INDENT> if self._actual: <NEW_LINE> <INDENT> self._FailWithProposition('is empty') <NEW_LINE> <DEDENT> return _InOrder() <NEW_LINE> <DEDENT> missing = _DuplicateCounter() <NEW_LINE> extra = _Duplicat...
Determines if the subject contains exactly the expected elements. Helper function for ContainsExactly() and ContainsExactlyElementsIn(). Args: expected: iterable of objects that should be contained in the subject. warn_elements_in: boolean, default False. If True, and the assertion fails, and the developer ...
625941ee099cdd3c635f11af
def deleteCteFilter(self, cte_filter_id): <NEW_LINE> <INDENT> return self._sendRequest('DELETE', '/api/cte_filters/' + str(cte_filter_id), None, False)
deleteCteFilter : Remove a CTE filter. Sample usage:
625941ee167d2b6e312190ec
def get_node_dict(graph, attr): <NEW_LINE> <INDENT> return {k: v[attr] for k, v in graph.nodes.items()}
Return a `dict` of node:attribute pairs from a graph.
625941eefbf16365ca6f6726
def format(self, record): <NEW_LINE> <INDENT> if isinstance(record.msg, dict): <NEW_LINE> <INDENT> message_dict = record.msg <NEW_LINE> record.message = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message_dict = {} <NEW_LINE> record.message = record.getMessage() <NEW_LINE> <DEDENT> if "asctime" in self.requiredF...
Formats a log record and serializes to json
625941ee0a366e3fb873ed77
def pgbouncer_up(): <NEW_LINE> <INDENT> sudo('/etc/init.d/pgbouncer start')
Start pgpool.
625941ee4527f215b584c9a9
def make_module_extra(self): <NEW_LINE> <INDENT> txt = super(EB_Xmipp, self).make_module_extra() <NEW_LINE> txt += self.module_generator.set_environment('XMIPP_HOME', self.installdir) <NEW_LINE> return txt
Define Xmipp specific variables in generated module file, i.e. XMIPP_HOME.
625941ee2c8b7c6e89b35d13
def init_lstm_layer(params, nin, ndim, options, prefix='lstm'): <NEW_LINE> <INDENT> params[prefix + '_w_x'] = init_weight(nin, 4 * ndim, options) <NEW_LINE> if options['init_lstm_svd']: <NEW_LINE> <INDENT> params[prefix + '_w_h'] = np.concatenate([ortho_weight(ndim), ortho_weight(ndim), ortho_weight(ndim), ortho_weight...
initializt lstm layer
625941ee07f4c71912b119dc
def validate(self, value): <NEW_LINE> <INDENT> for validate in self._validators: <NEW_LINE> <INDENT> validate(value)
Validate that the given value matches the column's requirements. Raise a ValueError only if the given value was invalid.
625941ee7d847024c06be818
def on_check_condition(self): <NEW_LINE> <INDENT> model = self.widget.get_model() <NEW_LINE> if not model: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> curiter = self.condition_widget.get_active_iter() <NEW_LINE> format = self.condition_widget.get_model().get_value(curiter, 0) <NEW_LINE> formatinfo = transcoder...
Specifies the condition to meet :returns: Whether the condition is met or not :rtype: bool
625941eed8ef3951e3243a95
def parse_instance_info(node): <NEW_LINE> <INDENT> info = node.instance_info <NEW_LINE> i_info = {} <NEW_LINE> i_info['image_source'] = info.get('image_source') <NEW_LINE> iwdi = node.driver_internal_info.get('is_whole_disk_image') <NEW_LINE> if not iwdi: <NEW_LINE> <INDENT> if (i_info['image_source'] and not service_u...
Gets the instance specific Node deployment info. This method validates whether the 'instance_info' property of the supplied node contains the required information for this driver to deploy images to the node. :param node: a single Node. :returns: A dict with the instance_info values. :raises: MissingParameterValue, i...
625941ee627d3e7fe0d693a9
def load_word2vec_embeddings(path): <NEW_LINE> <INDENT> en_model = KeyedVectors.load_word2vec_format(path, binary=True) <NEW_LINE> embeddings_index = en_model.wv <NEW_LINE> all_embeddings = np.stack(embeddings_index.syn0) <NEW_LINE> del en_model <NEW_LINE> embedding_mean,embedding_std = all_embeddings.mean(), all_embed...
Load pretrained word2vec embeddings. Keyword arguments: path -- the path to the pretrained embeddings
625941eede87d2750b8602f0
def setup_cuda_fft_resample(n_jobs, W, new_len): <NEW_LINE> <INDENT> cuda_dict = dict(use_cuda=False, fft_plan=None, ifft_plan=None, x_fft=None, x=None, y_fft=None, y=None) <NEW_LINE> n_fft_x, n_fft_y = len(W), new_len <NEW_LINE> cuda_fft_len_x = int((n_fft_x - (n_fft_x % 2)) // 2 + 1) <NEW_LINE> cuda_fft_len_y = int((...
Set up CUDA FFT resampling Parameters ---------- n_jobs : int | str If n_jobs == 'cuda', the function will attempt to set up for CUDA FFT resampling. W : array The filtering function to be used during resampling. If n_jobs='cuda', this function will be shortened (since CUDA assumes FFTs of real sig...
625941ee099cdd3c635f11b0
def test_on_message_receive_ping(mocker): <NEW_LINE> <INDENT> connect_websocket = mocker.patch( 'gdax_websocket.websocket.GdaxWebsocket.connect_websocket') <NEW_LINE> send_message_mock = mocker.patch( 'gdax_websocket.websocket.GdaxWebsocket.send_message') <NEW_LINE> socket = GdaxWebsocket() <NEW_LINE> ping_handler = mo...
Bitmex websocket uses Primus websocket lib which uses the following heartbeat scheme: client will disconnect if not recv within `pingTimeout` primus::pong::{timestamp} +----------------------+ | | +---v----+ +---------+ | server | | clie...
625941ee004d5f362079a887
def RemoteHostCopy(self, file_path, remote_path='', copy_to=True): <NEW_LINE> <INDENT> if copy_to: <NEW_LINE> <INDENT> file_name = posixpath.basename(file_path) <NEW_LINE> src_spec, dest_spec = file_path, '%s:%s' % (self.name, file_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> remote_path, _ = self.RemoteCommand(...
Copies a file to or from the VM. Args: file_path: Local path to file. remote_path: Optional path of where to copy file on remote host. copy_to: True to copy to vm, False to copy from vm. Raises: RemoteCommandError: If there was a problem copying the file.
625941ee1f037a2d8b946754