code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def 二分搜索(l, tgt, gt=None): <NEW_LINE> <INDENT> left = 0 <NEW_LINE> right = len(l)-1 <NEW_LINE> middle = -1 <NEW_LINE> if not gt: <NEW_LINE> <INDENT> while left <= right: <NEW_LINE> <INDENT> middle = (left+right) // 2 <NEW_LINE> if not tgt > l[middle]: <NEW_LINE> <INDENT> right = middle - 1 <NEW_LINE> <DEDENT> else: <NE...
查找 l 中不比 tgt 小的位置 l 应当已经排序过,并且是递增的 lt(tgt,l[i]) 当 tgt 比 l[i] 大时返回真
625941e6d8ef3951e324397d
def get_neighbour_frames(frame_id, n_frames=None, seconds=None, cursor=None, cursor_is_prepared=False, n_frames_left=None, n_frames_right=None, seconds_left=None, seconds_right=None): <NEW_LINE> <INDENT> n_frames_left = n_frames_left or n_frames <NEW_LINE> n_frames_right = n_frames_right or n_frames <NEW_LINE> seconds ...
Retrieves a specified number of frames around a center frame from the database. Arguments: frame_id: database ID of the middle frame n_frames: number of frames for the margin; attempts to return 2 * n_frames + 1 frames seconds: optional instead of n_frames; generally seconds = n_frames * 3.0 cursor: op...
625941e623e79379d52ee99e
def reader_num_work_units_completed(reader_handle, name=None): <NEW_LINE> <INDENT> _ctx = _context._context <NEW_LINE> if _ctx is None or not _ctx._eager_context.is_eager: <NEW_LINE> <INDENT> _, _, _op = _op_def_lib._apply_op_helper( "ReaderNumWorkUnitsCompleted", reader_handle=reader_handle, name=name) <NEW_LINE> _res...
Returns the number of work units this Reader has finished processing. Args: reader_handle: A `Tensor` of type mutable `string`. Handle to a Reader. name: A name for the operation (optional). Returns: A `Tensor` of type `int64`.
625941e6f7d966606f6aa449
def do_config(self, p_value): <NEW_LINE> <INDENT> self._change_user_without_root() <NEW_LINE> self._set_om_monitor_cron() <NEW_LINE> self._init_instance() <NEW_LINE> self._config_instance() <NEW_LINE> p_value.value = 1
Config instance on new nodes
625941e6a934411ee3751ad4
def raw_info(self): <NEW_LINE> <INDENT> return u"{} = ({}) {}".format(self.id.decode('ascii'), {0: u"Latin-1", 1: u"UTF-16", 2: u"UTF-16BE", 3: u"UTF-8"}[self.encoding], self.__unicode__())
returns a human-readable version of this frame as unicode
625941e62c8b7c6e89b35bfd
def q_sample(self, x_start, t, noise=None): <NEW_LINE> <INDENT> if noise is None: <NEW_LINE> <INDENT> noise = th.randn_like(x_start) <NEW_LINE> <DEDENT> assert noise.shape == x_start.shape <NEW_LINE> return ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + _extract_into_tensor(self.sqrt_one...
Diffuse the data for a given number of diffusion steps. In other words, sample from q(x_t | x_0). :param x_start: the initial data batch. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :param noise: if specified, the split-out normal noise. :return: A noisy version of x_start.
625941e630c21e258bdfa8e1
def element_status(self, ele): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.get_element(ele, timeout=0) <NEW_LINE> return True <NEW_LINE> <DEDENT> except TimeoutException: <NEW_LINE> <INDENT> return False
元素状态 :param ele: :return:
625941e657b8e32f524838de
def _update_play_queue_order(self, print_queue=True): <NEW_LINE> <INDENT> total_tracks = len(self.queue) <NEW_LINE> if total_tracks: <NEW_LINE> <INDENT> if not len(self.play_queue_order): <NEW_LINE> <INDENT> self.play_queue_order = list(range(total_tracks)) <NEW_LINE> <DEDENT> if self.current_play_mode == self.play_mod...
Update the queue playback order. A sequential order is applied if the current play mode is "NORMAL" or a random order if current play mode is "SHUFFLE"
625941e6d486a94d0b98e587
def move(self, row, col, player): <NEW_LINE> <INDENT> add = -1 <NEW_LINE> if player == 1: <NEW_LINE> <INDENT> add = 1 <NEW_LINE> <DEDENT> self.row[row] += add <NEW_LINE> self.col[col] += add <NEW_LINE> if row == col: <NEW_LINE> <INDENT> self.diagonal += add <NEW_LINE> <DEDENT> if row + col == self.n-1: <NEW_LINE> <INDE...
Player {player} makes a move at ({row}, {col}). @param row The row of the board. @param col The column of the board. @param player The player, can be either 1 or 2. @return The current winning condition, can be either: 0: No one wins. 1: Player 1 wins. 2: Player 2 wins. :type row: int :type col:...
625941e6e5267d203edce0d7
def __checkARow(self, f, t): <NEW_LINE> <INDENT> ct1 = 0; <NEW_LINE> ct2 = 0; <NEW_LINE> w = 0 <NEW_LINE> ii = 0 <NEW_LINE> for i in range(t): <NEW_LINE> <INDENT> x, y = f(i, t) <NEW_LINE> if self.__bd[x][y] == 1: <NEW_LINE> <INDENT> ct1 += 1 <NEW_LINE> if ct1 == self.__roSz: <NEW_LINE> <INDENT> ii = i <NEW_LINE> w = 1...
f: function that calculate the index (x,y) t: row lenght
625941e63617ad0b5ed68337
def calc_elems_in_physgrps(self): <NEW_LINE> <INDENT> for grp_num, grp_nodes in self.nodes_in_physical_groups.items(): <NEW_LINE> <INDENT> self.elems_in_physical_groups[grp_num] = set() <NEW_LINE> grp_n_set = set(grp_nodes) <NEW_LINE> for eleid, elem in self.elems.items(): <NEW_LINE> <INDENT> if grp_n_set.intersection(...
Calculates the elements attached to nodes in physical groups.
625941e60383005118ecfa21
def test_testreport_1(base_settings): <NEW_LINE> <INDENT> filename = base_settings["unittest_data_dir"] / "testreport-example.json" <NEW_LINE> inst = testreport.TestReport.parse_file( filename, content_type="application/json", encoding="utf-8" ) <NEW_LINE> assert "TestReport" == inst.resource_type <NEW_LINE> impl_testr...
No. 1 tests collection for TestReport. Test File: testreport-example.json
625941e6a8ecb033257d350c
def index(request): <NEW_LINE> <INDENT> return HttpResponse("Hello World!")
Default index page.
625941e65e10d32532c5f365
def nonblocking_custom_capture(tr_mesh, rot_xyz, last_rot=(0, 0, 0)): <NEW_LINE> <INDENT> vis = o3d.visualization.Visualizer() <NEW_LINE> vis.create_window(width=224, height=224, visible=False) <NEW_LINE> vis.add_geometry(tr_mesh) <NEW_LINE> R_0 = tr_mesh.get_rotation_matrix_from_xyz(last_rot) <NEW_LINE> tr_mesh.rotate...
Custom function for Open3D to allow non-blocking capturing on a headless server. The function renders a triangle mesh file in a 224x224 window capturing a depth-image from the rot_xyz rotation of the object. Stores the image in the ./tmp/ folder. :param tr_mesh: open3d.geometry.TriangleMesh object to render. :param r...
625941e6377c676e912725e7
def check_row(sudoku): <NEW_LINE> <INDENT> for row in sudoku: <NEW_LINE> <INDENT> for element in row: <NEW_LINE> <INDENT> if element not in "12345678910": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return True
Your solution goes here. You may add other helper functions as needed. The function has to return True for a valid sudoku grid and false otherwise
625941e6566aa707497f49a3
@busi.route('/classes/Space/<int:todo_id>', methods=['PUT', ]) <NEW_LINE> def update_space(todo_id): <NEW_LINE> <INDENT> session_token = request.headers.get('X-LC-Session', "") <NEW_LINE> if session_token == "" or session_token is None: <NEW_LINE> <INDENT> return jsonify({"result": {"error_code": 1, "msg": 'miss sessio...
查询组 :return:
625941e6283ffb24f3c55d3d
def set(self, index, item): <NEW_LINE> <INDENT> index = int(index) <NEW_LINE> self._check_bounds(index) <NEW_LINE> self.data[index] = item
Sets the given item at the given index. Throws an exception if the index is not within the bounds of the array.
625941e65f7d997b87174edc
def test_retrieve_self_unauthenticated(self): <NEW_LINE> <INDENT> retrieve_url = reverse(get_url_name(__name__, 'api-profile-retrieve')) <NEW_LINE> resp = self.client.get(retrieve_url) <NEW_LINE> self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN, resp.json())
Not logged in and not using 'pk'. (deny)
625941e60383005118ecfa22
def save_to_sheet(target_sheet_url, df): <NEW_LINE> <INDENT> gc = gspread.oauth() <NEW_LINE> sh = gc.open_by_url(target_sheet_url) <NEW_LINE> target_gid = gid_for_sheets_url(target_sheet_url) <NEW_LINE> sheet_data = sh.fetch_sheet_metadata() <NEW_LINE> try: <NEW_LINE> <INDENT> item = finditem( lambda x: str(x['properti...
save df to the google doc at target_sheet_url. The data will always be saved to the specified tab within the sheet (specified within the url), and the old contents of the tab will be saved to a backup tab before being replaced. Requires authentication. You must have the client secret installed in `~/.config/gspread/cr...
625941e629b78933be1e5ae7
def __init__(self, root=None, onlyin=None, verbose=False): <NEW_LINE> <INDENT> self.verbose = verbose <NEW_LINE> self._root = root <NEW_LINE> origonlyin = onlyin <NEW_LINE> onlyin = [onlyin] if isinstance(onlyin, basestring) else onlyin <NEW_LINE> onlyin = set() if onlyin is None else set(onlyin) <NEW_LINE> onlyin = [r...
Parameters ------------- root : element tree node, optional The root element node of the AST. onlyin : str, optional Filename to search, prevents finding APIs coming from other libraries. verbose : bool, optional Flag to display extra information while visiting the file.
625941e66aa9bd52df0371e7
def _dump_mapping(self, m, tmpdir): <NEW_LINE> <INDENT> my_utils = self._memory_handler.get_target_platform().get_target_ctypes_utils() <NEW_LINE> if m.permissions[0] != 'r': <NEW_LINE> <INDENT> log.debug('Ignore read protected mapping %s', m) <NEW_LINE> return <NEW_LINE> <DEDENT> elif m.pathname in ['[vdso]', '[vsysca...
Dump one mapping to one file in one tmpdir.
625941e663f4b57ef000154d
def SetServoMinimum3(self, pwmLevel): <NEW_LINE> <INDENT> pwmDutyLow = pwmLevel & 0xFF <NEW_LINE> pwmDutyHigh = (pwmLevel >> 8) & 0xFF <NEW_LINE> try: <NEW_LINE> <INDENT> self.RawWrite(COMMAND_SET_PWM_MIN_3, [pwmDutyHigh, pwmDutyLow]) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> raise <NEW_LINE> <D...
SetServoMinimum3(pwmLevel) Sets the minimum PWM level for servo output #3 This corresponds to position -1 This value can be set anywhere from 0 for a 0% duty cycle to 65535 for a 100% duty cycle Setting values outside the range of the servo for extended periods of time can damage the servo LIMIT CHECKING IS ALTERED B...
625941e6097d151d1a223298
def onRspSubMarketData(self, data, error, n, last): <NEW_LINE> <INDENT> self.log.info(error['ErrorID'])
订阅合约回报
625941e685dfad0860c3b29c
def get_last_available_status_message(cons: Consumer, status_topic: str): <NEW_LINE> <INDENT> partitions = cons.assignment() <NEW_LINE> _, hi = cons.get_watermark_offsets(partitions[0], cached=False, timeout=2.0) <NEW_LINE> last_msg_offset = hi - 1 <NEW_LINE> cons.assign([TopicPartition(status_topic, partition=0, offse...
:param cons: :param status_topic: :return: The last status message.
625941e6596a897236089efb
def p_expression_statement(self, p): <NEW_LINE> <INDENT> p[0] = ast.ExpressionStatement(expression=p[1])
expression_statement : expression SEMICOLON
625941e673bcbd0ca4b2c4b6
def build(self): <NEW_LINE> <INDENT> lines = [] <NEW_LINE> _status = getattr(self.iterator, '_status', None) <NEW_LINE> if _status is not None: <NEW_LINE> <INDENT> self.status = _status <NEW_LINE> <DEDENT> if isinstance(self.status, int): <NEW_LINE> <INDENT> self.status = "{0} {1}".format(self.status, httping.STATUS_DE...
Return built head bytes from .status and .headers
625941e6e1aae11d1e74a0fc
def hit_tile(self, pos, power=1, sound=False): <NEW_LINE> <INDENT> global play_sounds, sounds <NEW_LINE> for tile in self.mapr: <NEW_LINE> <INDENT> if tile.topleft == pos: <NEW_LINE> <INDENT> if tile.type == self.TILE_BRICK: <NEW_LINE> <INDENT> if play_sounds and sound: <NEW_LINE> <INDENT> sounds["brick"].play() <NEW_L...
Hit the tile @param pos Tile's x, y in px @return True if bullet was stopped, False otherwise
625941e682261d6c526ab8e7
def create_role(name, description=None): <NEW_LINE> <INDENT> if name in SystemRole.get_valid_values(): <NEW_LINE> <INDENT> raise ValueError('"%s" role name is blacklisted' % (name)) <NEW_LINE> <DEDENT> role_db = RoleDB(name=name, description=description) <NEW_LINE> role_db = Role.add_or_update(role_db) <NEW_LINE> retur...
Create a new role.
625941e63d592f4c4ed1d4a2
def bin_to_int(arr, _multiple=None): <NEW_LINE> <INDENT> if isinstance(arr, (list, tuple)): <NEW_LINE> <INDENT> arr = np.array(arr, dtype=int) <NEW_LINE> <DEDENT> assert isinstance(arr, np.ndarray) and arr.ndim and arr.ndim < 3, "Input must be array type of not more than two dimensions" <NEW_LINE> if arr.ndim == 2: ...
Convert binary array(s) to positive integer(s).
625941e616aa5153ce3628b8
def play_degree_objs(dataset_path): <NEW_LINE> <INDENT> total_data_samples = 0 <NEW_LINE> fnames = ['education-degree.json'] <NEW_LINE> ed_pat_1 = re.compile(r'\(\(NAM:(.*?)\)\)') <NEW_LINE> ed_pat_2 = re.compile(r'\(\(NOM:(.*?)\)\)') <NEW_LINE> resolved_sample = 0 <NEW_LINE> for fname in fnames: <NEW_LINE> <INDENT> pr...
Check if every case of degree has a the object clearly marked out. Generally function to play around with these degree objects. :param dataset_path: unicode; full path to the dir with all rel jsons. :return:
625941e63cc13d1c6d3c77b9
def carFleet(self, target, position, speed): <NEW_LINE> <INDENT> if not position: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> length = len(position) <NEW_LINE> mapping = {} <NEW_LINE> for i, p in enumerate(position): <NEW_LINE> <INDENT> mapping[p] = speed[i] <NEW_LINE> <DEDENT> position.sort(reverse=True) <NEW_LIN...
:type target: int :type position: List[int] :type speed: List[int] :rtype: int
625941e6596a897236089efc
def _cache_contents(self, style_urls, asset_url_path): <NEW_LINE> <INDENT> files = {} <NEW_LINE> asset_urls = [] <NEW_LINE> for style_url in style_urls: <NEW_LINE> <INDENT> if not self.quiet: <NEW_LINE> <INDENT> print(' * Downloading style', style_url, file=sys.stderr) <NEW_LINE> <DEDENT> r = requests.get(style_url) <N...
Fetches the given URLs and caches their contents and their assets in the given directory.
625941e644b2445a339324d4
def _get_tstat_full_directory_path_with_units(self, statname, tup): <NEW_LINE> <INDENT> front = 'U' + str(int(self._get_units_of_stat(statname))) + '_' <NEW_LINE> if statname in self._tstats: <NEW_LINE> <INDENT> stat_dir = os.path.join(self._tuple_dirs[tup], front + statname + '_tsD') <NEW_LINE> <DEDENT> elif statname ...
Finds the full path of a given tstat Returns: A string with the path name
625941e638b623060ff0b22e
def get_municipalities(title): <NEW_LINE> <INDENT> municipalities = [] <NEW_LINE> site = pywikibot.Site("sv", "wikipedia") <NEW_LINE> page = pywikibot.Page(site, title) <NEW_LINE> for cat in page.categories(): <NEW_LINE> <INDENT> cat_title = cat.titleWithoutNamespace() <NEW_LINE> if cat_title not in municip_cache_globa...
Extract the municipalities from svwp article of nature reserve. Get the names of categories to which the article belongs, and extract the names of municipalities from them.
625941e67d43ff24873a30e4
def __init__(self, gradient_lambda: float, network_factory: NetworkFactory, l1_lambda: float = 0.0, seed: int = None): <NEW_LINE> <INDENT> self._gradient_lambda = gradient_lambda <NEW_LINE> self._seed = seed <NEW_LINE> self._network_factory = network_factory <NEW_LINE> self._l1_lambda = l1_lambda
Creates a new Wasserstein GAN loss factory. :param gradient_lambda: Lambda to multiply with discriminator gradient norm :param network_factory: Network factory used to create the correlating generators and discriminators :param l1_lambda: Lambda to multiply with the l1 distance between generated and real samples for th...
625941e616aa5153ce3628b9
def __init__(self, pickup_node, delivery_node): <NEW_LINE> <INDENT> self.pickup_node = pickup_node <NEW_LINE> self.delivery_node = delivery_node <NEW_LINE> self.id = pickup_node.identity
Create a new Request object.
625941e6956e5f7376d712ad
def GetToasterBoxWindow(self): <NEW_LINE> <INDENT> return self._tb
Returns the L{ToasterBox} frame.
625941e6b5575c28eb68e445
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941e69b70327d1c4e1218
def sendPreparedMessage(self, preparedMsg): <NEW_LINE> <INDENT> if self.websocket_version != 0: <NEW_LINE> <INDENT> if self._perMessageCompress is None or preparedMsg.doNotCompress: <NEW_LINE> <INDENT> self.sendData(preparedMsg.payloadHybi) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sendMessage(preparedMsg.payl...
Implements :func:`autobahn.interfaces.IWebSocketChannel.sendPreparedMessage`
625941e6baa26c4b54cb155c
def onAssetValueChanged(self, value): <NEW_LINE> <INDENT> if isinstance(value, dict) and "Id" in value: <NEW_LINE> <INDENT> id = value['Id'] <NEW_LINE> if "Value" in value: <NEW_LINE> <INDENT> value['value'] = value['Value'] <NEW_LINE> <DEDENT> resources.valueStore[id] = value <NEW_LINE> resources.trigger = resources.A...
callback for the processor part: check if the value of an actuator has changed, if so, update the group's value
625941e63317a56b8693a08f
def __post_load_exclusion(self): <NEW_LINE> <INDENT> exclusion = self.conf.get('exclusion') <NEW_LINE> if isinstance(exclusion, list): <NEW_LINE> <INDENT> for mac in exclusion: <NEW_LINE> <INDENT> self.exclusion.add(mac)
Called by post_load() to load internal representation of exception
625941e6507cdc57c6307125
def __getitem__(self, index): <NEW_LINE> <INDENT> sample = self.get_sample(index) <NEW_LINE> if self.transform: <NEW_LINE> <INDENT> sample = self.transform(sample) <NEW_LINE> <DEDENT> if self.return_indexes: <NEW_LINE> <INDENT> sample = (sample, index) <NEW_LINE> <DEDENT> return sample
Get a sample and transform it to be used in a model, use the transformations Args: index : int, index of the sample desired Returns: tuple Tuple containing the features and the labels (numpy.array, numpy.array) or Tuple containing the features, the labels and the index (numpy.array, numpy.array, int)
625941e663b5f9789fde7527
def _handle_darknet_rnn_layers(self, layer_num, sym): <NEW_LINE> <INDENT> attr = {} <NEW_LINE> layer = self.net.layers[layer_num] <NEW_LINE> processed = False <NEW_LINE> if LAYERTYPE.RNN == layer.type: <NEW_LINE> <INDENT> attr.update({'n' : layer.n}) <NEW_LINE> attr.update({'batch' : layer.batch}) <NEW_LINE> attr.updat...
Parse attributes and handle the rnn layers.
625941e69c8ee82313fbbbb7
def jstrptime(format, date_str): <NEW_LINE> <INDENT> date = struct_jtm() <NEW_LINE> res = c_char_p() <NEW_LINE> res = _jstrptime(date_str, format, byref(date)) <NEW_LINE> return date, res
Return :class:`.types.struct_jtm` from date_str according to format. :param string format: format of string representation :param string date_str: string representation
625941e6462c4b4f79d1db10
def settext(self, text, cls='current'): <NEW_LINE> <INDENT> self.replace(TextContent, value=text, cls=cls)
Set the text for this element (and class)
625941e626068e7796caf126
def read_list_stream(self): <NEW_LINE> <INDENT> self.__sample = [] <NEW_LINE> list_stream = self.read_list_stream_create() <NEW_LINE> list_stream = self.read_list_stream_handle_errors(list_stream) <NEW_LINE> for cells in list_stream: <NEW_LINE> <INDENT> self.__sample.append(cells) <NEW_LINE> if len(self.__sample) >= se...
Read list stream Returns: gen<any[][]>: list stream
625941e6cc40096d61595d90
def initialize(): <NEW_LINE> <INDENT> global METAINFO <NEW_LINE> METAINFO = {}
Sets up global variables.
625941e6099cdd3c635f109a
@retry_on_exception(3, base_delay=2, exc_type=subprocess.CalledProcessError) <NEW_LINE> def unison_sync(paths_to_sync): <NEW_LINE> <INDENT> log('Synchronizing CA (%s) to all peers.' % (', '.join(paths_to_sync)), level=INFO) <NEW_LINE> keystone_gid = grp.getgrnam('keystone').gr_gid <NEW_LINE> unison.sync_to_peers(peer_i...
Do unison sync and retry a few times if it fails since peers may not be ready for sync. Returns list of synced units or None if one or more peers was not synced.
625941e6f8510a7c17cf9b40
def get_gpg_public_keyrings_path(): <NEW_LINE> <INDENT> keyring_list = str(get_value(GPG_PUBLIC_KEYRING_PATH)).split(",") <NEW_LINE> sanitized_list = map(str.strip, keyring_list) <NEW_LINE> return sanitized_list
Return a list of string representing keyring path.
625941e6a219f33f34628da5
def _get_language_for_editing(self, request, video_id, language_code, subtitle_language_pk=None, base_language=None): <NEW_LINE> <INDENT> video = models.Video.objects.get(video_id=video_id) <NEW_LINE> editable = False <NEW_LINE> create_new = False <NEW_LINE> if subtitle_language_pk is not None: <NEW_LINE> <INDENT> lang...
Return the subtitle language to edit or a lock response.
625941e6d268445f265b52b0
def test_options(self) -> None: <NEW_LINE> <INDENT> prob = cp.Problem(cp.Minimize(cp.norm(self.x, 1)), [self.x == cp.Variable(2, boolean=True)]) <NEW_LINE> if cp.CBC in INSTALLED_SOLVERS: <NEW_LINE> <INDENT> for i in range(2): <NEW_LINE> <INDENT> prob.solve(solver=cp.CBC, verbose=True, maximumSeconds=100) <NEW_LINE> <D...
Test that all the cvx.CBC solver options work.
625941e6be8e80087fb2107d
def print_params(self): <NEW_LINE> <INDENT> print(f'KmeansMinus2(n_outliers={self.n_outliers}, n_centers={self.n_centers}, distance_function={self.distance_function}') <NEW_LINE> print(f'\tmax_iter={self.max_iter}, r_seed={self.seed}, verbose={logging.getLevelName(self.verbose)})')
Print the paramters of the algorithm.
625941e6925a0f43d254a2bc
def test_gaussian_pdf(self): <NEW_LINE> <INDENT> pdf = gaussian_pdf(AXIS, 6 * 3600., (7200.,)) <NEW_LINE> PLT.plot(AXIS, pdf) <NEW_LINE> PLT.show()
Gaussian pdf
625941e68e71fb1e9831dbe9
def abort_keepalive_pings(self): <NEW_LINE> <INDENT> assert self.state is State.CLOSED <NEW_LINE> exc = ConnectionClosed(self.close_code, self.close_reason) <NEW_LINE> exc.__cause__ = self.transfer_data_exc <NEW_LINE> for ping in self.pings.values(): <NEW_LINE> <INDENT> ping.set_exception(exc) <NEW_LINE> <DEDENT> if se...
Raise ConnectionClosed in pending keepalive pings. They'll never receive a pong once the connection is closed.
625941e615baa723493c43ba
def dirty(name, target, user=None, username=None, password=None, ignore_unversioned=False): <NEW_LINE> <INDENT> ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} <NEW_LINE> return _fail(ret, 'This function is not implemented yet.')
Determine if the working directory has been changed.
625941e68da39b475bd653ba
def file_to_words(path): <NEW_LINE> <INDENT> sentences = [] <NEW_LINE> with open(path, 'r', encoding='utf-8') as f: <NEW_LINE> <INDENT> line = f.readline() <NEW_LINE> while line: <NEW_LINE> <INDENT> words = jieba.lcut(line, cut_all=True, HMM=True) <NEW_LINE> sentences.append(words) <NEW_LINE> line = f.readline() <NEW_L...
将文本文件转换为sequences :param path: :return:
625941e6a05bb46b383ecc5f
def segment_display(self): <NEW_LINE> <INDENT> val = dict(SEGMENT_BY_CHOICES).get(self.segment_by, '') <NEW_LINE> if self.segment_by == 'location': <NEW_LINE> <INDENT> val = '%s - %s' % (val, dict(LOCATION_CHOICES).get(self.locate_by)) <NEW_LINE> <DEDENT> return val
Display method for this campaign's segmenting and locating of callers
625941e6a8370b7717052cdf
def __iter__(self): <NEW_LINE> <INDENT> active = Queue.Queue() <NEW_LINE> active.put(self) <NEW_LINE> while active.qsize() > 0: <NEW_LINE> <INDENT> next = active.get() <NEW_LINE> for _, child in next.children.items(): <NEW_LINE> <INDENT> if child is not None: <NEW_LINE> <INDENT> active.put(child) <NEW_LINE> <DEDENT> <D...
A generator function. Does a pre-order traversal over the nodes in the tree without using recursion.
625941e6f9cc0f698b140a39
def _select_options(self, options, keys, invert=False): <NEW_LINE> <INDENT> options = self._merge_options(options) <NEW_LINE> result = {} <NEW_LINE> for key in options: <NEW_LINE> <INDENT> if (invert and key not in keys) or (not invert and key in keys): <NEW_LINE> <INDENT> result[key] = options[key] <NEW_LINE> <DEDENT>...
Selects the provided keys (or everything except the provided keys) out of an options object
625941e656ac1b37e6264608
def __init__(self, seqsManager, outPath): <NEW_LINE> <INDENT> CorrMutGeneric.__init__(self,seqsManager, outPath) <NEW_LINE> self.seqsManager= seqsManager <NEW_LINE> self.corrMutOutPath= myMakeDir(outPath,"corrMut") <NEW_LINE> self.featName="psicov"
@param seqsManager: ..manageSeqs.seqsManager.SeqsManager @param outPath: str. path where corrMut scores will be saved
625941e66fb2d068a760f4e5
def get_last_control_point(interval): <NEW_LINE> <INDENT> if len(interval["e"]) >= 2: <NEW_LINE> <INDENT> en = Vector(interval["e"][0], interval["e"][1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> en = interval["e"][0] <NEW_LINE> <DEDENT> return en
Returns the last control point of a bezier interval Args: interval (dict) : Holds one interval of the bezier curve that is two waypoints Returns: (misc.Vector) If the interval holds position bezier (float) Else : the interval holds value bezier
625941e6236d856c2ad44c21
@pytest.yield_fixture(scope='session') <NEW_LINE> def app(): <NEW_LINE> <INDENT> params = { 'DEBUG': False, 'TESTING': True, 'WTF_CSRF_ENABLED': False } <NEW_LINE> _app = create_app(settings_override=params) <NEW_LINE> context = _app.app_context() <NEW_LINE> context.push() <NEW_LINE> yield _app <NEW_LINE> context.pop()
Setup the flask test app. This only gets executed once. :return: Flask app
625941e6baa26c4b54cb155d
def visit_functiondef(self, node): <NEW_LINE> <INDENT> decorate = node.decorators.accept(self) if node.decorators else '' <NEW_LINE> docs = '\n%s"""%s"""' % (self.indent, node.doc) if node.doc else '' <NEW_LINE> return_annotation = '' <NEW_LINE> if six.PY3 and node.returns: <NEW_LINE> <INDENT> return_annotation = '->' ...
return an astroid.Function node as string
625941e6287bf620b61d3ea2
def mopup(self): <NEW_LINE> <INDENT> root_name = self.dispersed_image.split('.fits')[0] <NEW_LINE> result_root = self.simul_grisim.split('.fits')[0] <NEW_LINE> out_spc = config_util.getOUTPUT(root_name + '_2.SPC.fits') <NEW_LINE> result_spc = config_util.getOUTSIM(result_root + '_2.SPC.fits') <NEW_LINE> shutil.move(out...
Deleting tmp-files, copying SPC's, STP's
625941e656ac1b37e6264609
def SetInput1(self, *args): <NEW_LINE> <INDENT> return _itkStatisticsRelabelImageFilterPython.itkStatisticsRelabelImageFilterIUS3IUC3_SetInput1(self, *args)
SetInput1(self, itkImageUS3 input)
625941e6097d151d1a223299
def feasible(self, xr): <NEW_LINE> <INDENT> if isinstance(xr, linalgs.MultipartArray): <NEW_LINE> <INDENT> xr = xr.get_parts() <NEW_LINE> <DEDENT> x = xr[0] <NEW_LINE> if self.penalty_start > 0: <NEW_LINE> <INDENT> x_ = x[self.penalty_start:, :] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x_ = x <NEW_LINE> <DEDENT> r...
Feasibility of the constraint at points x and r. From the interface Constraint. Parameters ---------- xr : List or tuple with two elements, numpy arrays. The first element is x and the second is r.
625941e607d97122c4178cd7
def check_conf_interval(avg: pandas.Series, down_time: dict) -> dict: <NEW_LINE> <INDENT> for node_type in ['NORMAL', "FREE_RIDER"]: <NEW_LINE> <INDENT> if node_type not in down_time: <NEW_LINE> <INDENT> down_time[node_type] = [] <NEW_LINE> <DEDENT> average = avg[node_type] <NEW_LINE> down_time[node_type] += [average] ...
:param avg: :param down_time:
625941e6627d3e7fe0d69293
def set_error(self, message): <NEW_LINE> <INDENT> self.done = True <NEW_LINE> self.error = {'message': message}
Marks the operation as failed. Args: message: A string specifying the reason the operation failed.
625941e6d164cc6175783191
def forbid_multi_line_headers(name, val): <NEW_LINE> <INDENT> val = smart_text(val) <NEW_LINE> if '\n' in val or '\r' in val: <NEW_LINE> <INDENT> raise BadHeaderError('Header values can\'t contain newlines ' '(got %r for header %r)' % (val, name)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> val = val.encode('ascii') <...
Forbids multi-line headers, to prevent header injection.
625941e660cbc95b062c6985
def angular_velocity_is_trivial(omega): <NEW_LINE> <INDENT> return (np.abs(omega) < EPSILON)
test if the provided angular velocity is small enough to be treated as zero
625941e67d43ff24873a30e5
def display_shows_episodes(self, show_name, season): <NEW_LINE> <INDENT> self.games_items = [] <NEW_LINE> episodes = self.gp.get_shows_episodes(show_name, season) <NEW_LINE> for episode in episodes: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> listitem = xbmcgui.ListItem('[B]%s[/B]' % show_name) <NEW_LINE> for episode_...
Show episodes for a given season/show
625941e673bcbd0ca4b2c4b7
def getTransferRunTime(transferID): <NEW_LINE> <INDENT> return 0,0
Returns the runtime of a filetransfer. @param transferID: the ID of the filetransfer @type transferID: int @return: a tuple, containing the errorcode and the runtime in seconds @rtype: tuple (int, int)
625941e607f4c71912b118c6
def write_PRINT(self, style): <NEW_LINE> <INDENT> s = "PRINT\t" + style + '\n' <NEW_LINE> self.english_out.write(s) <NEW_LINE> self.picture_out.write(s)
Writes a 'PRINT' line in eng & pic files. Parameters ---------- style : str Returns ------- None
625941e610dbd63aa1bd2fe4
def testMultiClassification(self): <NEW_LINE> <INDENT> random.seed(42) <NEW_LINE> n_classes = 5 <NEW_LINE> X, y = datasets.make_multilabel_classification(n_classes=n_classes, random_state=42)
TODO(ilblackdragon): Implement multi-output classification.
625941e6d99f1b3c44c679c9
def do_ws(args): <NEW_LINE> <INDENT> ws = "/project/%s/commands/_analyse" % args.project <NEW_LINE> return ws
Build the web service resource path
625941e657b8e32f524838e0
def connect_db(): <NEW_LINE> <INDENT> return MongoClient()
Connect to the database -- must have a mongod client running
625941e6d8ef3951e3243980
def page(self, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> params = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) <NEW_LINE> response = self._version.page( 'GET', self._uri, params=params, ) <NEW_LINE> return ServicePage(self._vers...
Retrieve a single page of ServiceInstance records from the API. Request is executed immediately :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for client state :param int page_size: Number of records to return, defaults to 50 :returns: Page of ServiceIns...
625941e6d486a94d0b98e589
def Add(self, other): <NEW_LINE> <INDENT> if len(self.data) != len(other.data): <NEW_LINE> <INDENT> raise RuntimeError("Can only add series of identical lengths.") <NEW_LINE> <DEDENT> for i in range(len(self.data)): <NEW_LINE> <INDENT> if self.data[i][1] != other.data[i][1]: <NEW_LINE> <INDENT> raise RuntimeError("Time...
Add other to self pointwise. Requires that both self and other are of the same length, and contain identical timestamps. Typically this means that Normalize has been called on both with identical time parameters. Args: other: The sequence to add to self. Raises: RuntimeError: other does not contain the same time...
625941e61f5feb6acb0c4f8b
def host_update(host_id, values): <NEW_LINE> <INDENT> IMPL.host_update(host_id, values)
Update Compute host.
625941e63cc13d1c6d3c77ba
def str_recurse(self, tree_node, level = 0): <NEW_LINE> <INDENT> ret_str = "" <NEW_LINE> if not self.valid_node_in_tree(tree_node): <NEW_LINE> <INDENT> return ret_str <NEW_LINE> <DEDENT> if level > self.BLANK_STR_LEN - 1: <NEW_LINE> <INDENT> return self.BLANK_STRING + " ... " <NEW_LINE> <DEDENT> if not tree_node.dltd...
recursive tree stringizer (with indentation) for subtree with root tree_node in this instance's tree
625941e6d268445f265b52b1
def load_urls(file_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> df = pd.read_csv(file_path) <NEW_LINE> urls = list(df.url) <NEW_LINE> logger.info("%s: urls has been load\t%s" % (module_name, file_path)) <NEW_LINE> return urls <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> logger.error("%s: urls...
读取URL数据,csv格式 :param file_path: 读取路径 :return:
625941e6566aa707497f49a5
def cb_irc_server_connected(data, signal, signal_data): <NEW_LINE> <INDENT> if weechat.config_get_plugin('show_server') == 'on': <NEW_LINE> <INDENT> growl_notify( 'Server', 'Server Connected', 'Connected to network {0}.'.format(signal_data)) <NEW_LINE> <DEDENT> return weechat.WEECHAT_RC_OK
Notify when connected to IRC server.
625941e6adb09d7d5db6cbcf
def download(wiki = "wp", language = "wo"): <NEW_LINE> <INDENT> if wiki == "wp": <NEW_LINE> <INDENT> file = language + "wiki-latest-pages-meta-history.xml.bz2" <NEW_LINE> url = "http://download.wikimedia.org/" + language + "wiki/latest/" + file <NEW_LINE> <DEDENT> f_url_in = urllib2.urlopen(url) <NEW_LINE> if not os.pa...
Download MediaWiki XML dump.
625941e61d351010ab855f5d
def _linearize(self): <NEW_LINE> <INDENT> system = self._system <NEW_LINE> if system._owns_assembled_jac or system._views_assembled_jac: <NEW_LINE> <INDENT> mtx = system._jacobian._int_mtx <NEW_LINE> if isinstance(mtx, DenseMatrix): <NEW_LINE> <INDENT> ranges = system._jacobian._view_ranges[system.pathname] <NEW_LINE> ...
Perform factorization.
625941e65f7d997b87174ede
def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> rst = func(*args, **kwargs) <NEW_LINE> dct = Base_do.sqlalchemy_obj_to_dict(rst) <NEW_LINE> return dct
装饰器的wrapper [description] Arguments: *args {list} -- args **kwargs {dict} -- kwargs Returns: dict -- Base_do.sqlalchemy_obj_to_dict(rst)
625941e66aa9bd52df0371e9
def createTemperature(self): <NEW_LINE> <INDENT> rec = TemperatureRecord("") <NEW_LINE> rec.valid = self.valid <NEW_LINE> rec.temperature = self.temperature <NEW_LINE> return rec
Converts the current object to a TemperatureRecord :returns: TemperatureRecord from the current TemperatureRecordAdapter
625941e6cad5886f8bd2741b
def __get_credentials(self, store_file_name): <NEW_LINE> <INDENT> home_dir = os.path.expanduser('~') <NEW_LINE> credential_dir = os.path.join(home_dir, '.credentials') <NEW_LINE> if not os.path.exists(credential_dir): <NEW_LINE> <INDENT> os.makedirs(credential_dir) <NEW_LINE> <DEDENT> credential_path = os.path.join(cre...
Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential.
625941e6be383301e01b58c0
@router.get("/users/user", response_model=schemas.User) <NEW_LINE> def read_user( username: Optional[str] = None, user_id: Optional[int] = None, db: Session = Depends(get_db), ) -> Any: <NEW_LINE> <INDENT> if username: <NEW_LINE> <INDENT> db_user = get_user_by_username(db=db, username=username) <NEW_LINE> <DEDENT> elif...
Get data about user
625941e6099cdd3c635f109b
def run(self): <NEW_LINE> <INDENT> log.info('Pipeline {s} execution started'.format(s=self.label)) <NEW_LINE> self.pre_validate() <NEW_LINE> create_replace_dir(tdir=self.ustar_mp_dir, label='{s}.run'.format(s=self.label), suffix=self.pipeline.run_id, simulation=self.pipeline.simulation) <NEW_LINE> log.info('Execution c...
Executes ustar_mp
625941e623e79379d52ee9a1
def validate_error_func(self): <NEW_LINE> <INDENT> pass
# Validate the error function
625941e6b545ff76a8914258
def require_file(file: Text): <NEW_LINE> <INDENT> f = pathlib.Path(file).resolve() <NEW_LINE> if not f.is_file(): <NEW_LINE> <INDENT> raise Exception(f'The required file {str(f)} was not found')
Asserts that a given file exists. Raises an exception if it doesn't.
625941e601c39578d7e7527e
def cache_function(length): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> def inner_func(*args, **kwargs): <NEW_LINE> <INDENT> key = cache_function_key(func, args, kwargs) <NEW_LINE> value = cache.get(key) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> else: <NEW_LI...
A variant of the snippet posted by Jeff Wheeler at http://www.djangosnippets.org/snippets/109/ Caches a function, using the function and its arguments as the key, and the return value as the value saved. It passes all arguments on to the function, as it should. The decorator itself takes a length argument, which is t...
625941e685dfad0860c3b29e
def s_m(self, prob): <NEW_LINE> <INDENT> return Utils.Zero()
Magnetic source term :param BaseFDEMProblem prob: FDEM Problem :rtype: numpy.ndarray :return: magnetic source term on mesh
625941e6b5575c28eb68e446
def to_bytes(self): <NEW_LINE> <INDENT> result = self.header.to_bytes() <NEW_LINE> if self.queries is not None: <NEW_LINE> <INDENT> for query in self.queries: <NEW_LINE> <INDENT> result += query.to_bytes() <NEW_LINE> <DEDENT> <DEDENT> if self.answers_rr is not None: <NEW_LINE> <INDENT> for answer in self.answers_rr: <N...
Перевод DNS пакета в последоваетльность байт
625941e6e1aae11d1e74a0fe
def _read_dlog(self, exclude_beam_off): <NEW_LINE> <INDENT> other_dlg_file = _return_other_dlg(self.filename) <NEW_LINE> a_file = self.filename if osp.basename(self.filename).startswith('A') else other_dlg_file <NEW_LINE> b_file = self.filename if osp.basename(self.filename).startswith('B') else other_dlg_file <NEW_LIN...
Read in Dynalog files from .dlg files (which are renamed CSV files). Formatting follows from the Dynalog File Viewer Reference Guide.
625941e6cdde0d52a9e53478
def char_lab_IV_to_aggregate_df(fname_list): <NEW_LINE> <INDENT> df_list = [] <NEW_LINE> if len(fname_list) > 1: <NEW_LINE> <INDENT> for f in fname_list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> df_list.append(char_lab_IV_to_df(f)) <NEW_LINE> print('Read ', f) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print('...
function to return an aggregated dataframe from a list of 8 inch char lab IV tester files [fname_list] Args: fname_list (list): list of files to aggregate, must be of 8" tester type Returns: pandas.DataFrame of aggregated results
625941e61f037a2d8b94663f
def test_create_symlink(self): <NEW_LINE> <INDENT> tempdir = tempfile.mkdtemp() <NEW_LINE> tempdir2 = tempfile.mkdtemp(dir=tempdir) <NEW_LINE> src = tempfile.NamedTemporaryFile(dir=tempdir2) <NEW_LINE> origin = tempdir + "/" + os.path.basename(src.name) <NEW_LINE> helpers.create_symlink(origin, tempdir2) <NEW_LINE> ass...
Test create_symlink() Making a symlink should work as intended, origin is not yet created and will have the name of the tempfile that needs to be created. Structure is as follows: tempdir | |--tempdir2 | |-src | |-origin
625941e615baa723493c43bb
def font_defs(): <NEW_LINE> <INDENT> add_font_def( 'music', self.window().selected_font('music'), self.cb_music.isChecked() ) <NEW_LINE> add_font_def( 'brace', self.window().selected_font('brace'), self.cb_music.isChecked() ) <NEW_LINE> add_font_def( 'roman', self.window().selected_font('roman'), self.cb_roman.isChecke...
Compose the font definitions list.
625941e6627d3e7fe0d69294
def ask_openfile(initialfolder='.',title='Open',types=None): <NEW_LINE> <INDENT> if types!=None: <NEW_LINE> <INDENT> aTypes = [(type.split('|')[1],type.split('|')[0]) for type in types] <NEW_LINE> defaultExtension = aTypes[0][1] <NEW_LINE> strFiles = tkFileDialog.askopenfilename(initialdir=initialfolder,title=title,def...
Open a native file dialog that asks the user to choose a file. The path is returned as a string. Specify types in the format ['.bmp|Windows Bitmap','.gif|Gif image'] and so on.
625941e6cc0a2c11143dd2d4
def calculate_negative_balance(results): <NEW_LINE> <INDENT> def _process_negative_balance(results, result, negative_balance): <NEW_LINE> <INDENT> if result[0] < 0: <NEW_LINE> <INDENT> negative_balance = result[0] + negative_balance <NEW_LINE> <DEDENT> elif result[1] > 20000: <NEW_LINE> <INDENT> negative_balance = resu...
Calculate how much can be discounted in the month See the reference in the docs of how the ir is calculated. And in the provided url. Basically it gets a list of sell operations and calculates if there is a negative value to discount. .. warning:: This method was projected to get a list of sell_operations in a chron...
625941e64e4d5625662d4815