code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@CoroutineInputTransformer.wrap <NEW_LINE> def ipy_prompt(): <NEW_LINE> <INDENT> prompt1_re = re.compile(r'^In \[\d+\]: ') <NEW_LINE> prompt2_re = re.compile(r'^(In \[\d+\]: |^\ \ \ \.\.\.+: )') <NEW_LINE> return _strip_prompts(prompt1_re, prompt2_re)
Strip IPython's In [1]:/...: prompts.
625941f757b8e32f52483b11
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, CustomerInventory): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
625941f70a50d4780f667509
def call(self, x): <NEW_LINE> <INDENT> left_columns = x[:, :self.add_columns[0], :, :] <NEW_LINE> right_columns = x[:, -self.add_columns[0]:, :, :] <NEW_LINE> periodic_x = tf.concat([right_columns, x, left_columns], axis=1) <NEW_LINE> left_columns = periodic_x[:, :, :self.add_columns[1], :] <NEW_LINE> right_columns = p...
Add self.kernel_size[-1] columns in the geographical domain
625941f74428ac0f6e5bae6a
def random_order(self, side, price): <NEW_LINE> <INDENT> if side == "bid": <NEW_LINE> <INDENT> queue = self.bids[price] <NEW_LINE> <DEDENT> elif side == "ask": <NEW_LINE> <INDENT> queue = self.asks[price] <NEW_LINE> <DEDENT> N = len(queue) <NEW_LINE> return queue[np.random.randint(low=0, high=N)]
Return the reference number of a random order in (side, price) queue.
625941f7be8e80087fb212a7
def __remove_partially_cloned_backups(self) -> None: <NEW_LINE> <INDENT> backups = DataLayer.instance.backup_partially_cloned() <NEW_LINE> if backups: <NEW_LINE> <INDENT> self._io.title('Removing Partially Cloned Host Backups') <NEW_LINE> for backup in backups: <NEW_LINE> <INDENT> self._io.section('Removing backup {}/{...
Removes backups that are still marked "in progress" (and hence cloned partially).
625941f7e64d504609d74eb1
def run(*args, **kwargs): <NEW_LINE> <INDENT> workingDir = kwargs.pop("workingDir", None) <NEW_LINE> stdin = kwargs.pop("stdin", None) <NEW_LINE> assert not kwargs <NEW_LINE> cmd = args <NEW_LINE> try: <NEW_LINE> <INDENT> p = subprocess.Popen( cmd, cwd=workingDir, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=s...
Execute the command described by args, return a 'RunResult'. This is a convenience function which wraps the functionality of subprocess.Popen() in a manner more compatible for our uses here. Raise a 'CalledProcessError' if the return code is not equal to zero; also echo extra information to stderr. Usage examples: ...
625941f7b5575c28eb68e678
def is_link(path, use_sudo=False, verbose=False): <NEW_LINE> <INDENT> func = sudo if use_sudo else run <NEW_LINE> cmd = 'test -L "$(echo %s)"' % path <NEW_LINE> args, kwargs = [], {'warn_only': True} <NEW_LINE> if not verbose: <NEW_LINE> <INDENT> args = [hide('everything')] <NEW_LINE> <DEDENT> with settings(*args, **kw...
Return True if the given path is a symlink on the current remote host. If ``use_sudo`` is True, will use `.sudo` instead of `.run`. `.is_link` will, by default, hide all output. Give ``verbose=True`` to change this.
625941f7a934411ee3751d07
def main(): <NEW_LINE> <INDENT> current_version = _read_current_version() <NEW_LINE> print(f"Read current version as: {current_version}") <NEW_LINE> next_version = parse_version_str(current_version).bump_minor.version_str <NEW_LINE> print(f"Next version: {next_version}") <NEW_LINE> _set_github_output("next_version", ne...
Run the actual script logic. Args: version_verride: should contain Github Action input. Empty strings are treated as "nil" values. This is because that's how bash passes nils.
625941f7bde94217f368345c
def add(self, address: int): <NEW_LINE> <INDENT> A: BinaryNumber = self.registers[Processor.ACCUMULATOR] <NEW_LINE> B: BinaryNumber = self.registers[address] <NEW_LINE> C: BinaryNumber = BinaryNumber() <NEW_LINE> carry = 0 <NEW_LINE> for i in reversed(range(BinaryNumber.LENGTH)): <NEW_LINE> <INDENT> if A[i] + B[i] + ca...
Instruction: ADD, R Performs addition to value in the accumulator such that accumulator += register_R.
625941f729b78933be1e5d15
def delete_first(self): <NEW_LINE> <INDENT> deleted = self.head <NEW_LINE> if self.head: <NEW_LINE> <INDENT> self.head = self.head.next <NEW_LINE> <DEDENT> return deleted
Delete the first (head) element in the LinkedList as return it
625941f7a79ad161976cc7b7
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
625941f7eab8aa0e5d26e1cc
def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True): <NEW_LINE> <INDENT> self.encoding = encoding <NEW_LINE> self.object_hook = object_hook <NEW_LINE> self.parse_float = parse_float <NEW_LINE> self.parse_int = parse_int <NEW_LINE> self.parse_constant =...
``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no effect when decoding ``unicode`` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. ``object_hoo...
625941f79b70327d1c4e144a
def conditional_space(self, condition): <NEW_LINE> <INDENT> if self._is_symbolic: <NEW_LINE> <INDENT> self <NEW_LINE> <DEDENT> domain = self.where(condition) <NEW_LINE> prob = self.probability(condition) <NEW_LINE> density = {key: val / prob for key, val in self._density.items() if domain._test(key)} <NEW_LINE> return ...
This method is used for transferring the computation to probability method because conditional space of random variables with symbolic dimensions is currently not possible.
625941f71d351010ab85618c
def free_energy(self,X): <NEW_LINE> <INDENT> X_score = T.dot(X, self.W) + self.c <NEW_LINE> vbias_term = T.dot(X, self.b) <NEW_LINE> hidden_term = T.sum( T.nnet.softplus(X_score), axis=1) <NEW_LINE> return -hidden_term - vbias_term
Function to compute the free energy
625941f70383005118ecfc51
@app.route('/isolist/', defaults = {'start': 0, 'length': 50, 'view_type': "normal" }) <NEW_LINE> @app.route('/isolist/all/', defaults = {'start': 0, 'length': 99999, 'view_type': "all" }) <NEW_LINE> @app.route('/isolist/<int:start>/<int:length>/', defaults = {'view_type': "normal" }) <NEW_LINE> def index(start, length...
This controller method provides the logic behind displaying the isolist.html view
625941f75fc7496912cc3fef
def main(): <NEW_LINE> <INDENT> preprocessor = DATA_PREPROCESSOR('tweets.json','labels-train+dev.tsv','labels-test.tsv') <NEW_LINE> train, validation, test, = preprocessor.preprocess_data() <NEW_LINE> x_train, x_test,x_validation, y_train, y_test, y_validation = preprocessor.toke...
main function Runs 5 model one by one DEBUG_PRINT : Make this flag true if user wants to see various plots and CM
625941f78da39b475bd655ee
def percent_translated(self): <NEW_LINE> <INDENT> total = len([e for e in self if not e.obsolete]) <NEW_LINE> if total == 0: <NEW_LINE> <INDENT> return 100 <NEW_LINE> <DEDENT> translated = len(self.translated_entries()) <NEW_LINE> return int(translated * 100 / float(total))
Convenience method that returns the percentage of translated messages.
625941f7f548e778e58cdbf2
def test_cycle(self): <NEW_LINE> <INDENT> from itertools import cycle as itertools_cycle <NEW_LINE> class Cycle(core.Tag): <NEW_LINE> <INDENT> name = 'classy_cycle' <NEW_LINE> options = core.Options( arguments.MultiValueArgument('values'), 'as', arguments.Argument('varname', required=False, resolve=False), ) <NEW_LINE>...
This test re-implements django's cycle tag (because it's quite crazy) and checks if it works.
625941f7e8904600ed9f25aa
def test_filter_no_transform() -> None: <NEW_LINE> <INDENT> result = get_query_filters( {"filter[name]": "John", "filter[lastName]": "Coltrane", "limit": 50} ) <NEW_LINE> assert result == {"name": "John", "lastName": "Coltrane"}
The transform works with no filter.
625941f7498bea3a759ba11f
def _get_url(self) -> str: <NEW_LINE> <INDENT> url, _user, _domain = parse_account_user(self.account.user) <NEW_LINE> return url
Get matrix server url
625941f7b7558d58953c5577
def ordering(self, inverse_count): <NEW_LINE> <INDENT> ordering = np.ones(self._K, dtype=int) * -1 <NEW_LINE> for action, val in enumerate(inverse_count): <NEW_LINE> <INDENT> for idx, established in enumerate(ordering): <NEW_LINE> <INDENT> if established > -1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if val == ...
Compute ordering from inverse count vector
625941f77047854f462a1a73
def update(self, var, fn, args=(), kwargs=None, group=True): <NEW_LINE> <INDENT> _require_cross_replica_or_default_context_extended(self) <NEW_LINE> if kwargs is None: <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> <DEDENT> with self._container_strategy().scope(): <NEW_LINE> <INDENT> return self._update(var, fn, args, kwar...
Run `fn` to update `var` using inputs mirrored to the same devices. If `var` is mirrored across multiple devices, then this implements logic like: ``` results = {} for device, v in var: with tf.device(device): # args and kwargs will be unwrapped if they are mirrored. results[device] = fn(v, *args, **kwargs)...
625941f78a43f66fc4b546cf
def modify(self, transformer): <NEW_LINE> <INDENT> return Effect(ModifyReference(ref=self, transformer=transformer))
Return an Effect that updates the value with ``fn(old_value)``. :param transformer: Function that takes old value and returns the new value. This is not guaranteed to be linearizable if multiple threads are modifying the reference at the same time. It is safe to assume consistent modification as long as you're no...
625941f7e5267d203edce306
def visualizeQuakes(data_file): <NEW_LINE> <INDENT> data_dict = readFile(data_file) <NEW_LINE> quake_centroids = createCentroids(6, data_dict) <NEW_LINE> clusters = createClusters(6, quake_centroids, data_dict, 7) <NEW_LINE> draw = eqDraw(6, data_dict, clusters) <NEW_LINE> return None
(str) -> None Visualizes the earthquake clusters. Calls other readFile, createCentroids, createClusters, and visualizeQuakes. Returns None.
625941f7796e427e537b0c3d
def __init__(self, resource, use_container=False, **options): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resource._meta <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise TypeError("``%r`` is not a valid type for a related field." % resource) <NEW_LINE> <DEDENT> self.of = resource <NEW_LINE> self.us...
Initialisation of a CompositeField. :param resource: :param use_container: Special flag for codecs that support containers or just multiple instances of a sub element (ie XML). :param empty: This collection can be empty :param options: Additional options passed to :py:class:`odin.fields.Field` super class.
625941f7e76e3b2f99f3ae72
def get_tag(self, tag: Union[MISPTag, int, str, UUID], pythonify: bool=False) -> Union[dict, MISPTag]: <NEW_LINE> <INDENT> tag_id = self.__get_uuid_or_id_from_abstract_misp(tag) <NEW_LINE> r = self._prepare_request('GET', f'tags/view/{tag_id}') <NEW_LINE> tag_r = self._check_json_response(r) <NEW_LINE> if not (self.glo...
Get a tag by id.
625941f78e05c05ec3eea9ec
def testVSModifyInvalidInput(self): <NEW_LINE> <INDENT> pass
Test VSModifyInvalidInput
625941f74f6381625f1150ac
def __delitem__(self, key): <NEW_LINE> <INDENT> raise NotImplemented
NotImplemented, normally we should not want delete options
625941f776d4e153a657f1a4
def parity_test_suite(): <NEW_LINE> <INDENT> testit(is_binary('1001010') == True) <NEW_LINE> testit(is_binary('100 1010') == False) <NEW_LINE> testit(is_binary('100') == False) <NEW_LINE> testit(is_div_by_sevens('1001010') == True) <NEW_LINE> testit(is_div_by_sevens('100100011010010100001') == True) <NEW_LINE> testit(i...
Designed to test the following functions: is_binary(bitstring) is_div_by_sevens(bitstring) split_into_sevens(bitstring) add_parity(list_of_chunks) run_all(bitstring)
625941f73617ad0b5ed68568
def next_batch(array_dict: Dict[str, np.ndarray], shuffled_indices: np.ndarray, cur_position: int, batch_size: int) -> Tuple[Dict[str, np.ndarray], int]: <NEW_LINE> <INDENT> indices, next_position = get_batch_indices( shuffled_indices, batch_size, cur_position) <NEW_LINE> subset_arrays = {x: y[indices] for x, y in arra...
Returns the next batch of arrays. Args: array_dict: A dictionary of arrays. shuffled_indices: The order of indices to traverse. cur_position: Where in the indices we currently are. batch_size: The size of batches to return. Returns: A tuple with the current batch of arrays and the next position.
625941f74d74a7450ccd4838
def pc_input_buffers_full(self, *args): <NEW_LINE> <INDENT> return _analog_swig.pll_freqdet_cf_sptr_pc_input_buffers_full(self, *args)
pc_input_buffers_full(pll_freqdet_cf_sptr self, int which) -> float pc_input_buffers_full(pll_freqdet_cf_sptr self) -> pmt_vector_float
625941f7796e427e537b0c3e
def receive(self, num_bytes): <NEW_LINE> <INDENT> self.write_cmd(self.cr_addr, 0x02) <NEW_LINE> self.write_cmd(self.rfd_addr, 0x0) <NEW_LINE> self.write_cmd(self.dtr_addr, 0x101 | (self.iic_addr << 1)) <NEW_LINE> cr_reg = 0x05 <NEW_LINE> if num_bytes == 1: <NEW_LINE> <INDENT> cr_reg |= 0x10 <NEW_LINE> <DEDENT> self.wri...
This method receives IIC bytes from the device. Parameters ---------- num_bytes : int Number of bytes to be received from the device. Returns ------- iic_bytes : list A list of 8-bit bytes received from the driver. Raises ------ RuntimeError Timeout when waiting for the RX FIFO to fill.
625941f799fddb7c1c9de9ff
def unfollow(self, followerId, followeeId): <NEW_LINE> <INDENT> tweets, followers = self.tweets, self.followers <NEW_LINE> if followeeId not in followers[followerId]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> followers[followerId].remove(followeeId)
Follower unfollows a followee. If the operation is invalid, it should be a no-op. :type followerId: int :type followeeId: int :rtype: void
625941f7d8ef3951e3243bb0
def get_object_or_none(klass, *args, **kwargs): <NEW_LINE> <INDENT> queryset = _get_queryset(klass) <NEW_LINE> try: <NEW_LINE> <INDENT> return queryset.get(*args, **kwargs) <NEW_LINE> <DEDENT> except queryset.model.DoesNotExist: <NEW_LINE> <INDENT> return None
try to return the class instance and return None if none existent.
625941f7bd1bec0571d90ca1
def test_ceildiv(self): <NEW_LINE> <INDENT> self.assertEqual(utils.ceildiv(3, 1), 3) <NEW_LINE> self.assertEqual(utils.ceildiv(6, 3), 2) <NEW_LINE> self.assertEqual(utils.ceildiv(7, 3), 3) <NEW_LINE> self.assertEqual(utils.ceildiv(8, 3), 3) <NEW_LINE> self.assertEqual(utils.ceildiv(-6, 3), -2) <NEW_LINE> self.assertEqu...
Test the ceil division
625941f77cff6e4e81117ff7
def run( self, new_sample_x: np.array, new_sample_mu: float, new_sample_sigma: float, new_sample_acq: float, mu: np.array, sigma: np.array, acq_values: np.array, iteration: int ) -> Tuple[np.array, float, float, float, np.array, np.array, np.array]: <NEW_LINE> <INDENT> pass
actual callback function to be executed. :param new_sample_x: found optima which would be next sample in the optimizer :param new_sample_mu: mu value estimated for the found optima/ next sample :param new_sample_sigma: sigma value estimated for the found optima/ next sample :param new_sample_acq: acquisition value est...
625941f7d6c5a102081446c2
def split(input, split_absolut_path, delimiter=';', row_limit=1000, output_name_template='%s_%s.csv', keep_headers=True): <NEW_LINE> <INDENT> if not os.path.exists(input): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if 0 == os.path.getsize(input): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> filename = os.path.spl...
Split csv file, encoding of the file must be uft-8.
625941f755399d3f05588d2b
def book_writer(trigram_d): <NEW_LINE> <INDENT> text_output = list(random.choice(list(trigram_d.keys())).split()) <NEW_LINE> while len(text_output) < 301: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> text_output += [random.choice(trigram_d[" ".join(text_output[-2:])])] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <I...
keeps adding text until word count is 300, then puts the text into my_new_book.txt
625941f70383005118ecfc52
def slice_locs(self, start=None, end=None, strict=False): <NEW_LINE> <INDENT> if start is None: <NEW_LINE> <INDENT> start_slice = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not isinstance(start, tuple): <NEW_LINE> <INDENT> start = start, <NEW_LINE> <DEDENT> start_slice = self._partial_tup_index(start, side='lef...
For an ordered MultiIndex, compute the slice locations for input labels. They can tuples representing partial levels, e.g. for a MultiIndex with 3 levels, you can pass a single value (corresponding to the first level), or a 1-, 2-, or 3-tuple. Parameters ---------- start : label or tuple, default None If None, def...
625941f72c8b7c6e89b35e2d
def __init__(self, config): <NEW_LINE> <INDENT> super(TerraformBaseAction, self).__init__(config) <NEW_LINE> self.terraform = Terraform()
Creates a new BaseAction given a StackStorm config object (kwargs works too) Also stores the Terraform class from python_terraform in a class variable :param config: StackStorm configuration object for the pack :returns: a new BaseAction
625941f7be7bc26dc91cdc65
def p_S(t): <NEW_LINE> <INDENT> pass
S : OPEN_SQUARE_BRACKET EXP CLOSE_SQUARE_BRACKET T | OPEN_PARENTHESES EXP U
625941f7ab23a570cc2507fb
def record_clicked(self): <NEW_LINE> <INDENT> self.reset_buttons(True, False, False) <NEW_LINE> if not self.treeRecords.selectedItems(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> item = self.treeRecords.currentItem() <NEW_LINE> if not item: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> identifier = get_item_data(...
record clicked signal
625941f792d797404e3047ff
def test_get_storage_pool_by_name(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.tbd.get_storage_pool_by_name('test_storage_pool'), StoragePool) <NEW_LINE> self.assertRaisesRegexp(CloubedException, 'storage pool fail not found in configuration', self.tbd.get_storage_pool_by_name, 'fail')
Cloubed.get_storage_pool_by_name() shoud find the StoragePool with name in parameter and return it else raise CloubedException
625941f7ad47b63b2c50a5f2
def makeOutputDirectories(self): <NEW_LINE> <INDENT> if not self.suppressOutputAndLog: <NEW_LINE> <INDENT> utils.mkdirP(self.outDir) <NEW_LINE> utils.mkdirP(self.phyloOutDir)
make output directories if they do not already exist
625941f7009cb60464c63a1e
def encrypt_password(self, password = None): <NEW_LINE> <INDENT> password = password or self._parameters.get("password", None) <NEW_LINE> if not password: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.password = models.RootEntity.encrypt(password)
Encrypts the specified password (in sha512) and sets it in the user, in the password attribute. In case no password is specified, it will be retrieved from the parameters map. Passwords are encrypted in sha512. :type password: String :param password: The password to encrypt.
625941f757b8e32f52483b12
def is_variable_cell(self, how='all'): <NEW_LINE> <INDENT> if self.is_periodic: <NEW_LINE> <INDENT> if 'rx' not in self.columns: <NEW_LINE> <INDENT> self.compute_cell_magnitudes() <NEW_LINE> <DEDENT> rx = self['rx'].min() <NEW_LINE> ry = self['ry'].min() <NEW_LINE> rz = self['rz'].min() <NEW_LINE> if np.allclose(self['...
Check if the simulation cell (applicable to periodic simulations) varies (e.g. variable cell molecular dynamics).
625941f7566aa707497f4bd2
def segment_set_op(A, B, op): <NEW_LINE> <INDENT> if op == 'and': bit_op = lambda x, y: x & y <NEW_LINE> elif op == 'or': bit_op = lambda x, y: x | y <NEW_LINE> else: raise ValueError('Unsupported operation ''%s''' % (op,)) <NEW_LINE> a, b = flatten(A), flatten(B) <NEW_LINE> i, j, n, m, c = 0, 0, len(a), len(b), [] <NE...
Union or intersect two sets of closed segments. op=''and' returns intersection, op='or' returns union. A set is specified by a list of tuples [(a[0],a[1]),...(a[2*n-2],a[2*n-1])] representing the segments [a[0],a[1]], ... [a[2*n-2],a[2*n-1]].
625941f7b7558d58953c5578
def wind_ninja_output_dir(out_dir, file_datetime): <NEW_LINE> <INDENT> return os.path.join(out_dir, 'data{}'.format(file_datetime.strftime(fmt1)), 'wind_ninja_data', 'hrrr.{}'.format(file_datetime.strftime(fmt1)))
Create the wind ninja output directory for HRRR files Arguments: out_dir {str} -- output directory path file_datetime {datetime} -- datetime of the file Returns: str -- path to the cropped HRRR data
625941f7cc0a2c11143dd504
def test_patch_new_resource(self): <NEW_LINE> <INDENT> response = self.app.patch('/artists/276', content_type='application/json', data=json.dumps({u'Name': u'Jeff Knupp'})) <NEW_LINE> assert response.status_code == 201 <NEW_LINE> assert type(response.data) == str <NEW_LINE> assert json.loads(response.data)['Name'] == u...
Send HTTP PATCH for a resource which doesn't exist (should be created).
625941f723849d37ff7b36fc
def __init__(self, parser_actions, options): <NEW_LINE> <INDENT> self.parser_actions = parser_actions <NEW_LINE> self.options = options
Initialize.
625941f77c178a314d6efade
def _add_taped_edges_to_graph(self, link_list): <NEW_LINE> <INDENT> blob_to_blob = [(self._node_start_blobs[n1], self._node_end_blobs[n2]) for (n1, n2) in link_list] <NEW_LINE> self._graph.bridge_gaps(link_list, blob_to_blob)
Adds edges from *link_list* to the graph. All added edges have the 'taped' property set True.
625941f726238365f5f0f4e9
def Read(self, *args): <NEW_LINE> <INDENT> return _btk.btkAcquisitionFileIO_Read(self, *args)
Read(self, filename, output) Read the file designated by the given filename and fill the given btkAcquisition
625941f7fbf16365ca6f6845
def get_windows_interfaces(): <NEW_LINE> <INDENT> import win32com.client <NEW_LINE> import pywintypes <NEW_LINE> locator = win32com.client.Dispatch("WbemScripting.SWbemLocator") <NEW_LINE> service = locator.ConnectServer(".", "root\cimv2") <NEW_LINE> interfaces = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for adapter in se...
Get Windows interfaces. :returns: list of windows interfaces
625941f7c4546d3d9de730ad
def truncate_sdr_samples(input_data_samples, truncation_point): <NEW_LINE> <INDENT> truncated_input_data_samples = [] <NEW_LINE> for image_iter in range(len(input_data_samples)): <NEW_LINE> <INDENT> temp_sdr_array = np.reshape( input_data_samples[image_iter], (128, INPUT_GRID_DIMENSION * INPUT_GRID_DIMENSION)) <NEW_LIN...
Truncate the input SDRs, so as to evaluate e.g. how well a k-NN performs when given only 3 out of the total INPUT_GRID_DIMENSION*INPUT_GRID_DIMENSION input features
625941f7d486a94d0b98e7b9
def bayesian_information_criterion(Y_true, Y_pred, p): <NEW_LINE> <INDENT> m = Y_true.shape[0] <NEW_LINE> rss = residual_square_sum(Y_true, Y_pred) <NEW_LINE> score = rss + p * np.log(m) <NEW_LINE> return score
BIC = RSS + p log m The smaller value of BIC is the better model fits the target vector. Args: Returns:
625941f732920d7e50b28848
def do_backspace(self, from_undo=False, mode='bkspc'): <NEW_LINE> <INDENT> if self.readonly: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cc, cr = self.cursor <NEW_LINE> _lines = self._lines <NEW_LINE> text = _lines[cr] <NEW_LINE> cursor_index = self.cursor_index() <NEW_LINE> prev_line_len = len(_lines[cr - 1]) <NEW_...
Do backspace operation from the current cursor position. This action might do several things: - removing the current selection if available. - removing the previous char and move the cursor back. - do nothing, if we are at the start.
625941f7507cdc57c630735e
def _on_context_menu(self, event): <NEW_LINE> <INDENT> loc_x = event.pos().x() <NEW_LINE> loc_y = event.pos().y() <NEW_LINE> context_menu = QMenu() <NEW_LINE> def add_default_actions(): <NEW_LINE> <INDENT> context_menu.addAction('Jump to address', lambda: self.debug_panel.on_cm_jump_to_address(view=1)) <NEW_LINE> if se...
build and show contextmenu
625941f723e79379d52eebcd
def delete_application(self, project_id, application_id): <NEW_LINE> <INDENT> url = get_api_server_url('/api/projects/{}/applications/{}/'.format( project_id, application_id)) <NEW_LINE> headers = {'X-CSRFToken': self.client.cookies['csrftoken']} <NEW_LINE> res = self.client.delete(url, headers=headers) <NEW_LINE> if r...
Delete the application in the project.
625941f7e64d504609d74eb2
def getPeakShift(filename): <NEW_LINE> <INDENT> if filename.endswith(".macs"): <NEW_LINE> <INDENT> return getPeakShiftFromMacs(filename) <NEW_LINE> <DEDENT> elif filename.endswith(".zinba"): <NEW_LINE> <INDENT> return getPeakShiftFromZinba(filename) <NEW_LINE> <DEDENT> elif filename.endswith(".spp"): <NEW_LINE> <INDENT...
get peak shift for a track or filename. This method examines the extension of filename to identify the peak caller and call the approporiate parser. Alternatively, it will check if a file with one of the known peak caller suffixes is present that starts with ``filename``. Arguments --------- filename : string Fi...
625941f73cc13d1c6d3c79e9
def get_qt_bank_info(self, userid, merchant_id): <NEW_LINE> <INDENT> pass
Parameters: - userid - merchant_id
625941f7d10714528d60035e
def __find_artordets(self, tokens, edits, chunks, level=2): <NEW_LINE> <INDENT> words = [w.lower() for w in chunks.words] <NEW_LINE> idx_map = tokenization.map_tokens([t.lower() for t in tokens], words) <NEW_LINE> for i, err in enumerate(tokens): <NEW_LINE> <INDENT> if (i,i+1) in edits: <NEW_LINE> <INDENT> cor = edits[...
Data are composed of three types of events: 1) All articles in the data 2) Spaces in front of a noun phrase if that noun phrase does not start with an article. To identify the beginning of a noun phrase, we ran a part-of-speech tagger and a phrase chunker and excluded all noun phrases not headed by a personal...
625941f791af0d3eaac9c090
def move_position(ann,i): <NEW_LINE> <INDENT> if ann == "b": <NEW_LINE> <INDENT> if i-1 < 0: <NEW_LINE> <INDENT> print("cant go back! staying here!") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = i-1 <NEW_LINE> print("moving back!") <NEW_LINE> <DEDENT> <DEDENT> elif ann == "f": <NEW_LINE> <INDENT> i = i+1 <NEW_LINE...
if user wants to move forward or back
625941f7dc8b845886cb5ba9
def get_job(self, id): <NEW_LINE> <INDENT> data = self.gogrid_client.sendAPIRequest("grid/job/get", {"id": id}) <NEW_LINE> doc = xml.dom.minidom.parseString(data) <NEW_LINE> return self._parse_job_object(doc.getElementsByTagName("object")[0])
Returns information about single job.
625941f74f88993c3716c6d2
def find_peak_base(sequence, maxima_index, minima_index): <NEW_LINE> <INDENT> p = Point2(maxima_index, sequence[maxima_index]) <NEW_LINE> q = Point2(minima_index, sequence[minima_index]) <NEW_LINE> basis_line = Line2.through_points(p, q) <NEW_LINE> query_points = query(Point2(index, sequence[index]) for index in range(...
Find the index of the base of the peak. Args: sequence: A sequence of data in which to locate the peak base. maxima_index: The index of an item in sequence on or near the top of the peak. minima_index: The index of an item in sequence off or away from the peak. Returns: The index of the estimated base...
625941f782261d6c526abb1c
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'reshebnik.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you su...
Run administrative tasks.
625941f75fcc89381b1e1d37
def sortResult(self, result_list): <NEW_LINE> <INDENT> rmap = {} <NEW_LINE> classes = [] <NEW_LINE> for n, t, o, e in result_list: <NEW_LINE> <INDENT> cls = t.__class__ <NEW_LINE> if not cls in rmap: <NEW_LINE> <INDENT> rmap[cls] = [] <NEW_LINE> classes.append(cls) <NEW_LINE> <DEDENT> rmap[cls].append((n, t, o, e)) <NE...
unittest does not seems to run in any particular order. Here at least we want to group them together by class.
625941f7aad79263cf3910be
@contract <NEW_LINE> def last_n_average_threshold_factory(time_step, migration_time, params): <NEW_LINE> <INDENT> return lambda utilization, state=None: ( last_n_average_threshold(params['threshold'], params['n'], utilization), {})
平均CPU利用率阈值算法的实现; 参数:(为了统一接口,简单算法中不会应用,开发复杂的算法,则会应用,复杂算法这里没有给出;) time_step:调用算法的时间长度; migration_time:所计算出的虚拟机迁移所花费的时间; params:若干参数信息;
625941f78c0ade5d55d3f034
def remove(comps): <NEW_LINE> <INDENT> actions = [] <NEW_LINE> actions.append(Deselect(comps)) <NEW_LINE> actions.extend([Remove(comp) for comp in comps]) <NEW_LINE> action = Composite(actions) <NEW_LINE> get_base().action_manager.push(action) <NEW_LINE> action() <NEW_LINE> get_base().doc.on_modified(comps)
Create the remove composite action, execute it and push it onto the undo queue.
625941f7dc8b845886cb5baa
def cos(x): <NEW_LINE> <INDENT> if (isinstance(x,Dual)): <NEW_LINE> <INDENT> x.der = -1 * np.sin(x.val)*x.der <NEW_LINE> x.val = np.cos(x.val) <NEW_LINE> return x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.cos(x)
Calculate cosine of the input Keyword arguments:numpy.tan x -- a real number or a dual number Return: the cosine value
625941f7d268445f265b54e2
def Makkink(self, Rs=None): <NEW_LINE> <INDENT> (Delta, gamma, lambdah) = (self.Delta, self.gamma, self.lambdah) <NEW_LINE> if Rs is None: <NEW_LINE> <INDENT> Rs = self.apx_solar_radiations(Kt=self.Kt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Rs = force_reference(Rs, self.tavg) <NEW_LINE> <DEDENT> PET = 0.61 * Del...
Computes the PET with the Makkink (1957) method [Makkink_1957]_: .. math:: PET = 0.61 \cfrac{\Delta}{\Delta+\gamma} \cfrac{R_s}{\lambda_H} - 0.12 Parameters ---------- %(Rs)s
625941f7baa26c4b54cb178a
def recrypt_files(options, strict=False): <NEW_LINE> <INDENT> rechiffre_roles = options.roles <NEW_LINE> _, my_roles_w = get_my_roles(options) <NEW_LINE> if rechiffre_roles == None: <NEW_LINE> <INDENT> rechiffre_roles = my_roles_w <NEW_LINE> <DEDENT> allfiles = all_files(options) <NEW_LINE> def is_wanted(fileroles): <N...
Rechiffre les fichiers. Ici, la signification de ``options.roles`` est : strict => on chiffre les fichiers dont *tous* les rôles sont dans la liste non strict => on ne veut rechiffrer que les fichiers qui ont au moins un de ces roles.
625941f738b623060ff0b45f
def removeNamespace(ns_name): <NEW_LINE> <INDENT> new_name = ns_name.replace(':', '_') <NEW_LINE> return new_name
Makes namespace as part of the name
625941f796565a6dacc8fd3b
def readAnno(annofile, annodict, head = 1, locusL = []): <NEW_LINE> <INDENT> limit = 0 <NEW_LINE> if len(locusL) > 0: <NEW_LINE> <INDENT> limit = 1 <NEW_LINE> <DEDENT> tmpDict = {} <NEW_LINE> for line in open(annofile): <NEW_LINE> <INDENT> if head: <NEW_LINE> <INDENT> head -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
**************************************************************** This read anno file get from Ensmbl using R-Script. **************************************************************** FileFormat: ensembl_peptide_id description go_biological_process_id name_1006 go_cellular_component_idgo_cellular_co...
625941f7236d856c2ad44e57
def t380291_x7(): <NEW_LINE> <INDENT> if not GetEventStatus(73800123): <NEW_LINE> <INDENT> assert t380291_x13(text3=29001820, z2=73800123, flag3=0, mode3=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> SetEventState(73800121, 0) <NEW_LINE> SetEventState(73800122, 0) <NEW_LINE> SetEventState(73800123, 0) <NEW_LINE> ass...
State 0,1
625941f71f5feb6acb0c51bc
def get_with_clause_table_ref_count(self): <NEW_LINE> <INDENT> return self._choose_from_bounds('WITH_TABLE_COUNT')
Return the number of table ref entries a WITH clause should contain.
625941f76aa9bd52df03741b
def _extract_id_token(id_token): <NEW_LINE> <INDENT> segments = id_token.split('.') <NEW_LINE> if len(segments) != 3: <NEW_LINE> <INDENT> raise VerifyJwtTokenError( 'Wrong number of segments in token: %s' % id_token) <NEW_LINE> <DEDENT> return json.loads(_urlsafe_b64decode(segments[1]).decode('utf-8'))
Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload.
625941f7293b9510aa2c3902
def get_value_sql(self): <NEW_LINE> <INDENT> return self.value
valeur à enregistrer dans la colonne de l'élément
625941f731939e2706e4d4d3
def solve_right_binned(bin_width, pseudos, Ms, B_2, ths): <NEW_LINE> <INDENT> pseudos_binned = matrix_reduce_col(pseudos, bin_width) <NEW_LINE> Ms_binned = matrix_reduce(Ms, bin_width) <NEW_LINE> B_2_binned = matrix_reduce_col(B_2, bin_width) <NEW_LINE> ths_binned = matrix_reduce_col(ths, bin_width) <NEW_LINE> Fs_binne...
actually it is unsure how the binning should work e.g. similar to K_ll to K_bb binning, binning should occur with the combination of (Ms * B_2 * ths) but then it introduce yet another band power window function comparing to the one used in spectra Ignoring this for now since we are not multiplying F on the right in ou...
625941f791af0d3eaac9c091
def test_7_before_1978_christmas(self): <NEW_LINE> <INDENT> calendar = FinancialDate.Calendar() <NEW_LINE> self.assertEqual(calendar.NthTradingDayBefore(datetime.datetime(1978, 12, 25), 7), datetime.datetime(1978, 12, 13))
Test combination of non-trivial N and static holiday in non-recent history for before dates
625941f7a934411ee3751d08
@pytest.fixture() <NEW_LINE> def mocked_filesystem_create_log_path(mocker): <NEW_LINE> <INDENT> return mocker.patch("stylish.filesystem.create_log_path")
Return mocked :func:`stylish.filesystem.create_log_path`.
625941f73eb6a72ae02ecb63
def makeLicense(user): <NEW_LINE> <INDENT> licLevel = "" <NEW_LINE> while True: <NEW_LINE> <INDENT> print("Configure license for: {0}".format(user)) <NEW_LINE> print("A - Advanced") <NEW_LINE> print("S - Standard") <NEW_LINE> print("B - Basic") <NEW_LINE> print("R - REVOKE ALL") <NEW_LINE> licLevel = getInput("[A|S|B|R...
Creates a list of proper ArcGIS Pro licenses and extensions
625941f78e71fb1e9831de19
def set_columns(self, *args): <NEW_LINE> <INDENT> return _vnl_matrix_fixedPython.vnl_matrix_fixedF_3_3_set_columns(self, *args)
set_columns(self, unsigned int starting_column, vnl_matrixF m)
625941f796565a6dacc8fd3c
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(TrackingBox, self).__init__(*args, **kwds) <NEW_LINE> if self.uid is None: <NEW_LINE> <INDENT> self.uid = 0 <NEW_LINE> <DEDENT> if self.confidence is None: <NEW_LINE> <INDENT> self.confidence = 0. <NEW_LINE> <DEDENT> if se...
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: uid,confidence,classes,signal,bbox...
625941f7a8370b7717052f10
def get_format_description(self): <NEW_LINE> <INDENT> raise NotImplementedError(self.get_format_description)
Return the short description for this format.
625941f750812a4eaa59c98d
def test05(self): <NEW_LINE> <INDENT> Y, X, Z = self.general_grids.expanded <NEW_LINE> Y_rot, X_rot, Z_rot = self.general_grids.rotate(np.pi/4, 0, 0) <NEW_LINE> import mayavi.mlab as mlab <NEW_LINE> import amitibo <NEW_LINE> import amitibo <NEW_LINE> import mayavi.mlab as mlab <NEW_LINE> amitibo.viz3D(Y, X, Z, Y) <NEW_...
Test the general grid and its rotation
625941f7e76e3b2f99f3ae73
def _sample_negative_statements(self, negative_examples_per_image): <NEW_LINE> <INDENT> random.seed(286) <NEW_LINE> meta_list = [meta for meta in self.get_meta_list() if 'actions_and_reasons' in meta] <NEW_LINE> for i, meta in enumerate(meta_list): <NEW_LINE> <INDENT> neg_stmts = [] <NEW_LINE> for _ in x...
Randomly sample negative statements, only for evaluation purpose. Modify 'negative_statements' data field. Args: negative_examples_per_image: number of negative examples of each image.
625941f73cc13d1c6d3c79ea
@webserviceHandle('/login_ky') <NEW_LINE> def ky_server_login(): <NEW_LINE> <INDENT> token = request.args.get('open_id') <NEW_LINE> result = __login(token) <NEW_LINE> logger.debug("kuaiyong login in token:%s result:%s" % (token, result)) <NEW_LINE> if result.get('code') != 0: <NEW_LINE> <INDENT> return json.dumps(dict(...
account login
625941f730bbd722463cc43d
def __init__(self, failed=None, paused=None, resumed=None, started=None, stopped=None): <NEW_LINE> <INDENT> self._failed = None <NEW_LINE> self._paused = None <NEW_LINE> self._resumed = None <NEW_LINE> self._started = None <NEW_LINE> self._stopped = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.failed = fai...
ScanEvents - a model defined in Swagger
625941f7bf627c535bc13843
def __add_in_arxiv_class(self, field, value, output_format): <NEW_LINE> <INDENT> if (len(value) >= 1): <NEW_LINE> <INDENT> return self.__add_in(field, value[0], output_format) <NEW_LINE> <DEDENT> return ''
:param field: :param value: :param output_format: :return:
625941f77b180e01f3dc4e62
def __iter__(self): <NEW_LINE> <INDENT> for first in self._bychild: <NEW_LINE> <INDENT> yield first
Provides iterator for this RuleDict.
625941f7be383301e01b5aec
def go_to_frame(self, frame_nb: int): <NEW_LINE> <INDENT> if self.dir_images: <NEW_LINE> <INDENT> self.dir_images_index = frame_nb <NEW_LINE> if self.dir_images_index >= len(self.dir_images): <NEW_LINE> <INDENT> self.dir_images_index = len(self.dir_images) - 1 <NEW_LINE> <DEDENT> if self.dir_images_index < 0: <NEW_LINE...
load frame and visualize it
625941f7de87d2750b86040e
def safe_get_udf_model_class(model_string): <NEW_LINE> <INDENT> model_class = safe_get_model_class(model_string) <NEW_LINE> if not isinstance(model_class(), UDFModel): <NEW_LINE> <INDENT> raise ValidationError(_('invalid model type - must subclass UDFModel')) <NEW_LINE> <DEDENT> return model_class
In a couple of cases we want to be able to convert a string into a valid django model class. For instance, if we have 'Plot' we want to get the actual class for 'treemap.models.Plot' in a safe way. This function returns the class represented by the given model if it exists in 'treemap.models' and the class's objects a...
625941f7bde94217f368345e
@rule(datatypes=['command', 'filePath', 'processPath', 'fileName']) <NEW_LINE> def right_to_left_character(rec): <NEW_LINE> <INDENT> rlo = u'\u202e' <NEW_LINE> commands = fetch_values_by_datatype(rec, 'command') <NEW_LINE> for command in commands: <NEW_LINE> <INDENT> if isinstance(command, unicode) and rlo in command: ...
author: @javutin description: Malicious files can be disguised by using a encoding trick that uses the unicode character U+202E, also known as right-to-left-override (RLO). The trick hides a potentially malicious extension and makes them appear harmle...
625941f7a934411ee3751d09
def reset(self): <NEW_LINE> <INDENT> self.vmin = self.original_vmin <NEW_LINE> self.vmax = self.original_vmax <NEW_LINE> self.repaint() <NEW_LINE> self.updateVolumeColors()
Resets vmin and vmax to original values.
625941f782261d6c526abb1d
def euclid_pg(p, q, x): <NEW_LINE> <INDENT> prs = sturm_pg(p, q, x, 1) <NEW_LINE> if prs == [] or len(prs) == 2: <NEW_LINE> <INDENT> return prs <NEW_LINE> <DEDENT> euclid_seq = [prs[0], prs[1]] <NEW_LINE> flag = 0 <NEW_LINE> m = len(prs) <NEW_LINE> i = 2 <NEW_LINE> while i <= m-1: <NEW_LINE> <INDENT> if flag == 0: <NE...
p, q are polynomials in Z[x] or Q[x]. It is assumed that degree(p, x) >= degree(q, x). Computes the Euclidean sequence of p and q in Z[x] or Q[x]. If the Euclidean sequence is complete the coefficients of the polynomials in the sequence are subresultants. That is, they are determinants of appropriately selected subm...
625941f7be8e80087fb212aa
def cat_childs(cat): <NEW_LINE> <INDENT> childs = [] <NEW_LINE> childs.extend(cat.child.all()) <NEW_LINE> for child in childs: <NEW_LINE> <INDENT> childs.extend(child.child.all()) <NEW_LINE> cat_childs(child) <NEW_LINE> <DEDENT> return childs
Получаем чайлдов полученой категории
625941f7236d856c2ad44e58
def test_no_such_file(self): <NEW_LINE> <INDENT> with self.assertRaises(IOError): <NEW_LINE> <INDENT> analyze_text('foobar')
Checks the proper exception is thrown if no suh file exists.
625941f7090684286d50f365
def run_alternating_projection(o_ji): <NEW_LINE> <INDENT> J, I = o_ji.shape <NEW_LINE> psi_j = np.nanmean(o_ji, axis=1) <NEW_LINE> b_ji = o_ji - np.tile(psi_j, (I, 1)).T <NEW_LINE> b_i = np.nanmean(b_ji, axis=0) <NEW_LINE> MAX_ITR = 1000 <NEW_LINE> DELTA_THR = 1e-8 <NEW_LINE> EPSILON = 1e-8 <NEW_LINE> itr = 0 <NEW_LINE...
Run Alternating Projection (AP) algorithm. :param o_ji: 2D numpy array containing raw votes. The first dimension corresponds to the PVSs (j); the second dimension corresponds to the subjects (i). If a vote is missing, the element is NaN. :return: dictionary containing results keyed by 'mos_j', 'sos_j', 'bias_i' and '...
625941f79b70327d1c4e144c
def find_point_group(self, tol=DEFAULT_SYM_TOL): <NEW_LINE> <INDENT> pg = self.find_highest_point_group(tol) <NEW_LINE> user = self.symmetry_from_input() <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> user_specified_direction = True if user[-1] in ['X', 'x', 'Y', 'y', 'Z', 'z'] else False <NEW_LINE> if self.symmet...
Find computational molecular point group, user can override this with the "symmetry" keyword. Result is highest D2h subgroup attendant on molecule and allowed by the user.
625941f71d351010ab85618e
def unnest(rec, *path): <NEW_LINE> <INDENT> if isinstance(rec, list): <NEW_LINE> <INDENT> return [unnest(item, *path) for item in rec] <NEW_LINE> <DEDENT> elif isinstance(rec, tuple): <NEW_LINE> <INDENT> return (unnest(item, *path) for item in rec) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert isinstance(rec, di...
Unnests inner values in a dictionary according to key path. If the rec is a tuple or a list then unnesting is applied to its items. Eg. >>> example_dict = {'a': {'b': {'c': 'the_value'}}} >>> unnest(example_dict, "a", "b") {'c': 'the_value'} @param rec: record to unnest @type rec: dict, list or tuple of di...
625941f78da39b475bd655f0