code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def close_file(self): <NEW_LINE> <INDENT> if self._raw_file is None or self._csv_file is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._raw_file.close() <NEW_LINE> self._csv_file = None <NEW_LINE> self._raw_file = None <NEW_LINE> return True <NEW_LINE> <DEDENT> except ValueErr...
Tries to close the current file. Return: True - File was close False - File could not be closed
625941ca7d43ff24873a2d56
def test02(self): <NEW_LINE> <INDENT> if common.verbose: <NEW_LINE> <INDENT> print('\n', '-=' * 30) <NEW_LINE> print("Running %s.test02..." % self.__class__.__name__) <NEW_LINE> <DEDENT> self.h5file.enable_undo() <NEW_LINE> self.h5file.remove_node('/agroup2') <NEW_LINE> self.h5file.create_group(self.h5file.root, 'agrou...
Test with multiple generations (Group case)
625941ca377c676e9127225e
def has_key(self, key): <NEW_LINE> <INDENT> index = bisect.bisect_left(self.keys, key) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.keys[index] == key <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return False
Return True if we have 'key'
625941ca090684286d50ed9a
def __init__(self, _exec=None, open=None, wait=None, close=None, start=None, stop=None, add_tags=None, del_tags=None, download_file=None, upload_file=None): <NEW_LINE> <INDENT> self.__exec = None <NEW_LINE> self._open = None <NEW_LINE> self._wait = None <NEW_LINE> self._close = None <NEW_LINE> self._start = None <NEW_L...
Command - a model defined in OpenAPI
625941cae1aae11d1e749d6c
def controllability_gramian(A, B, T = np.inf): <NEW_LINE> <INDENT> assert A.shape[0]==A.shape[1], "Matrix A is not square" <NEW_LINE> assert A.shape[0]==B.shape[0], "Matrix A and B do not align" <NEW_LINE> if not np.isfinite(T): <NEW_LINE> <INDENT> eigVals, eigVecs = scipy.linalg.eig(A) <NEW_LINE> assert np.max(np.real...
Compute the causal controllability Gramian of the continuous time system. The system is described as dx = A*x + B*u T is the horizon over which to compute the Gramian. If not specified, the infinite horizon Gramian is computed. Note that the infinite horizon Gramian only exists for asymptotically stable systems. ...
625941ca4f88993c3716c11d
def _compute_pred_labels(self, probabilities): <NEW_LINE> <INDENT> return tf.math.argmax(probabilities, axis=-1)
Computes predicted labels given normalized class probabilities.
625941cabe383301e01b553c
def test_lv_present_with_reduce_without_force(lv01): <NEW_LINE> <INDENT> name = "testlv01" <NEW_LINE> vgname = "testvg01" <NEW_LINE> comt = "To reduce a Logical Volume option 'force' must be True." <NEW_LINE> ret = {"name": name, "changes": {}, "result": False, "comment": comt} <NEW_LINE> mock = MagicMock(return_value=...
Test to reduce a logical volume
625941ca50812a4eaa59c3d8
def dtw_distance(s1, s2, distance_func): <NEW_LINE> <INDENT> import math <NEW_LINE> n = len(s1) <NEW_LINE> m = len(s2) <NEW_LINE> dtw_table = [[math.inf for _ in range(m+1)] for _ in range(n+1)] <NEW_LINE> dtw_table[0][0] = 0 <NEW_LINE> for i in range(1, n+1): <NEW_LINE> <INDENT> for j in range(1, m+1): <NEW_LINE> <IND...
DTW (Dynamic time warping) https://en.wikipedia.org/wiki/Dynamic_time_warping Args: s1: list, series 1. e.g. [1, 2, 2, 3] s2: list, series 2. e.g. [1, 1, 2, 2, 3] distance_func: function, used to calculate distance between s1 and s2. Returns: int, DTW distance.
625941cae5267d203edcdd53
def inverse_transform(self, y, threshold=None) -> CumlArray: <NEW_LINE> <INDENT> if has_scipy(): <NEW_LINE> <INDENT> from scipy.sparse import isspmatrix as scipy_sparse_isspmatrix <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from cuml.common.import_utils import dummy_function_always_false as scipy_s...
Transform binary labels back to original multi-class labels Parameters ---------- y : array of shape [n_samples, n_classes] threshold : float this value is currently ignored Returns ------- arr : array with original labels
625941ca23849d37ff7b3145
def serialise( self, conversion: str, price_map: PriceMap, end: datetime.date | None, ) -> SerialisedTreeNode: <NEW_LINE> <INDENT> children = [ child.serialise(conversion, price_map, end) for child in self.children ] <NEW_LINE> return SerialisedTreeNode( self.name, cost_or_value(self.balance, conversion, price_map, end...
Serialise the account. Args: end: A date to use for cost conversions.
625941cad58c6744b4257d16
def __init__(self, filename, listfile=True): <NEW_LINE> <INDENT> if hasattr(filename, 'read'): <NEW_LINE> <INDENT> self.file = filename <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.file = open(filename, 'rb') <NEW_LINE> <DEDENT> self.header = self.read_header() <NEW_LINE> self.hash_table = self.read_table('hash')...
Create a MPQArchive object. You can skip reading the listfile if you pass listfile=False to the constructor. The 'files' attribute will be unavailable if you do this.
625941ca009cb60464c63467
def TrainWithTuning(data_path,class_indices,skf=StratifiedKFold(n_splits=5, random_state=1291295159), clf=svm.SVC(), param_grid={"clf__kernel": ['linear', 'poly', 'rbf'], "clf__C": [1,2,3]}, img_sizes=[50,100,150,200,250], Hog_orientations=[7, 8, 9,10, 11], Hog_pixels_per_cell= [(8,8)], Hog_cells_per_block=[(4,4)], Hog...
" documentation: this function train the whole pipeline with the given parameters using cross validation method and finds the optimal parameters. input data_path: the path to the data input class_indices: classes to apply tuning process on input skf: stratified cross validation object input clf: the classifier object ...
625941caec188e330fd5a855
def decorator(method): <NEW_LINE> <INDENT> if callable(method): <NEW_LINE> <INDENT> @_wraps(method) <NEW_LINE> def wrapped(*args, **kwargs): <NEW_LINE> <INDENT> return method(*args, **kwargs) <NEW_LINE> <DEDENT> return wrapped <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("'%s' object is not callable" %...
@deprecated Will be changed next minor.
625941ca07f4c71912b11537
def draw(): <NEW_LINE> <INDENT> screen.fill(BLACK) <NEW_LINE> bubble_grid.draw(screen) <NEW_LINE> ship.draw(screen) <NEW_LINE> bullets.draw(screen) <NEW_LINE> droppers.draw(screen) <NEW_LINE> score.draw(screen) <NEW_LINE> if new_level_msg: <NEW_LINE> <INDENT> screen.draw.text(new_level_msg , centery=(HEIGHT//4), center...
PGZero's global draw() function
625941ca099cdd3c635f0d10
def replace(self, mapping, allow_nonatomic=False): <NEW_LINE> <INDENT> if not isinstance(mapping, FunctionExpr): <NEW_LINE> <INDENT> mapping = FunctionExpr(mapping) <NEW_LINE> <DEDENT> return WriteQuery(internal.PointMutate(self, mapping, allow_nonatomic))
Replace.
625941ca38b623060ff0aea3
def storeFilesNoZip(pmid, metaData, fulltextData, outDir): <NEW_LINE> <INDENT> warnMsgs = [] <NEW_LINE> fileDir = join(outDir, 'files') <NEW_LINE> if not isdir(fileDir): <NEW_LINE> <INDENT> os.makedirs(fileDir) <NEW_LINE> <DEDENT> suppFnames = [] <NEW_LINE> suppUrls = [] <NEW_LINE> pdfFound = False <NEW_LINE> for suffi...
write files from dict (keys like main.html or main.pdf or s1.pdf, value is binary data) to directory <outDir>/files
625941ca45492302aab5e378
def bvh(filepath: str = "", filter_glob: str = "*.bvh", target: typing.Union[int, str] = 'ARMATURE', global_scale: float = 1.0, frame_start: int = 1, use_fps_scale: bool = False, update_scene_fps: bool = False, update_scene_duration: bool = False, use_cyclic: bool = False, rotate_mode: typing.Union[int, str] = 'NATIVE'...
Load a BVH motion capture file :param filepath: File Path, Filepath used for importing the file :type filepath: str :param filter_glob: filter_glob :type filter_glob: str :param target: Target, Import target type :type target: typing.Union[int, str] :param global_scale: Scale, Scale the BVH by this value :type gl...
625941ca10dbd63aa1bd2c5a
def create_session(): <NEW_LINE> <INDENT> engine = create_engine('sqlite:///todo.sqlite') <NEW_LINE> Base.metadata.create_all(engine) <NEW_LINE> Base.metadata.bind = engine <NEW_LINE> DBSession = sessionmaker(bind=engine) <NEW_LINE> return(DBSession())
Creates a sesson object @return: session object
625941ca187af65679ca51d5
def secpera(): <NEW_LINE> <INDENT> return 3.15569259747e7
Number of seconds per year.
625941ca07d97122c4178940
def test5(self): <NEW_LINE> <INDENT> data = {"riskId": "XZ123456", "riskDesc": "XZ描述", "insuranceClassesId": "XL12345", "riskFlag": "M", "riskGroupFlag": "G", "riskShortFlag": "L"} <NEW_LINE> f = {"updateFiles": open(updateFiles, 'r')} <NEW_LINE> r = requests.post(self.base_url, data=data, files=f) <NEW_LINE> result = ...
险种名称riskName为空
625941ca5fcc89381b1e1774
@log_decorator <NEW_LINE> @debug_decorator <NEW_LINE> def save(game_map_, player_): <NEW_LINE> <INDENT> with open('save.pickable', 'wb') as handle: <NEW_LINE> <INDENT> pickle.dump([game_map_.map_, player_.position, player_.hp, player_.treasure], handle)
Function save the game Args: game_map_(GameMap): game map to save player_(Player): player to save Returns: None
625941ca56b00c62f0f1470f
def triangle_ratio(P, T): <NEW_LINE> <INDENT> A = torch.cat(triangle_angle(P, T), dim=1) <NEW_LINE> return torch.min(A, 1, keepdim=True)[0]/torch.max(A, 1, keepdim=True)[0]
Returns the ratio between the minimum and maximum angles of the given triangles Parameters ---------- P : Tensor the input points set tensor T : LongTensor the topology tensor Returns ------- Tensor the triangles ratio
625941ca66673b3332b92147
def transform(self, X): <NEW_LINE> <INDENT> return self.featurize_many(X, ignore_errors=True)
Compute features for a list of inputs
625941ca851cf427c661a5c5
def id(self): <NEW_LINE> <INDENT> return 'Networks'
Returns the unique provider id, used for identifying the provider. This string should be a unique, short, character only string, eg "qgis" or "gdal". This string should not be localised.
625941cab57a9660fec33939
def reset(self, func_wrapper, rand_state, x0=None): <NEW_LINE> <INDENT> if x0 is None: <NEW_LINE> <INDENT> self.current_location = self.lower + rand_state.random_sample( len(self.lower)) * (self.upper - self.lower) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.current_location = np.copy(x0) <NEW_LINE> <DEDENT> ini...
Initialize current location is the search domain. If `x0` is not provided, a random location within the bounds is generated.
625941ca293b9510aa2c334d
def scylla_dado_bruto(nome, gdr=None): <NEW_LINE> <INDENT> hashscy = random.getrandbits(64) <NEW_LINE> with open(f'{path_scylla_f}/etc/api/googledrv/id_folder.txt', 'r') as pegar_id_pasta: <NEW_LINE> <INDENT> id_pasta = str(pegar_id_pasta.read()) <NEW_LINE> <DEDENT> Path(f'/home/{usuario}/Documents/Oblivion').mkdir(par...
Saves the raw file of data leak/Salva o dado bruto do vazamento de dados. :param nome: Name/Nome :param gdr: Uploads to Google Drive/Sobe arquivo para o Google Drive.
625941ca3539df3088e2e401
@cli.command() <NEW_LINE> @click.option('--detail', '-l', is_flag=True, help='detailed output of ls') <NEW_LINE> @click.argument('path', type=click.STRING, required=False) <NEW_LINE> @pass_config <NEW_LINE> def ls(config, detail, path): <NEW_LINE> <INDENT> config.context.set_auto_context() <NEW_LINE> out = config.conte...
show details of ansible envionments
625941ca1d351010ab855bd2
def test_7_get_rooms_admin(self): <NEW_LINE> <INDENT> resp = self.simulate_get(headers={ 'Cookie': 'session=%s' % self.admin_session}) <NEW_LINE> self.assertEqual(resp.status, falcon.HTTP_OK) <NEW_LINE> expected_room_names = [ 'test1', 'test2', 'admin2_room', 'test3', 'test4'] <NEW_LINE> self.assertEqual( [x['name'] fo...
Attempt to get rooms superuser account.
625941ca26068e7796caed94
def namelist(self, name): <NEW_LINE> <INDENT> return self.find_namelist_item(name).namelist
Find and return the name of the inlist a valid inlist item belongs to Parameters ---------- name : str Name of a valid inlist item Returns ------- str : Name of the namelist that `name` belongs to.
625941ca3617ad0b5ed67fae
def isCentroid(self): <NEW_LINE> <INDENT> return False
Return True if this Node is a Centroid
625941ca31939e2706e4cf21
def contains_cftime_datetimes(var) -> bool: <NEW_LINE> <INDENT> return _contains_cftime_datetimes(var.data)
Check if an xarray.Variable contains cftime.datetime objects
625941ca4d74a7450ccd427a
def Set_IQR_Trig_Timeout(self,iTime): <NEW_LINE> <INDENT> self.write(f'TRIGger:GPRF:MEAS:IQRecorder:TOUT {iTime}')
Trigger Timeout, sec
625941caf8510a7c17cf97b3
def getLogger(name, level=logging.INFO, saveName="SOC_base.log"): <NEW_LINE> <INDENT> logger = logging.getLogger(name) <NEW_LINE> logger.setLevel(level) <NEW_LINE> formatter = logging.Formatter("%(asctime)s,%(name)s,%(levelname)s,%(message)s") <NEW_LINE> fh = logging.FileHandler(saveName) <NEW_LINE> fh.setFormatter(for...
Loggerを作成する。 name:Loggerの名前(string) level:Loggingのレベル(int) saveName:Loggerの保存先(string)
625941caa219f33f34628a21
def extrude(bm: BMesh, geom: List[Union[BMVert, BMEdge, BMFace]]) -> Geometry: <NEW_LINE> <INDENT> prev_faces = [f for f in bm.faces] <NEW_LINE> extruded = bmesh.ops.extrude_face_region(bm, geom=geom) <NEW_LINE> extruded_geom = extruded['geom'] <NEW_LINE> if len(bm.faces) > len(prev_faces): <NEW_LINE> <INDENT> extruded...
Extrude a geometry and return vertices, edges and faces created
625941caf9cc0f698b1406b2
def GetCreatedAtInSeconds(self): <NEW_LINE> <INDENT> return calendar.timegm(rfc822.parsedate(self.created_at))
Get the time this status message was posted, in seconds since the epoch. Returns: The time this status message was posted, in seconds since the epoch.
625941ca92d797404e304240
def delete_directory(self, path): <NEW_LINE> <INDENT> result = self.master.rmdir(path) <NEW_LINE> print(result)
Delete a file in storage servers through Naming Server path :param path: Directory path in FS that is deleted :return: result string
625941ca21bff66bcd684a0a
def __getitem__(self, path): <NEW_LINE> <INDENT> return dict.__getitem__(self, path.strip('/'))
Returns the handler function for the given path.
625941cafb3f5b602dac3749
def _is_zero(self, name, value): <NEW_LINE> <INDENT> if value <= 0: <NEW_LINE> <INDENT> raise ValueError("{} must be > 0".format(name))
Checks if value is negative or zero
625941ca4f6381625f114af1
def rpc_table_info(rpc_table: RPC_Table, html: bool=False) -> str: <NEW_LINE> <INDENT> info = [] <NEW_LINE> for name, func in rpc_table.items(): <NEW_LINE> <INDENT> info.extend(_func_info(name, func, html)) <NEW_LINE> <DEDENT> while info and not info[-1]: info.pop() <NEW_LINE> return _merge_info(info, html)
Returns the names, function signatures and doc-string of all functions in the `rpc_table` as a (more or less) well-formatted string or as HTML-snippet.
625941ca50485f2cf553ce50
def create_select(): <NEW_LINE> <INDENT> return _query("select")
Create the grammar for the 'select' statement
625941ca4f6381625f114af2
def test_unauthenicated_forbidden_from_update_route(testapp): <NEW_LINE> <INDENT> response = testapp.get('/journal/1/edit', status=403) <NEW_LINE> assert response.status_code == 403
unauthenticated user can't edit entry.
625941ca0383005118ecf699
def quant_compute_targets(ex_rois, gt_rois, stride, weights = (1.0, 1.0, 1.0, 1.0)): <NEW_LINE> <INDENT> return box_utils.quantilize_bbox_transform_inv(ex_rois, gt_rois, stride, weights).astype( np.float32, copy = False )
Compute bounding-box regression targets for an image.
625941cabe7bc26dc91cd6b8
def isPalindrome(self, x): <NEW_LINE> <INDENT> original = x <NEW_LINE> reverseInt = 0 <NEW_LINE> while x > 0: <NEW_LINE> <INDENT> reverseInt *= 10 <NEW_LINE> reverseInt += (x%10) <NEW_LINE> x /= 10 <NEW_LINE> <DEDENT> return reverseInt == original
:type x: int :rtype: bool
625941ca4428ac0f6e5ba8a9
def mainTask(self): <NEW_LINE> <INDENT> assert self.location, ( "location is not available, call SoyuzScript.setupLocation() " "before calling mainTask().") <NEW_LINE> distroseries = self.location.distroseries <NEW_LINE> self._checkParameters(distroseries) <NEW_LINE> self.logger.info("Obsoleting all packages for distro...
Execute package obsolescence procedure. Modules using this class outside of its normal usage in the main script can call this method to start the copy. In this case the caller can override test_args on __init__ to set the command line arguments. :raise SoyuzScriptError: If the distroseries is not provided or it ...
625941ca66656f66f7cbc261
def __iter__(self): <NEW_LINE> <INDENT> return self.root.__iter__()
return __iter__ function on the root node
625941ca4e4d5625662d448f
def __del__(self): <NEW_LINE> <INDENT> if not self.__preserved: <NEW_LINE> <INDENT> shutil.rmtree(self.path, ignore_errors=True)
>>> d = TempDir() >>> f = d / 'foo' >>> _ = open(f, 'w') >>> os.path.exists(f) True >>> p = str(d) >>> del d >>> os.path.exists(p) False
625941cad18da76e2353258d
def cal_p2(tmp_x1): <NEW_LINE> <INDENT> lst = [idx for idx, item in enumerate(x2) if item < tmp_x1] <NEW_LINE> return (len(lst)*1.0 / len(x2))
given a tmp_x1, return the probability of x2<tmp_x1 :param tmp_x1: :return:
625941ca8e7ae83300e4b083
def skip_line_by_sev(sev, minsev): <NEW_LINE> <INDENT> return SEVS.get(sev, 0) < SEVS.get(minsev, 0)
should we skip this line? If the line severity is less than our minimum severity, yes we should
625941caac7a0e7691ed4184
def login(self): <NEW_LINE> <INDENT> headers = {"Content-Type": "application/json"} <NEW_LINE> login_url = parse.urljoin(self.api_url, "/pluginhandler/ocplugin/authmgmt/login") <NEW_LINE> data = jsonutils.dumps({"user_name": self._user, "passwd": self._password}) <NEW_LINE> attempts = 0 <NEW_LINE> while True: <NEW_LINE...
Login to NVSD Controller.
625941caa17c0f6771cbe107
def test_register_get(client): <NEW_LINE> <INDENT> res = client.get("/register") <NEW_LINE> res = res.data.decode() <NEW_LINE> assert "EOF templates/register.html" in res
註冊頁面
625941ca76e4537e8c351729
def train(self, mode=True): <NEW_LINE> <INDENT> super(TSN_Gate, self).train(mode) <NEW_LINE> if mode and len(self.args.frozen_layers) > 0 and self.args.freeze_corr_bn: <NEW_LINE> <INDENT> for layer_idx in self.args.frozen_layers: <NEW_LINE> <INDENT> for km in self.base_model.named_modules(): <NEW_LINE> <INDENT> k, m = ...
Override the default train() to freeze the BN parameters :return:
625941ca01c39578d7e74ef2
def _prepare_pane(self, dock_widget, include_sizes=True): <NEW_LINE> <INDENT> pane = self._get_pane(dock_widget) <NEW_LINE> if include_sizes: <NEW_LINE> <INDENT> pane.width = dock_widget.widget().width() <NEW_LINE> pane.height = dock_widget.widget().height() <NEW_LINE> <DEDENT> return pane
Returns a sized PaneItem for a QDockWidget.
625941cabe383301e01b553d
@fixture('session') <NEW_LINE> def v(): <NEW_LINE> <INDENT> return '5.80'
Actual vk API version
625941ca32920d7e50b28287
def require_col(db, zls): <NEW_LINE> <INDENT> if isinstance(zls, (int, str)): <NEW_LINE> <INDENT> zls = [zls] <NEW_LINE> <DEDENT> zls = [('railway_graph_%d' % zl) if isinstance(zl, int) else zl for zl in zls] <NEW_LINE> empty_collections = [zl for zl in zls if db[zl].count() == 0] <NEW_LINE> if empty_collections: <NEW_...
Make sure all collections `zls` are present in `db` and abort the program if not. :param db: connection that should contain required collections :type db: :class:`pymongo.Connection` :param zls: required collections :type zls: int, str or sequence of int or str
625941ca6e29344779a626c9
def affine_forward(x, w, b): <NEW_LINE> <INDENT> out = None <NEW_LINE> xx = np.reshape(x, (x.shape[0], -1)) <NEW_LINE> xx = np.hstack([xx, np.ones((xx.shape[0], 1))]) <NEW_LINE> ww = np.vstack([w, b]) <NEW_LINE> out = xx.dot(ww) <NEW_LINE> pass <NEW_LINE> cache = (x, w, b) <NEW_LINE> return out, cache
Computes the forward pass for an affine (fully-connected) layer. The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N examples, where each example x[i] has shape (d_1, ..., d_k). We will reshape each input into a vector of dimension D = d_1 * ... * d_k, and then transform it to an output vector of di...
625941cad268445f265b4f25
def init_stats(): <NEW_LINE> <INDENT> return {"step_time": 0.0, "slot_train_loss": 0.0, "intent_train_loss": 0.0, "predict_count": 0.0, "word_count": 0.0, "sequence_count": 0.0, "grad_norm": 0.0}
Initialize statistics that we want to accumulate.
625941ca796e427e537b067d
def test_stack_upgrade(self): <NEW_LINE> <INDENT> base = self.make_branch_and_tree('base', format=self.scenario_old_format) <NEW_LINE> self.build_tree(['base/foo']) <NEW_LINE> base.commit('base commit') <NEW_LINE> stacked = base.bzrdir.sprout('stacked', stacked=True) <NEW_LINE> self.assertTrue(stacked.open_branch().get...
Correct checks when stacked-on repository is upgraded. We initially stack on a repo with the same rich root support, we then upgrade it and should fail, we then upgrade the overlaid repository.
625941ca96565a6dacc8f783
def LUT(rom, **kwargs): <NEW_LINE> <INDENT> return LUTN(rom, **kwargs)
n-bit LUT I[n] -> n
625941cae1aae11d1e749d6e
def connected(self): <NEW_LINE> <INDENT> return self._pvobj.connected
Check PV connection.
625941ca8da39b475bd6502b
def printstate(): <NEW_LINE> <INDENT> for x in range(0, len(main.MAZE)): <NEW_LINE> <INDENT> s = "" <NEW_LINE> for y in range(0, len(main.MAZE[x])): <NEW_LINE> <INDENT> s = s + main.MAZE[x][y] <NEW_LINE> <DEDENT> print(s)
Ausgabe des aktuellen Status
625941ca4f88993c3716c11f
def get_confusion_matrix(actual, predicted): <NEW_LINE> <INDENT> m = np.zeros((9,9)) <NEW_LINE> for a, b in zip(actual, predicted): <NEW_LINE> <INDENT> m[a,b] += 1 <NEW_LINE> <DEDENT> class_totals = np.sum(m, axis=1) <NEW_LINE> for i in xrange(9): <NEW_LINE> <INDENT> m[i] = m[i]*1. / class_totals[i]*1. <NEW_LINE> <DEDE...
Returns the confusion matrix
625941cabe383301e01b553e
def _processing_terms(self, term, previous_states_ind): <NEW_LINE> <INDENT> if term.startswith("_"): <NEW_LINE> <INDENT> var_ind, new_keys = previous_states_ind[term] <NEW_LINE> shape = (len(var_ind),) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cont_dim = self.cont_dim.get(term, 1) <NEW_LINE> shape = hlpst.input_sha...
processing a specific term to get new keys from the term, an iterator with variable indices and matching keys
625941cab7558d58953c4fcc
def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10, dropout=0, use_batchnorm=False, reg=0.0, weight_scale=1e-2, dtype=np.float32, seed=None): <NEW_LINE> <INDENT> self.use_batchnorm = use_batchnorm <NEW_LINE> self.use_dropout = dropout > 0 <NEW_LINE> self.reg = reg <NEW_LINE> self.num_layers = 1 + len(hid...
Initialize a new FullyConnectedNet. Inputs: - hidden_dims: A list of integers giving the size of each hidden layer. - input_dim: An integer giving the size of the input. - num_classes: An integer giving the number of classes to classify. - dropout: Scalar between 0 and 1 giving dropout strength. If dropout=0 then th...
625941caa79ad161976cc1fd
def update(self, new_categories): <NEW_LINE> <INDENT> db = current.db <NEW_LINE> if self.last_cat == None: <NEW_LINE> <INDENT> self.user_condition = util.get_available_conditions().conditionNumber <NEW_LINE> self.count_pair = -1 <NEW_LINE> current.log_action(self.user, self.problem, 'create_user_model', {'condition':se...
new_categories is an array. It's length can be 1 or 2
625941ca50812a4eaa59c3da
def addNodeStyle(self, style_name, font_id = None, font_set = None, background_color = None, transparency = None): <NEW_LINE> <INDENT> show = False <NEW_LINE> if show: print('in addNodeStyle() with style_name {style_name}, font_id {font_id}, font_set {font_set}, background_color {background_color}, transparency {transp...
add a new style for a node. If you wish to reuse an already existing font, you can specify it using its font_id which you can find using the findFont() method. If you wish to specify a font, use font_family, font_style, font_size, font_color. If that font description already exists, its font_id will be found and used...
625941ca283ffb24f3c559b9
def find_phantomjs_path(): <NEW_LINE> <INDENT> candidate_path = [d+'/phantomjs' for d in os.getenv('PATH', '').split(':')] <NEW_LINE> for path in candidate_path: <NEW_LINE> <INDENT> if os.path.exists(path): <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> <DEDENT> return None
Find path of PhantomJS :returns: Path of PhantomJS (If it is not found, return None) :rtype: str or None
625941cabaa26c4b54cb11d7
def close_window(self): <NEW_LINE> <INDENT> print(self.wordhistory) <NEW_LINE> sys.exit()
Method for exiting the application
625941cabde94217f3682ea9
def pop(data: bytes) -> typing.Tuple[TSerializable, bytes]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> blength, data = data.split(b':', 1) <NEW_LINE> length = int(blength) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("not a tnetstring: missing or invalid length prefix: {}".format(data))...
This function parses a tnetstring into a python object. It returns a tuple giving the parsed object and a string containing any unparsed data from the end of the string.
625941cacb5e8a47e48b7b62
def unparse(self, text): <NEW_LINE> <INDENT> words = text.split() <NEW_LINE> words = self.__process_input_text(words) <NEW_LINE> words = ['$psom', '$som'] + words + ['$eom'] <NEW_LINE> for w1, w2, w3 in self.__triples(words): <NEW_LINE> <INDENT> w1 = self.__strip_control_signals(w1) <NEW_LINE> w2 = self.__strip_control...
Undoes the parsing of the supplied text (if possible), removing all associations it would form if parsed. Keyword arguments: text -- The raw text to be unparsed, as a string.
625941cad99f1b3c44c67646
def __call__(self, event): <NEW_LINE> <INDENT> x, y = event.mouseevent.xdata, event.mouseevent.ydata <NEW_LINE> annotation = self.annotations[event.artist.axes] <NEW_LINE> if x is not None: <NEW_LINE> <INDENT> if not self.display_all: <NEW_LINE> <INDENT> for ann in self.annotations.values(): <NEW_LINE> <INDENT> ann.set...
Intended to be called through "mpl_connect".
625941ca71ff763f4b549742
def __init__(self): <NEW_LINE> <INDENT> self.PortraitSet = None
:param PortraitSet: 用户喜好的明星画像数组 :type PortraitSet: list of StarPortrait
625941ca91af0d3eaac9bad0
def format_ticks(ax, xy, scale=1., format="%.1f"): <NEW_LINE> <INDENT> if xy == 'x' or xy == 'xy': <NEW_LINE> <INDENT> locx = ax.get_xticks() <NEW_LINE> ax.set_xticks(locx, map(lambda x: format % x, locx*scale)) <NEW_LINE> <DEDENT> if xy == 'y' or xy == 'xy': <NEW_LINE> <INDENT> locy = ax.get_yticks() <NEW_LINE> ax.set...
Reformat numbers at x or y - axis. The scale can be changed to display e.g. MHz instead of Hz. The number format can be changed as well. Parameters ---------- ax : axes object xy : string, either 'x', 'y' or 'xy' select corresponding axis (axes) for reformatting scale : real (default: 1.) rescaling fac...
625941ca507cdc57c6306d91
def error(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['sep'] = kwargs.get('sep', ' ') <NEW_LINE> kwargs['end'] = kwargs.get('end', '\n') <NEW_LINE> text = kwargs['sep'].join([str(arg) for arg in args]) + kwargs['end'] <NEW_LINE> full_text = '{}\nHand: {}\nTracking: {}'.format(text.strip(), self.hand, self.tracki...
Stop play due to a bot malfunction. (None) Parameters: The parameters are the same as the built-in bot function.
625941ca8a349b6b435e822b
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
625941cad10714528d5ffd9a
def _initSanityTests(self): <NEW_LINE> <INDENT> tabSanityTests = QtGui.QWidget() <NEW_LINE> layoutSanityTests = QtGui.QFormLayout(tabSanityTests) <NEW_LINE> self.cbPatientGenderMatch = QtGui.QCheckBox() <NEW_LINE> self.cbPatientGenderMatch.setChecked(ConfigDetails().patientGenderMatch) <NEW_LINE> self.cbPatientDobMatch...
Initialise Data sanity tests UI tab
625941ca004d5f362079a3eb
def _writeString(self, obj, use_reference=True): <NEW_LINE> <INDENT> string = to_bytes(obj, "utf-8") <NEW_LINE> if use_reference and isinstance(obj, JavaString): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> idx = self.references.index(obj) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.references.appen...
Appends a string to the serialization stream :param obj: String to serialize :param use_reference: If True, allow writing a reference
625941cafbf16365ca6f627b
def cci(series, window=14): <NEW_LINE> <INDENT> price = typical_price(series) <NEW_LINE> typical_mean = rolling_mean(price, window) <NEW_LINE> res = (price - typical_mean) / (.015 * np.std(typical_mean)) <NEW_LINE> return pd.Series(index=series.index, data=res)
compute commodity channel index
625941caa934411ee375174b
def load_graphs_cost(name): <NEW_LINE> <INDENT> x,y,low_cost_list, best_gen_size_list,best_fly_size_list = load_pickles_cost(name) <NEW_LINE> cost_graph(low_cost_list,x,y) <NEW_LINE> best_gen_size_graph(best_gen_size_list,x,y) <NEW_LINE> best_fly_size_graph(best_fly_size_list,x,y)
graphs lowest cost (in dollar per kilowatt hour), and their respective flywheel and generator sizes Inputs: name: string that was used to label the files when loading them
625941ca099cdd3c635f0d12
def valid_dbname(dbname): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if VALID_DB_NAMES.match(dbname) is not None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return False
Test a dbname string to see if it looks valid.
625941caadb09d7d5db6c847
def plan_bid_cb(self, msg): <NEW_LINE> <INDENT> if msg.header.frame_id != self.identifier: <NEW_LINE> <INDENT> self.plan_bid_lock.acquire() <NEW_LINE> self.plan_bids[msg.header.frame_id] = msg.bid <NEW_LINE> self.plan_bid_lock.release()
Update internal state to reflect other agent's PPI bid. msg - message of type PlanBid msg.header - contains the sender's ID as frame_id msg.bid - agent's PPI (potential path improvement) for current planning iteration
625941ca29b78933be1e5764
def internalpatch(ui, repo, patchobj, strip, prefix='', files=None, eolmode='strict', similarity=0): <NEW_LINE> <INDENT> backend = workingbackend(ui, repo, similarity) <NEW_LINE> return patchbackend(ui, backend, patchobj, strip, prefix, files, eolmode)
use builtin patch to apply <patchobj> to the working directory. returns whether patch was applied with fuzz factor.
625941caa4f1c619b28b00f2
def forward(self, v_j_filt_prime): <NEW_LINE> <INDENT> fnn_enc_output = relu(self.fnn_enc(v_j_filt_prime)) <NEW_LINE> fnn_dec_output = relu(self.fnn_dec(fnn_enc_output)) <NEW_LINE> v_j_filt = fnn_dec_output.mul(v_j_filt_prime) <NEW_LINE> return v_j_filt
The forward pass. :param v_j_filt_prime: The output of the Masker. :type v_j_filt_prime: torch.Tensor :return: The output of the Denoiser. :rtype: torch.Tensor
625941caac7a0e7691ed4185
def reset_layout(self, *args) -> None: <NEW_LINE> <INDENT> self._loop.widget = self._body <NEW_LINE> self._loop.draw_screen()
Resets the console UI to the default layout (hides the menu)
625941ca5fc7496912cc3a35
def prepare(self): <NEW_LINE> <INDENT> self.detCumulativeAcceptanceValues() <NEW_LINE> self.detAcceptanceRateValues() <NEW_LINE> self.detCumulativeRejectanceValues() <NEW_LINE> self.detRejectanceRateValues()
Calculate the Acceptance and Rejectance Matrix :return:
625941ca009cb60464c6346a
def _isHierarchyRoot (self): <NEW_LINE> <INDENT> base = self.__baseTypeDefinition <NEW_LINE> return isinstance(base, SimpleTypeDefinition) or base.isUrTypeDefinition()
Return C{True} iff this is the root of a complex type definition hierarchy.
625941ca3c8af77a43ae3858
def settingsDeploy(self, action='start', options={}): <NEW_LINE> <INDENT> os.environ['DJANGO_SETTINGS_MODULE'] = TEST_SETTINGS <NEW_LINE> options.update({'settings': TEST_SETTINGS}) <NEW_LINE> return self.deploy(action, options)
Use the hendrix test project to test the bash deployment flow path
625941cadd821e528d63b261
def _calc_xi_2halo(bias, xi_mm, xi_2halo): <NEW_LINE> <INDENT> NR = len(xi_mm) <NEW_LINE> cluster_toolkit._lib.calc_xi_2halo(NR, bias, _dcast(xi_mm), _dcast(xi_2halo)) <NEW_LINE> return
Direct call to the vectorized version of xi_2halo(R).
625941cad53ae8145f87a329
def get_min_popularity(artist_dict, max_artists): <NEW_LINE> <INDENT> popularity = [] <NEW_LINE> for artist in artist_dict: <NEW_LINE> <INDENT> popularity.append(artist['popularity']) <NEW_LINE> <DEDENT> popularity.sort(reverse=True) <NEW_LINE> return popularity[max_artists]
Get the minimum popularity to be part of the top artists | dict, int --> int
625941caa8370b7717052958
def init(cls): <NEW_LINE> <INDENT> return _KeyHandlerRegisterer(cls.__name__, cls.__bases__, cls.__dict__.copy())
Rewrite the class to include the _KeyHandlerRegisterer metaclass.
625941ca63b5f9789fde719d
def test_person_delete(self): <NEW_LINE> <INDENT> response = self.client.open( '/people/{uuid}'.format(uuid='uuid_example'), method='DELETE') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8'))
Test case for person_delete Delete this person
625941caaad79263cf390af8
def _getbkfile(repo): <NEW_LINE> <INDENT> fp, pending = txnutil.trypending(repo.root, repo.svfs, "bookmarks") <NEW_LINE> return fp
Hook so that extensions that mess with the store can hook bm storage. For core, this just handles wether we should see pending bookmarks or the committed ones. Other extensions (like share) may need to tweak this behavior further.
625941ca07d97122c4178942
def append_after(filename="", search_string="", new_string=""): <NEW_LINE> <INDENT> with open(filename, 'r') as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> len_targetstr = len(search_string) <NEW_LINE> for y in range(len(lines)): <NEW_LINE> <INDENT> line = lines[y] <NEW_LINE> if search_string in line: <NEW_...
inserts new_string after a line that contains search_string
625941ca85dfad0860c3af13
def generate_bn_credential(self, system_typ_cd, corp_num, corp_info, effective_event=None): <NEW_LINE> <INDENT> if "bn_9" in corp_info and corp_info["bn_9"] and 0 < len(corp_info["bn_9"]): <NEW_LINE> <INDENT> effective_date = corp_info["recognition_dts"] if corp_info["recognition_dts"] else effective_event['effective_d...
Generate a BN credential.
625941ca5fcc89381b1e1776
def get_missing_courses(self, student): <NEW_LINE> <INDENT> for key, value in student.items(): <NEW_LINE> <INDENT> course_taken = set([x for x in student[key].get_courses()]) <NEW_LINE> student_major = student[key].major <NEW_LINE> remainder = set(self.majors_data[student_major]) - course_taken <NEW_LINE> student[key]....
get the missing courses for the major required by students
625941ca38b623060ff0aea6
def cal_conf_exist(self): <NEW_LINE> <INDENT> min_paper_list = self.paper_list1 if len(self.paper_list1) < len(self.paper_list2) else self.paper_list2 <NEW_LINE> max_paper_list = self.paper_list1 if len(self.paper_list1) >= len(self.paper_list2) else self.paper_list2 <NEW_LINE> conf_number2 = self.get_conf_frequency(ma...
similarity of representative community. :return:
625941cad268445f265b4f26
def splitinbytes(self,data,nbits,pos): <NEW_LINE> <INDENT> data = self.maskupperbits(data, nbits) <NEW_LINE> shift = (8 - (nbits & 0x7) + 8 - pos) & 0x7 <NEW_LINE> data <<= shift <NEW_LINE> nbits += shift <NEW_LINE> datainbytes = () <NEW_LINE> loopcount = 1 + (nbits - 1) // 8 <NEW_LINE> for i in range(loopcount): <NEW_...
Split input data in bytes to allow insertion in buffer by OR operation.
625941ca66673b3332b92149
def pretty_print(string, string_type=None): <NEW_LINE> <INDENT> string = str(string) <NEW_LINE> _string_length = pprint_dict[string_type] if string_type is not None else pprint_dict[string] <NEW_LINE> _right_justified_strings = ['localhost', 'remotehost', 'mem', 'timer', 'bgp_prefix'] <NEW_LINE> if string in _right_jus...
Take care of determining which fields should be justified to each side to improve readability
625941ca3539df3088e2e403
def flush(self): <NEW_LINE> <INDENT> self.cErrorMessage = "" <NEW_LINE> self.nErrorNumber = 0 <NEW_LINE> lbReturn = self.cbt.flush() <NEW_LINE> if (not lbReturn) and (self.cbt.geterrornumber != 0): <NEW_LINE> <INDENT> self.cErrorMessage = self.cbt.geterrormessage() <NEW_LINE> self.nErrorNumber = self.cbt.geterrornumber...
Call this function immediately after a gatherfromarray() to force the data changes to be written immediately to the disk. This will ensure that other users of the data will see it immediately. Otherwise CodeBase will buffer writes and could delay these writes until the buffer is full. This action applies only to the...
625941ca046cf37aa974ce00
def set_compose_session(request): <NEW_LINE> <INDENT> import uuid <NEW_LINE> randid = str(uuid.uuid4()).replace("-", "") <NEW_LINE> request.session["compose_mail"] = {"id": randid, "attachments": []} <NEW_LINE> return randid
Initialize a new "compose" session. It is used to keep track of attachments defined with a new message. Each new message will be associated with a unique ID (in order to avoid conflicts between users). :param request: a Request object. :return: the new unique ID.
625941ca07d97122c4178943
def test_sandbox_command_succeeds(self): <NEW_LINE> <INDENT> adapter = SandboxAdapter('https://localhost', 'ACCESS-TOKEN') <NEW_LINE> print_var_type_n_val(var001 = adapter, pointer = "#23456UHGDCVRFgfff") <NEW_LINE> expected_result = { 'message': 'Hello, IOTA!', } <NEW_LINE> responses = deque([ create_http_respons...
Sending a sandbox command to the node.
625941ca3d592f4c4ed1d127