code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_points(direction, words_left): <NEW_LINE> <INDENT> if (1 < words_left < 5): <NEW_LINE> <INDENT> return get_factor(direction) * (10 - words_left) <NEW_LINE> <DEDENT> elif (words_left == 1): <NEW_LINE> <INDENT> return get_factor(direction) * (10 - words_left) + 25 <NEW_LINE> <DEDENT> elif (words_left >= 5): <NEW_...
(str, int) -> int Precondition: direction (one of 'up', 'down', 'forward' and 'backward')
625941e5925a0f43d254a2a3
def binarymask(mask:U[str, List[int]], durs:Seq[float]=None, offset=0, cycledurs=True): <NEW_LINE> <INDENT> if durs is None: <NEW_LINE> <INDENT> durs = [1] <NEW_LINE> <DEDENT> if cycledurs: <NEW_LINE> <INDENT> durs = _itertools.cycle(durs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert len(durs) == len(mask) <NEW...
Creates a binary mask Args: mask: a mask string ('x'=1, '-'=0) or a sequence of states (a state is either 0 or 1) durs: a sequence of durations (default=[1]) Example ======= >>> mask = binarymask("x--x-x---")
625941e5fff4ab517eb2f867
def get_change(self, change_locator, **kwargs): <NEW_LINE> <INDENT> return self.serve_change(change_locator, **kwargs)
:param async_req: bool :param str change_locator: (required) :param str fields: :return: Change
625941e50383005118ecfa09
def basic_block(self): <NEW_LINE> <INDENT> self.reset_min_max() <NEW_LINE> (x, y) = self._calculate_x_y() <NEW_LINE> self.margins[2] = 0 <NEW_LINE> self.margins[3] = 0 <NEW_LINE> svg = self.new_path(x, y) <NEW_LINE> svg += self._corner(1, -1) <NEW_LINE> svg += self._do_slot() <NEW_LINE> svg += self._rline_to(self._expa...
The most common block type: used for 0, 1, 2, or 3 argument commands, stacks, et al.
625941e582261d6c526ab8ce
def _MaybeDeleteOldCheckpoints(self, meta_graph_suffix="meta"): <NEW_LINE> <INDENT> if self._checkpoints_to_be_deleted: <NEW_LINE> <INDENT> p = self._checkpoints_to_be_deleted.pop(0) <NEW_LINE> should_keep = p[1] > self._next_checkpoint_time <NEW_LINE> if should_keep: <NEW_LINE> <INDENT> self._next_checkpoint_time += (...
Deletes old checkpoints if necessary. `self._checkpoints_to_be_deleted` is going to contain checkpoints that are over `max_to_keep`. They are going to be deleted. If `keep_checkpoint_every_n_hours` was specified, keep an additional checkpoint every `N` hours. For example, if `N` is 0.5, an additional checkpoint is k...
625941e5566aa707497f498b
def nextClosestTime(self, time): <NEW_LINE> <INDENT> HH, MM = time.split(":") <NEW_LINE> hh, mm = int(HH), int(MM) <NEW_LINE> allowed = set([hh/10, hh%10, mm/10, mm%10]) <NEW_LINE> curr = hh*60 + mm <NEW_LINE> def check(t): <NEW_LINE> <INDENT> hour = t / 60 <NEW_LINE> minute = t % 60 <NEW_LINE> digits = [hour/10, hour%...
:type time: str :rtype: str Simulate the clock going forward by one minute. Each time it moves forward, if all the digits are allowed, then return the current time.
625941e5bf627c535bc135f8
def move_up(self, test): <NEW_LINE> <INDENT> self.MOTOR.move_CW()
Moves the linear actuator upwards.
625941e530c21e258bdfa8c9
def chown(self, path, uid, gid): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file_object = self.filesystem.GetObject(path) <NEW_LINE> <DEDENT> except IOError as io_error: <NEW_LINE> <INDENT> if io_error.errno == errno.ENOENT: <NEW_LINE> <INDENT> raise OSError(errno.ENOENT, 'No such file or directory in fake filesystem...
Set ownership of a faked file. Args: path: (str) Path to the file or directory. uid: (int) Numeric uid to set the file or directory to. gid: (int) Numeric gid to set the file or directory to. `None` is also allowed for `uid` and `gid`. This permits `os.rename` to use `os.chown` even when the source file `uid` ...
625941e5d6c5a10208144477
def _mask_stat_map(stat_map_img, threshold=None): <NEW_LINE> <INDENT> stat_map_img = check_niimg_3d(stat_map_img, dtype='auto') <NEW_LINE> data = _safe_get_data(stat_map_img, ensure_finite=True) <NEW_LINE> if threshold is not None: <NEW_LINE> <INDENT> data, mask, threshold = _threshold_data(data, threshold) <NEW_LINE> ...
Load a stat map and apply a threshold. Returns: mask_img, stat_map_img, data, threshold
625941e51b99ca400220aedc
def connect_JSON(config): <NEW_LINE> <INDENT> testnet = config.get('testnet', '0') <NEW_LINE> testnet = (int(testnet) > 0) <NEW_LINE> if not 'rpcport' in config: <NEW_LINE> <INDENT> config['rpcport'] = 19998 if testnet else 9998 <NEW_LINE> <DEDENT> connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpa...
Connect to a Birch Core JSON-RPC server
625941e5d18da76e23532903
def call_with_singularity(self, job, args, work_dir, outfile, errfile, check_output, tool_name, mount_list): <NEW_LINE> <INDENT> RealtimeLogger.info(truncate_msg("Singularity Run: {}".format(" | ".join(" ".join(x) for x in args)))) <NEW_LINE> start_time = timeit.default_timer() <NEW_LINE> name = tool_name if tool_name ...
Thin wrapper for singularity_call that will use internal lookup to figure out the location of the singularity file. Only exposes singularity_call parameters used so far. expect args as list of lists. if (toplevel) list has size > 1, then piping interface used
625941e55166f23b2e1a5581
def test_init(self): <NEW_LINE> <INDENT> request = BusDataRequest.BusLineListRequest('A') <NEW_LINE> self.assertFalse(request.data_fetched) <NEW_LINE> self.assertFalse(any(request.data)) <NEW_LINE> self.assertEqual(self.mock_http_get.call_count, 0)
测试初始化
625941e599cbb53fe679300e
def get_job_number(self,name): <NEW_LINE> <INDENT> qacct = self.qacct(name) <NEW_LINE> if qacct: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return qacct['jobnumber'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> qstat = self.qstat(name) <NEW_LINE> if qstat: <NEW_LINE> <IND...
Return the number assigned by the backend compute engine Attempts to fetch the job number from the .drop.qacct file; if no information can be read from .drop.qacct (e.g. job hasn't finished yet) then tries to acquire the data from the .drop.qstat file. If neither of these files exists then tries to infer the job numb...
625941e58c3a8732951587e8
def _get_all_languages_or_default_template(templates): <NEW_LINE> <INDENT> for template in templates: <NEW_LINE> <INDENT> if template.language == '': <NEW_LINE> <INDENT> return template <NEW_LINE> <DEDENT> <DEDENT> return templates[0] if templates else None
Returns the first template that isn't language specific
625941e55f7d997b87174ec4
def __edit_consequent(self, con: SimpleConstraint) -> None: <NEW_LINE> <INDENT> con, index = self.__validate_constraint(con, antecedent=False, added=True) <NEW_LINE> self.__consequent_listbox.rename_item(con, index=index) <NEW_LINE> self.__consequent.remove(self.__selected_consequent) <NEW_LINE> self.__consequent.appen...
Executed whenever an item from consequent is edited. :param con: Edited item from consequent.
625941e544b2445a339324bb
@punt.route('/') <NEW_LINE> @punt.route('/about') <NEW_LINE> def about(): <NEW_LINE> <INDENT> return render_template('about.html', title='CFDB: About')
:return: about page
625941e567a9b606de4a82df
def get_district_teams_simple(self, district_key, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_district_teams_simple_with_http_info(district_key, **kwargs)
get_district_teams_simple # noqa: E501 Gets a short-form list of `Team` objects that competed in events in the given district. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_district_teams_simple(district_key...
625941e57d847024c06be6e8
def convert_date(date): <NEW_LINE> <INDENT> strdate = date.dict['date'] <NEW_LINE> dt = parser.parse(strdate) <NEW_LINE> dtstring = str(dt.year) + '-' + str(dt.month) + '-' + str(dt.day) <NEW_LINE> return dt, dtstring
Create and apply the date from the database.
625941e5cdde0d52a9e5345e
def get_permissions (self, user, view, action, item, target=None): <NEW_LINE> <INDENT> if target is None: <NEW_LINE> <INDENT> proot = etree.Element ('permissions') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> proot = target <NEW_LINE> <DEDENT> def perm_match (perm): <NEW_LINE> <INDENT> return perm.match (user, view, a...
Returns all permission matching specified user, view, action and item as XML Optionally append result to XML node provided as "target"
625941e5a05bb46b383ecc46
def clean_nones(value): <NEW_LINE> <INDENT> if isinstance(value, list): <NEW_LINE> <INDENT> return [clean_nones(x) for x in value if x is not None] <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> return { key: clean_nones(val) for key, val in value.items() if val is not None } <NEW_LINE> <DEDENT> ...
Recursively remove all None values from dictionaries and lists, and returns the result as a new dictionary or list.
625941e5f9cc0f698b140a20
def __init__(self, nums): <NEW_LINE> <INDENT> self.original = list(nums)
:type nums: List[int] :type size: int
625941e51d351010ab855f44
def convert_np_dtype_to_dtype_(np_dtype): <NEW_LINE> <INDENT> dtype = np.dtype(np_dtype) <NEW_LINE> if dtype == np.float32: <NEW_LINE> <INDENT> return core.VarDesc.VarType.FP32 <NEW_LINE> <DEDENT> elif dtype == np.float64: <NEW_LINE> <INDENT> return core.VarDesc.VarType.FP64 <NEW_LINE> <DEDENT> elif dtype == np.float16...
Convert the data type in numpy to the data type in Paddle Args: np_dtype(np.dtype): the data type in numpy. Returns: core.VarDesc.VarType: the data type in Paddle.
625941e566673b3332b924ba
def _get_guest_numa_config(self, context, instance, flavor, allowed_cpus=None): <NEW_LINE> <INDENT> topology = self._get_host_numa_topology() <NEW_LINE> guest_cpu_numa = self._get_cpu_numa_config_from_instance( context, instance) <NEW_LINE> if not guest_cpu_numa: <NEW_LINE> <INDENT> vcpus = flavor.vcpus <NEW_LINE> memo...
Returns the config objects for the guest NUMA specs. Determines the CPUs that the guest can be pinned to if the guest specifies a cell topology and the host supports it. Constructs the libvirt XML config object representing the NUMA topology selected for the guest. Returns a tuple of: (cpu_set, guest_cpu_tune, gu...
625941e5d164cc6175783178
def refinepractical(htmltag): <NEW_LINE> <INDENT> htmltag = unicode(htmltag) <NEW_LINE> practical = getwhatisbetweenthetags(htmltag) <NEW_LINE> practical = removewhitespaces(practical) <NEW_LINE> if practical == u'Teórica' or practical == u'TeóricaVinculada': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return ...
Returns True if the course being read is practical on this offer, false otherwise
625941e5435de62698dfe076
@task <NEW_LINE> def sphinx_daemon_restart(): <NEW_LINE> <INDENT> if is_sphinx_daemon_running(): <NEW_LINE> <INDENT> sphinx_daemon_stop() <NEW_LINE> <DEDENT> sphinx_daemon_start()
Restart the search daemon.
625941e53317a56b8693a077
@add_arg_scope <NEW_LINE> def xception_module(inputs, depth_list, skip_connection_type, stride, unit_rate_list=None, rate=1, activation_fn_in_separable_conv=False, outputs_collections=None, scope=None): <NEW_LINE> <INDENT> if len(depth_list) != 3: <NEW_LINE> <INDENT> raise ValueError('Expect three elements in depth_lis...
An Xception module. The output of one Xception module is equal to the sum of `residual` and `shortcut`, where `residual` is the feature computed by three separable convolution. The `shortcut` is the feature computed by 1x1 convolution with or without striding. In some cases, the `shortcut` path could be a simple ident...
625941e5ec188e330fd5abc0
def eventlet_server(): <NEW_LINE> <INDENT> from eventlet import wsgi, api <NEW_LINE> wsgi.server(api.tcp_listener(('', settings.SERVER_PORT)), Reactor)
Run as standalone wsgi server
625941e5b545ff76a891423e
def removeServer(self, server): <NEW_LINE> <INDENT> log.info("removing server {}:{} from QEMU module".format(server.host, server.port)) <NEW_LINE> self._servers.remove(server)
Removes a server from being used by this module. :param server: WebSocketClient instance
625941e5fbf16365ca6f65f5
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_iB.pack(_x.nodeID, _x.status)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(se) <NEW_LINE> except TypeError as te: self._check_types(te)
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
625941e516aa5153ce3628a1
def get_weighted_heights_displacment(padded_z, weights, row_dis, col_dis): <NEW_LINE> <INDENT> name_scp = 'weighting_heights_row_dis_{}_col_dis_{}'.format(row_dis, col_dis) <NEW_LINE> with tf.name_scope(name_scp): <NEW_LINE> <INDENT> shape = tf.shape(weights) <NEW_LINE> sliced_z = tf.slice(padded_z, [0, row_dis, col_di...
This function itend to multiply the input_z by weights with displacemet in row and col. padding is 'same'. padded_z - tensor [None, rows + win_size, cols + win_size] weights - tensor [None, rows, cols] row_dis - integer in range(win_size) col_dis - integer in range(win_size)
625941e521a7993f00bc8120
@param_get_slice_length() <NEW_LINE> def test_get_slice_length( nominal: typing.Any, total: int, expected: typing.Any) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> received = get_slice_length(nominal, total) <NEW_LINE> <DEDENT> except ValueError as err: <NEW_LINE> <INDENT> received = check_exception(err, expec...
Test `get_slice_length` in text subpackage Arguments: nominal {float} -- exact number (int) or percentage (0 < nominal < 1) total {int} -- number of items to slice from expected {typing.Any} -- expected Exception/number of items
625941e5956e5f7376d71295
def _get_dictionary_from_path_to_json(info_path): <NEW_LINE> <INDENT> with open(info_path, 'r') as f: <NEW_LINE> <INDENT> text = f.read() <NEW_LINE> <DEDENT> return json.loads(text)
Loads a json file and returns as a dictionary
625941e5a8370b7717052cc6
def load_from_json_file(filename): <NEW_LINE> <INDENT> with open(filename, 'r') as f: <NEW_LINE> <INDENT> return (json.load(f))
Function that creates an Object from a “JSON file”
625941e59c8ee82313fbbb9f
def receive(self, receiver: Reference) -> bytes: <NEW_LINE> <INDENT> raise NotImplementedError()
Receive a message from a port this client connects to. Args: receiver: The receiving (local) port. Returns: The received message.
625941e5236d856c2ad44c09
def process_aggregation(aggregate): <NEW_LINE> <INDENT> aggregated_documents = [ agg_document for agg_document in documents if aggregate in agg_document ] <NEW_LINE> terms = defaultdict(int) <NEW_LINE> def add_agg_value(agg_value): <NEW_LINE> <INDENT> if isinstance(agg_value, list): <NEW_LINE> <INDENT> for individual_v...
Find the values for this aggregation
625941e5293b9510aa2c36bb
def __handler_branch(self, root): <NEW_LINE> <INDENT> if root.node_left != None: <NEW_LINE> <INDENT> cur_handler = self.handler_query[root.node_left.node_text] <NEW_LINE> cur_handler(root.node_left) <NEW_LINE> <DEDENT> if root.node_right != None: <NEW_LINE> <INDENT> cur_handler = self.handler_query[root.node_right.node...
Handle the meaningless branch node
625941e526068e7796caf10f
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.status is None: <NEW_LINE> <INDENT> self.status = actionlib_msgs.msg.GoalStatus() <NEW_LINE> <DEDENT> if self.result is None: <NEW_LINE> <I...
unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str``
625941e5462c4b4f79d1daf9
def solution(sequences, duration): <NEW_LINE> <INDENT> regex = re.compile( r'Step ([A-Z]) must be finished before step ([A-Z]) can begin.') <NEW_LINE> steps = {} <NEW_LINE> for line in sequences: <NEW_LINE> <INDENT> matches = regex.match(line) <NEW_LINE> before = matches.group(1) <NEW_LINE> after = matches.group(2) <NE...
Solution to part one.
625941e5507cdc57c630710d
def _state_merged(self, want, have): <NEW_LINE> <INDENT> commands = [] <NEW_LINE> for interface in want: <NEW_LINE> <INDENT> for each in have: <NEW_LINE> <INDENT> if interface['name'] == each['name']: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> commands....
The command generator when state is merged :rtype: A list :returns: the commands necessary to merge the provided into the current configuration
625941e5379a373c97cfaf70
def lines(self, count: int = 1) -> Location: <NEW_LINE> <INDENT> end = self.end.lines(count) <NEW_LINE> return Location(self.filename, self.begin, end)
Extend the current location to the COUNT next lines.
625941e5cc40096d61595d78
def whenRunning(self) -> None: <NEW_LINE> <INDENT> self._whenRunning(**self._whenRunningArguments)
Call C{self._whenRunning} with C{self._whenRunningArguments}. @note: This method is called after the reactor starts running.
625941e5f8510a7c17cf9b28
def test_reverse_complement_gives_correct_sequence(self): <NEW_LINE> <INDENT> dna_util_obj = DnaUtil(TEST_FWD_SEQ) <NEW_LINE> expected = TEST_REV_COMP_SEQ <NEW_LINE> actual = dna_util_obj.reverse_complement() <NEW_LINE> self.assertEqual(expected, actual)
Test reverse complement method with test sequences
625941e58e71fb1e9831dbd1
@jit("f8(f8[:,:],f8,f8,f8[:,:],f8[:,:],f8,f8)") <NEW_LINE> def rela_boris_velocity_kick(v, c, eff_q, E, B, dt, eff_m): <NEW_LINE> <INDENT> v /= np.sqrt(1 - (v ** 2).sum(axis=1, keepdims=True) / c ** 2) <NEW_LINE> half_force = (eff_q * 0.5 / eff_m * dt) * E <NEW_LINE> v += half_force <NEW_LINE> t = B * eff_q * dt / (2 *...
The velocity update portion of the Boris pusher. Updates the velocity in place so as to conserve memory. Parameters ---------- v : `numpy.ndarray` Array of velocities, of shape `(N, 3)`, `N` being the number of macroparticles c : `float` The speed of light eff_q : `float` The effective charge of the partic...
625941e5d58c6744b4258088
@then("I fill incorrect email format") <NEW_LINE> def step_impl(context): <NEW_LINE> <INDENT> pass
:type context: behave.runner.Context
625941e5aad79263cf390e71
def getProxy(file_name): <NEW_LINE> <INDENT> file_path = '/Users/wangjiacan/Desktop/shawn/爬取资料/ip/' + file_name + '.txt' <NEW_LINE> file = open(file_path, 'r') <NEW_LINE> lines = file.readlines() <NEW_LINE> for proxy_ip in lines: <NEW_LINE> <INDENT> url_queue.put(proxy_ip[:-1])
下载代理的ip
625941e5d8ef3951e3243967
def create_xyz_basic(self): <NEW_LINE> <INDENT> if not self.__check_array__(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.resize: <NEW_LINE> <INDENT> self.data_array_resize = cv2.resize(self.data_array, tuple(self.resize_dims), interpolation=cv2.INTER_CUBIC) <NEW_LINE> <DEDENT> self.num_scans = self.data_ar...
Generate a basic xyz array with no hold on speed, purely arbitrary distances
625941e526238365f5f0f29d
def lcr_safe_write(self, device, message): <NEW_LINE> <INDENT> logger.info(f"safe write: {device.__class__.__name__}: {message}") <NEW_LINE> device.resource.write(message) <NEW_LINE> device.resource.query("*OPC?") <NEW_LINE> self.lcr_check_error(device)
Write, wait for operation complete, test for error.
625941e5dd821e528d63b5cf
def test_show_platform_psustatus(localhost, ansible_adhoc, testbed): <NEW_LINE> <INDENT> hostname = testbed['dut'] <NEW_LINE> ans_host = ansible_host(ansible_adhoc, hostname) <NEW_LINE> logging.info("Check PSU status using '%s', hostname: %s" % (CMD_PLATFORM_PSUSTATUS, hostname)) <NEW_LINE> psu_status = ans_host.comman...
@summary: Check output of 'show platform psustatus'
625941e5de87d2750b8601c0
def test_multisurf_GWAS_Sim(): <NEW_LINE> <INDENT> options['algorithm'] = 'multisurf' <NEW_LINE> Scores = MS.runMultiSURF(header, x, y, attr, var, distArray, options) <NEW_LINE> print("MultiSURF + GWAS_Sim MF") <NEW_LINE> print(str(Scores)) <NEW_LINE> assert Scores != None <NEW_LINE> assert len(Scores) == 20 <NEW_LINE>...
Test MultiSURF on GWAS_Sim Mixed Features (Discrete and Continuous)
625941e550485f2cf553d1c5
def decrypt_header(self, header: bytes, nonce: bytes) -> bytes: <NEW_LINE> <INDENT> return chacha20(self._adkey, header, nonce, 0)
Decrypt header data
625941e524f1403a92600f8c
def point_in_bounds(bounds): <NEW_LINE> <INDENT> print("---000---") <NEW_LINE> print(bounds) <NEW_LINE> print(type(bounds)) <NEW_LINE> points = bounds_pattern.match(bounds).groups() <NEW_LINE> print("---2222---") <NEW_LINE> print(points) <NEW_LINE> print(type(points)) <NEW_LINE> print("---3333---") <NEW_LINE> return (i...
'[42,1023][126,1080]' bounds_pattern = re.compile(r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]')
625941e566673b3332b924bb
def generate(): <NEW_LINE> <INDENT> get_latest('neovim') <NEW_LINE> get_latest('vim') <NEW_LINE> tags = defaultdict(lambda: defaultdict(lambda: defaultdict(bytes))) <NEW_LINE> for target in (b'neovim', b'vim'): <NEW_LINE> <INDENT> for (version, ref, tag_date), deltas in collect(target.decode('ascii')): <NEW_LINE> <INDE...
Generate the data file for the plugin. All byte strings from here.
625941e5b57a9660fec33cb4
@container.route("/", methods=["GET"]) <NEW_LINE> def list_containers(): <NEW_LINE> <INDENT> containers = [] <NEW_LINE> images = [] <NEW_LINE> try: <NEW_LINE> <INDENT> containers = g.docker_client.containers(all=True) <NEW_LINE> images = g.docker_client.images() <NEW_LINE> for image in images: <NEW_LINE> <INDENT> image...
List containers
625941e56fb2d068a760f4cd
def binarySearch(sortedList,x): <NEW_LINE> <INDENT> sInd=0 <NEW_LINE> eInd=len(sortedList)-1 <NEW_LINE> midInd=newMidInd(sInd,eInd) <NEW_LINE> while((eInd-sInd)>1): <NEW_LINE> <INDENT> print("testing",x,sortedList[midInd],"unsearched",eInd-sInd) <NEW_LINE> if(sortedList[midInd]>x): <NEW_LINE> <INDENT> eInd=midInd <NEW_...
Perform a binary search for a given value
625941e532920d7e50b285fd
def vocab(request): <NEW_LINE> <INDENT> tmp_g = None <NEW_LINE> try: <NEW_LINE> <INDENT> tmp_g = get_vocab() <NEW_LINE> <DEDENT> except StoreConnectionError as ex: <NEW_LINE> <INDENT> LOGGING.error(ex) <NEW_LINE> return HttpResponseServerError(str(ex)) <NEW_LINE> <DEDENT> req_format = validate_mime_format(request) <NEW...
Get the chame vocab. Args: request (WSGIRequest): The request from the user
625941e56e29344779a62a3a
def weigth_to_csv(file,lst,lenth): <NEW_LINE> <INDENT> with open(file, 'a') as csvfile: <NEW_LINE> <INDENT> for i, v in enumerate(lst): <NEW_LINE> <INDENT> csvfile.write(str(v)+',') <NEW_LINE> <DEDENT> csvfile.write(str(lenth)+'\n')
将列表写入文件
625941e557b8e32f524838c7
def sw_increment_counter(_dict_key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sws.sw_storm_counter_dict[_dict_key] += 1 <NEW_LINE> msg = "stormwatch counter for %s now: %d" % (_dict_key, sws.sw_storm_counter_dict[_dict_key]) <NEW_LINE> ecomp_logger(tds.LOG_TYPE_DEBUG, tds.SEV_INFO, tds.CODE_GENERAL, msg) <NEW_LINE>...
Add to appropriate counter based on arriving trap agent and OID :Parameters: _dict_key agent address from trap PDU and notify OID trap PDU, separated by a space :Exceptions: none :Keywords: stormwatch count threshold :Variables:
625941e5287bf620b61d3e8b
def _log_http_error(self, query, req, exc): <NEW_LINE> <INDENT> self.logger.error('log_error - %s: %s', req.url, exc) <NEW_LINE> for h in sorted(exc.response.headers): <NEW_LINE> <INDENT> self.logger.info('Response header: %s: %s', h, exc.response.headers[h]) <NEW_LINE> <DEDENT> body = exc.response.text <NEW_LINE> cont...
Log :exc:`requests.exceptions.HTTPError`, converting to GraphQL's ``{"data": null, "errors": [{"message": str(exc)...}]}`` :param query: the GraphQL query that triggered the result. :type query: str :param req: :class:`requests.Request` instance that was opened. :type req: :class:`requests.Request` :param exc: :exc:...
625941e54c3428357757c74f
def hist_plot(w_F, w_R, window_F, window_R, title, outfname): <NEW_LINE> <INDENT> numWins = len(w_F.keys()) <NEW_LINE> if numWins == 40: gs = gridspec.GridSpec(8,5) <NEW_LINE> elif numWins == 20: gs = gridspec.GridSpec(5,4) <NEW_LINE> else: print("ERROR: specified number of windows is not currently supported (only 20 o...
Plot probability histogram overlap of all windows. Parameters ---------- w_F: dictionary of all the dEs for all windows going forward (key=window number) w_R: dictionary of all the dEs for all windows going backward (key=window number) Note - based on how FEP calcns are conducted with F and R, need to loop ...
625941e53617ad0b5ed68320
def evaluate_model(x_data, y_data, weight, bias): <NEW_LINE> <INDENT> y_pred = weight * x_data + bias <NEW_LINE> cost = np.mean(np.square(y_data - y_pred)) <NEW_LINE> return cost
Calculating cost using calculated weights and bias.
625941e59f2886367277acb4
@login_required <NEW_LINE> def StudentInfo(request): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> responseForm = BuildingForm(request.POST) <NEW_LINE> if responseForm.is_valid(): <NEW_LINE> <INDENT> building = Building.objects.get(name = responseForm.cleaned_data['name']) <NEW_LINE> name = respo...
Gather information about student and any roommates they might have
625941e5b5575c28eb68e42e
def read_states(filename): <NEW_LINE> <INDENT> states = {} <NEW_LINE> if not filename: <NEW_LINE> <INDENT> return states <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> f = io.open(filename, "r", encoding='utf-8') <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> io_error(e, filename, False) <NEW_LINE> return s...
Reads the previous state saved into the argument of -s | --state=
625941e5bd1bec0571d90a59
@auth.requires_membership('badmin') <NEW_LINE> def index(): <NEW_LINE> <INDENT> tables=badmin_tables <NEW_LINE> if not request.args: <NEW_LINE> <INDENT> return redirect(URL(f='index',args=tables.keys()[0])) <NEW_LINE> <DEDENT> page=1 <NEW_LINE> if 'page' in request.vars: <NEW_LINE> <INDENT> page=int(request.vars.page) ...
List table
625941e57047854f462a182f
def _read(self): <NEW_LINE> <INDENT> if path.isfile(self.PATH): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.PATH, 'r') as conf: <NEW_LINE> <INDENT> self.conf = json.load(conf) <NEW_LINE> error.log('{} loaded'.format(self.PATH)) <NEW_LINE> <DEDENT> <DEDENT> except OSError: <NEW_LINE> <INDENT> error.criti...
Reads the json config file. If not found create a json object (dict).
625941e5adb09d7d5db6cbb7
def test_set_current_session_max_inactive_interval(self): <NEW_LINE> <INDENT> pass
Test case for set_current_session_max_inactive_interval
625941e5711fe17d8254278c
def test_url_representation_encode(self): <NEW_LINE> <INDENT> encoded_options = [ base64.urlsafe_b64encode('first=Stanley&last=Smith').strip('='), base64.urlsafe_b64encode('last=Smith&first=Stanley').strip('=') ] <NEW_LINE> data = { 'first': 'Stanley', 'last': 'Smith' } <NEW_LINE> code, verification_hash = utils.url_re...
Test the url_representation_encode functionality
625941e523e79379d52ee988
def _alembic_command(self, alembic_command, engine, *args, **kwargs): <NEW_LINE> <INDENT> self.ALEMBIC_CONFIG.stdout = buf = io.StringIO() <NEW_LINE> CONF.set_override('connection', str(engine.url), group='database') <NEW_LINE> getattr(command, alembic_command)(*args, **kwargs) <NEW_LINE> res = buf.getvalue().strip() <...
Alembic command redefine reasons Most of alembic command return data into output. We should redefine this setting for getting info.
625941e563f4b57ef0001537
def QueryOleTime(self): <NEW_LINE> <INDENT> return super(ITime, self).QueryOleTime()
Method ITime.QueryOleTime OUTPUT oleTime : DATE*
625941e594891a1f4081bed5
def round_num(num, precision=None, zero_fill=True): <NEW_LINE> <INDENT> if precision is None: <NEW_LINE> <INDENT> precision = PRECISION <NEW_LINE> <DEDENT> format_string = "%%.0%df" % precision <NEW_LINE> rounded_num = (format_string % num) <NEW_LINE> if not zero_fill: <NEW_LINE> <INDENT> while (re.search(r"(\.[0-9]*)0...
Rounds NUM to PRECISION places (normally 3); returned as a string, optionally zero-filled on the right Note: Precision can be overidden wth ROUNDING_PRECISION environment variable
625941e5d8ef3951e3243968
def getAllOverlaps(reads): <NEW_LINE> <INDENT> new_dict = {} <NEW_LINE> for key in reads.keys(): <NEW_LINE> <INDENT> new_dict[key] = {} <NEW_LINE> for key2 in reads.keys(): <NEW_LINE> <INDENT> if not key == key2: <NEW_LINE> <INDENT> new_dict[key][key2] = len(getOverlap(reads[key], reads[key2])) <NEW_LINE> <DEDENT> <DED...
Returns all the overlaps in a dict of the input file
625941e5498bea3a759b9ed8
def maintainMapping(self, keyName): <NEW_LINE> <INDENT> keyFilePathNoExtension = self.nameTransform(keyName, "") <NEW_LINE> mappingFilePath = os.path.join(self._keyStorePath, "mapping.txt") <NEW_LINE> with open(mappingFilePath, 'a') as mappingFile: <NEW_LINE> <INDENT> mappingFile.write(keyName + ' ' + keyFilePathNoExte...
Use nameTransform to get the file path for keyName (without the extension) and also add to the mapping.txt file. :param str keyName: The key name URI. :return: The key file path without the extension. :rtype: str
625941e507f4c71912b118af
def number_of_sources(graph): <NEW_LINE> <INDENT> is_source_dict = {k: True for k in graph.vertices} <NEW_LINE> for edge in graph.edges: <NEW_LINE> <INDENT> is_source_dict[edge.to_vertex] = False <NEW_LINE> <DEDENT> return sum(map(lambda is_sink: is_sink, is_source_dict.values()))
Get the number of source vertices in the given graph. :param graph: graph to count sources on. :return: number of source vertices in the graph
625941e5cad5886f8bd27403
def test_add_article_twitter(self): <NEW_LINE> <INDENT> url = "twitter.com/cnnnews/1239189451" <NEW_LINE> article = Article(url, "Title") <NEW_LINE> self.db.add_article(article) <NEW_LINE> result = self.db.get_by_id(Article, 1) <NEW_LINE> self.assertEqual(result.url, url) <NEW_LINE> self.assertEqual(result.title, "Titl...
(TestDBArticle) -> None Test add article when the article belongs to a twitter account and the source/account does not exist already.
625941e560cbc95b062c696e
def run_models(model_name, model, tokenizer, sequence, device, baseline): <NEW_LINE> <INDENT> features = prepare_input(sequence, tokenizer) <NEW_LINE> input_ids = features["input_ids"].to(device) <NEW_LINE> token_type_ids = features["token_type_ids"].to(device) <NEW_LINE> attention_mask = features["attention_mask"].to(...
Run Integrated and Intermediate gradients on the model layer. Parameters ---------- model_name: str Name of the model that is being run. Currently supported are "Bert" or "XLNet" model: torch.nn.Module Module to run tokenizer: transformers.tokenizer Tokenizer to process the sequence and produce the input ...
625941e521a7993f00bc8121
def projection(self,mat): <NEW_LINE> <INDENT> U,S,VT = np.linalg.svd(mat) <NEW_LINE> sigma=sorted(S.tolist()) <NEW_LINE> kappa={} <NEW_LINE> for s in sigma: <NEW_LINE> <INDENT> kappa.setdefault(s,0) <NEW_LINE> kappa[s]+=1 <NEW_LINE> <DEDENT> sigma=sorted(list(set(sigma))) <NEW_LINE> s=self.find_S(sigma,kappa) <NEW_LINE...
projection of a matrix onto the feasible set the projection proj has the same singular vectors of mat, and its singular values are sigma(proj)_i = max(0, min(1, sigma(mat)_i + S)) where S is chosen such that \sum_i sigma(proj)_i = k
625941e50c0af96317bb8612
def test_gc(): <NEW_LINE> <INDENT> assert gc(SeqRecord(Seq(''), id='123')) == (0.0, '123') <NEW_LINE> assert gc(SeqRecord(Seq('ACTG'), id='ABC')) == (.5, 'ABC') <NEW_LINE> assert gc(SeqRecord(Seq('GGCC'), id='XYZ')) == (1.0, 'XYZ')
Test gc
625941e50fa83653e46573e2
def set_viewport_size(self, width, height): <NEW_LINE> <INDENT> self.driver.set_window_size(width, height) <NEW_LINE> script = "return {width: document.body.clientWidth, height: document.body.clientHeight};" <NEW_LINE> measured = self.driver.execute_script(script) <NEW_LINE> delta = width - measured['width'] <NEW_LINE>...
Override NeedleTestCases's set_viewport_size class method because we need it to operate on the instance not the class. See the Needle documentation at http://needle.readthedocs.org/ for information on this feature. It is particularly useful to predict the size of the resulting screenshots when taking fullscreen captur...
625941e5fff4ab517eb2f869
def has_attached_node(self, node): <NEW_LINE> <INDENT> for container in self.get_nodes_containers(): <NEW_LINE> <INDENT> if isinstance(node, Node): <NEW_LINE> <INDENT> if container.get_attached_node() == node: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(node, str): <NEW_LINE> <INDENT> i...
Returns True if the given node (given by name or instance) is attached to one of the node containers.
625941e54c3428357757c750
def get_optimizer(): <NEW_LINE> <INDENT> return Adam(lr=0.0002, beta_1=0.5)
Setting up Adam parameters.
625941e5d6c5a10208144478
def stageRecovery(self, backupId): <NEW_LINE> <INDENT> self.send_stageRecovery(backupId) <NEW_LINE> return self.recv_stageRecovery()
Loads a backup to an in-memory storage. This must precede all other recovery operations. Parameters: - backupId
625941e50383005118ecfa0c
def generate_words(self, quantity, min_len=0): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while i < quantity: <NEW_LINE> <INDENT> word = '' <NEW_LINE> selected_char = ' ' <NEW_LINE> ready = False <NEW_LINE> while not ready: <NEW_LINE> <INDENT> selected_char = nr.choice(self.main_dataframe.columns, p=self.main_dataframe.loc[s...
Once is trained, this function can generate words, args: quantity: the quantity of words that you want min_len=0: the minimum length of a word.
625941e55e10d32532c5f34f
def _get_gcp_credentials(module, require_valid_json=True, check_libcloud=False): <NEW_LINE> <INDENT> (service_account_email, credentials_file, project_id) = _get_gcp_ansible_credentials(module) <NEW_LINE> (service_account_email, credentials_file, project_id) = _get_gcp_environment_credentials(service_account_email, cre...
Obtain GCP credentials by trying various methods. There are 3 ways to specify GCP credentials: 1. Specify via Ansible module parameters (recommended). 2. Specify via environment variables. Two sets of env vars are available: a) GOOGLE_CLOUD_PROJECT, GOOGLE_CREDENTIALS_APPLICATION (preferred) b) GCE_PROJECT, GCE...
625941e57b180e01f3dc4c1f
def __init__(self, default_template=None, disk_usage_depth=None, max_age=None, max_count=None, squash_depth=None, top_n_max=None, use_snapshot=None): <NEW_LINE> <INDENT> self._default_template = None <NEW_LINE> self._disk_usage_depth = None <NEW_LINE> self._max_age = None <NEW_LINE> self._max_count = None <NEW_LINE> se...
FsaSettingsSettings - a model defined in Swagger
625941e55510c4643540f804
def get_forecasts(self, name = None, school = None, category = None, semester = None, year = None, models = False): <NEW_LINE> <INDENT> vars, vals = [], []; <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> if type(name) is not list and type(name) is not tuple: <NEW_LINE> <INDENT> name = [name]; <NEW_LINE> <DEDENT> f...
Method for getting forecasts from the database Keywords: name : Name of the forecaster; if only this used, all forecasts for this forecaster returned. school : School to filter by; if only this used, all forecasts for this school are returned. category : category to filter by; if...
625941e5a8ecb033257d34f6
def random_walk(current_value, mean, scale=1.0, return_bias=RETURN_BIAS): <NEW_LINE> <INDENT> return current_value + (mean * scale * ((random.random() - 0.5) * 0.02)) + (return_bias * (mean - current_value))
Take the current and desired mean values of a simulated sensor value, and generate the next value, to simulate a random walk around the mean value, with a bias towards returning to the mean. With scale=1.0, typical variation over 1000 samples is roughly +/- 2.0 :param current_value: Current sensor value, arbitrary un...
625941e5d53ae8145f87a692
def getPlayData(play): <NEW_LINE> <INDENT> time=play.find(class_='occurrence-info').text.split('\r') <NEW_LINE> quarter=time[0].strip().strip('Q') <NEW_LINE> if quarter[:2]=="OT": <NEW_LINE> <INDENT> quarter=int(quarter[2:])+4 <NEW_LINE> <DEDENT> clock=time[-1].strip() <NEW_LINE> number='' <NEW_LINE> player=play.find(c...
' Yea Jamal just fill this in later. Args: Soup: BeautifulSoup Object containing all HTML data from a webpage Returns: relevant info
625941e573bcbd0ca4b2c4a0
def flag_deleted(req: "CamcopsRequest", batchdetails: BatchDetails, table: Table, pklist: Iterable[int]) -> None: <NEW_LINE> <INDENT> if batchdetails.onestep: <NEW_LINE> <INDENT> values = values_delete_now(req, batchdetails) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> values = values_delete_later() <NEW_LINE> <DEDENT...
Marks record(s) as deleted, specified by a list of server PKs within a table. (Note: "deleted" means "deleted with no successor", not "modified and replaced by a successor record".)
625941e5de87d2750b8601c1
def document_term_matrix(vectorizer, excerpt): <NEW_LINE> <INDENT> return vectorizer.transform([preprocess(excerpt)]).toarray()
Return a document-term matrix.
625941e56fece00bbac2db6e
def exec_payload(self, payload_name, args=()): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return payload_handler.exec_payload(self.shell, payload_name, args, use_api=True) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return payload_handler.exec_payload(None, payload_name, args, use_api=Tru...
Execute ANOTHER payload, by providing the other payload name. :param payload_name: The name of the payload I want to run. :return: The payload result.
625941e5e76e3b2f99f3ac2f
def perform_request(self): <NEW_LINE> <INDENT> url = self.get_base_url() <NEW_LINE> headers = { "User-Agent": self.get_user_agent() } <NEW_LINE> parameters = self.get_parameters() <NEW_LINE> parameters["json"] = "true" <NEW_LINE> response = requests.get( url, params=parameters, headers=headers, timeout=self.get_timeout...
Performs the API request and returns the response value :rtype : dict
625941e5435de62698dfe077
def pyang_plugin_init(): <NEW_LINE> <INDENT> plugin.register_plugin(MDPlugin()) <NEW_LINE> grammar.register_extension_module(md_module_name) <NEW_LINE> for stmt, occurence, (arg, rules), add_to_stmts in md_stmts: <NEW_LINE> <INDENT> grammar.add_stmt((md_module_name, stmt), (arg, rules)) <NEW_LINE> grammar.add_to_stmts_...
Called by pyang plugin framework at to initialize the plugin.
625941e55fdd1c0f98dc0660
def encrypt(self,text,key): <NEW_LINE> <INDENT> plaintext = self._clean_text(text) <NEW_LINE> encrypted_text = [] <NEW_LINE> for letter,keyletter in zip(plaintext.upper(),cycle(key.upper())): <NEW_LINE> <INDENT> offset = self.alphabet.index(keyletter) + 1 <NEW_LINE> pos = self.alphabet.index(letter) <NEW_LINE> encrypte...
Encrypt the text using Vigeneré's cipher.
625941e5c4546d3d9de72e62
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'ip': 'str', 'target_ref': 'V1ObjectReference' } <NEW_LINE> self.attribute_map = { 'ip': 'ip', 'target_ref': 'targetRef' } <NEW_LINE> self._ip = None <NEW_LINE> self._target_ref = None
Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941e58e05c05ec3eea7a2
def test_printDetailedTracebackCapturedVars(self): <NEW_LINE> <INDENT> self.assertDetailedTraceback(captureVars=True)
L{printDetailedTraceback} captures the locals and globals for its stack frames and adds them to the traceback, when called on a L{Failure} constructed with C{captureVars=True}.
625941e567a9b606de4a82e1
def jump_with_context(self, index): <NEW_LINE> <INDENT> context = self.get_context(index) <NEW_LINE> context_commands = context["cmds"] <NEW_LINE> self._partial_restore_context(context) <NEW_LINE> self.jump_to(index) <NEW_LINE> self._view.restore_context(context_commands)
Jump to the given index and restore context All the warnings listed in the documentation for Runtime.jump_to apply here.
625941e5596a897236089ee6
def removeCatalog( self, catalogName ): <NEW_LINE> <INDENT> catalog_removed = False <NEW_LINE> for i in range( len( self.readCatalogs ) ): <NEW_LINE> <INDENT> catalog, object, master = self.readCatalogs[i] <NEW_LINE> if catalog == catalogName: <NEW_LINE> <INDENT> del self.readCatalogs[i] <NEW_LINE> catalog_removed = Tr...
Remove the specified catalog from the internal pool
625941e5187af65679ca554b
def fit(self, X): <NEW_LINE> <INDENT> X = check_array(X) <NEW_LINE> memory = self.memory <NEW_LINE> if isinstance(memory, six.string_types): <NEW_LINE> <INDENT> memory = Memory(cachedir=memory, verbose=0) <NEW_LINE> <DEDENT> if self.linkage == "ward" and self.affinity != "euclidean": <NEW_LINE> <INDENT> raise ValueErro...
Fit the hierarchical clustering on the data Parameters ---------- X : array-like, shape = [n_samples, n_features] The samples a.k.a. observations. Returns ------- self
625941e58e05c05ec3eea7a3
def get_list_descend(node): <NEW_LINE> <INDENT> if node.leaf: <NEW_LINE> <INDENT> node_list.append(node) <NEW_LINE> return <NEW_LINE> <DEDENT> get_list_descend(node.lo_child) <NEW_LINE> get_list_descend(node.hi_child) <NEW_LINE> if not leaves_only: <NEW_LINE> <INDENT> node_list.append(node) <NEW_LINE> <DEDENT> return
Recusively walk the tree and build a list.
625941e5eab8aa0e5d26df84
def update_bar(self, bar: CBarData) -> CBarData: <NEW_LINE> <INDENT> ix = self._manager.get_index(bar.updateTime) <NEW_LINE> bar_picture = self._draw_bar_picture(ix, bar) <NEW_LINE> self._bar_picutures[ix] = bar_picture <NEW_LINE> self.update()
Update single bar data.
625941e567a9b606de4a82e2
def GetVariance(self): <NEW_LINE> <INDENT> return _itkConfidenceConnectedImageFilterPython.itkConfidenceConnectedImageFilterIUC2IUL2_GetVariance(self)
GetVariance(self) -> double
625941e54f6381625f114e66