code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def des_descrypt(self, s): <NEW_LINE> <INDENT> secret_key = '12345678' <NEW_LINE> k = des(secret_key.encode('utf-8'), ECB, pad=None, padmode=PAD_PKCS5) <NEW_LINE> de = k.decrypt(binascii.a2b_base64(s), padmode=PAD_PKCS5) <NEW_LINE> return de.decode('ascii')
位 DES 解密 8位key :return: 解密后的字符串
625941e77cff6e4e81117df3
def __init__(self, skyrenderer): <NEW_LINE> <INDENT> self.renderer = skyrenderer
Constructor
625941e7656771135c3ebce1
def touch(fname, cmd=None, times=None): <NEW_LINE> <INDENT> with open(fname, 'a') as opf: <NEW_LINE> <INDENT> opf.write('created: {0}\n'.format(datetime.datetime.now())) <NEW_LINE> opf.write('location of code execution: {0}\n'.format( os.path.abspath('.'))) <NEW_LINE> if cmd: <NEW_LINE> <INDENT> opf.write('{0}\n'.forma...
Similar to nix command, touch, to create an empty file, but also added some meta data to the touched file
625941e78c0ade5d55d3ee2c
def time_limit_test(self, nmax): <NEW_LINE> <INDENT> import random <NEW_LINE> import timeit <NEW_LINE> test = str(nmax) + " " + str(nmax) + "\n" <NEW_LINE> numnums = [str(i) + " " + str(i+1) for i in range(nmax)] <NEW_LINE> test += "\n".join(numnums) + "\n" <NEW_LINE> nums = [random.randint(1, 10000) for i in range(nma...
Timelimit testing
625941e7009cb60464c6381b
def symbol_cn2en(data): <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> d = { '。': '.', '。': '.', '〝': '"', '〞': '"', "‛": "'", '“': '"', '”': '"', "‘": "'", "’": "'", '~': '~', '—': '-', '$': '$', '¥': '$', '【': '[', '】': ']', '》': '>', '《': '<' } <NEW_LINE> table = ''.maketrans(d)...
中文标点转英文标点
625941e757b8e32f5248390b
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ResponseContainerPagedExternalLink): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
625941e763b5f9789fde7554
def to_utf8(cc: str): <NEW_LINE> <INDENT> bb = cc.encode('utf-8') <NEW_LINE> print('utf-8: ' + bi.b2a_hex(bb).decode())
get utf-8
625941e7ec188e330fd5ac04
def mk_descr(self): <NEW_LINE> <INDENT> return None
Prepare adapter's description to be included into connection description
625941e785dfad0860c3b2c9
def combine(matrices): <NEW_LINE> <INDENT> if not matrices: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> name = matrices[0][0] <NEW_LINE> combined = copy.deepcopy(matrices[0][1]) <NEW_LINE> mixed_datatypes = len({n[1].datatype for n in matrices}) > 1 <NEW_LINE> if mixed_datatypes: <NEW_LINE> <INDENT> combined.da...
Combine matrices in [(name,nexus-instance),...] and return new nexus instance. combined_matrix=combine([(name1,nexus_instance1),(name2,nexus_instance2),...] Character sets, character partitions and taxon sets are prefixed, readjusted and present in the combined matrix.
625941e7a05bb46b383ecc8b
def generate_hmac(value): <NEW_LINE> <INDENT> return salted_hmac(key_salt=settings.LOGIN_HMAC_SALT, value=value, secret=settings.LOGIN_HMAC_SECRET).hexdigest()
Generates the hmac
625941e73d592f4c4ed1d4cf
def decide_types(patterns, reader, column_names, **kwargs): <NEW_LINE> <INDENT> null_value = kwargs.get('null_value', _DEFAULT_NULL_VALUE) <NEW_LINE> index_types = kwargs.get('index_types', []) <NEW_LINE> typename_maps = dict( (int(index), typename) for (index, typename) in index_types) <NEW_LINE> inferences = [ _Infer...
Decide the types and returns the list of types. Given `null_value`, it is treated as NULL and type inference skips it. Given `index_types` as a list of (index, typename), the types of the specified columns will not be calculated and will be set the pre-defined type names.
625941e7d53ae8145f87a6d5
def _gs_create_param_dict(self) -> Tuple[Dict, Dict]: <NEW_LINE> <INDENT> if self.shapes is not None: <NEW_LINE> <INDENT> return self.param_dict, self.shapes <NEW_LINE> <DEDENT> param_dict = {} <NEW_LINE> shapes = {} <NEW_LINE> st = 0 <NEW_LINE> for name, param in self.module.named_parameters(): <NEW_LINE> <INDENT> par...
Create the shape and param dictionary used for sending parameters around the MPI world. this will also define the buffer size if it was not previously defined.
625941e721a7993f00bc8165
def set_lock_state(self, code, state): <NEW_LINE> <INDENT> lock_state = "lock" if state == STATE_LOCKED else "unlock" <NEW_LINE> transaction_id = hub.session.set_lock_state( code, self._device_label, lock_state )["doorLockStateChangeTransactionId"] <NEW_LINE> _LOGGER.debug("Verisure doorlock %s", state) <NEW_LINE> tran...
Send set lock state command.
625941e763f4b57ef000157a
def parse_json_links_index(out_dir): <NEW_LINE> <INDENT> index_path = os.path.join(out_dir, 'index.json') <NEW_LINE> if os.path.exists(index_path): <NEW_LINE> <INDENT> with open(index_path, 'r', encoding='utf-8') as f: <NEW_LINE> <INDENT> links = json.load(f)['links'] <NEW_LINE> check_links_structure(links) <NEW_LINE> ...
load the index in a given directory and merge it with the given link
625941e77d847024c06be72d
def current_directory(): <NEW_LINE> <INDENT> return os.path.dirname(os.path.realpath(__file__))
returns absolute file path to current module
625941e7a934411ee3751b02
def _make_widget(self): <NEW_LINE> <INDENT> self.widget = QtWidgets.QCheckBox() <NEW_LINE> self.widget.setTristate(True) <NEW_LINE> self.widget.stateChanged.connect(self.write_widget_value_to_attribute) <NEW_LINE> self.setToolTip("Checked:\t on\nUnchecked: off\nGrey:\t ignore")
Sets the widget (here a QCheckbox) :return:
625941e7379a373c97cfafb4
def array(self, names, array_length=None): <NEW_LINE> <INDENT> names, data = self._get_list_data(names) <NEW_LINE> if array_length is None: <NEW_LINE> <INDENT> array_length = np.max([np.size(d) for d in data]) <NEW_LINE> <DEDENT> out = np.nan * np.zeros(shape=(len(data), array_length)) <NEW_LINE> for n in range(len(dat...
Return numpy array of data with same length data with length 1 will be cast over the full length data with length >1 and < array_length will be filled with nans :param names: str or list of str, key or associated key in namespace :param array_length: int or None, length of arrays returned :return: array(n,array_lengt...
625941e7656771135c3ebce2
def test_removingLastTaskStopsScheduledCall(self): <NEW_LINE> <INDENT> calls = [None] <NEW_LINE> def sched(f): <NEW_LINE> <INDENT> calls[0] = FakeDelayedCall(f) <NEW_LINE> return calls[0] <NEW_LINE> <DEDENT> coop = task.Cooperator(scheduler=sched) <NEW_LINE> task1 = coop.cooperate(iter([1, 2])) <NEW_LINE> task2 = coop....
If the last task in a Cooperator is removed, the scheduled call for the next tick is cancelled, since it is no longer necessary. This behavior is useful for tests that want to assert they have left no reactor state behind when they're done.
625941e78c3a87329515882e
def scale_icp_odom_model(self, prob): <NEW_LINE> <INDENT> return self.create_noise_model( np.sqrt(1.0 / prob) * np.array(self.icp_odom_sigmas) )
p * d^T * R^{-1} * d = d^T * (1/p * R)^{-1} * d
625941e7d4950a0f3b08c7b6
def offset(self, offset): <NEW_LINE> <INDENT> self.log(u"Applying offset to all fragments...") <NEW_LINE> self.log([u" Offset %.3f", offset]) <NEW_LINE> for fragment in self.fragments: <NEW_LINE> <INDENT> fragment.interval.offset( offset=offset, allow_negative=False, min_begin_value=self.begin, max_end_value=self.end ...
Move all the intervals in the list by the given ``offset``. :param offset: the shift to be applied :type offset: :class:`~aeneas.exacttiming.TimeValue` :raises TypeError: if ``offset`` is not an instance of ``TimeValue``
625941e791af0d3eaac9be8b
def _system_state_change(cloud, module, router, network, internal_ids, internal_portids, filters=None): <NEW_LINE> <INDENT> state = module.params['state'] <NEW_LINE> if state == 'absent' and router: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if state == 'present': <NEW_LINE> <INDENT> if not router: <NEW_LINE> ...
Check if the system state would be changed.
625941e73617ad0b5ed68364
def reseed_choice(a, size=None, replace=True, p=None): <NEW_LINE> <INDENT> np.random.seed() <NEW_LINE> return np.random.choice(a=a, size=size, replace=replace, p=p)
Wrapper for the numpy choice function that reseeds before sampling to ensure that it doesn't make identical choices accross different parallel runs.
625941e71b99ca400220af21
def AddEconomicModel(self,economicmodel,override): <NEW_LINE> <INDENT> if (not economicmodel in self.EconomicModels) | override: <NEW_LINE> <INDENT> self.EconomicModels[economicmodel.Name]=economicmodel <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Error when adding the economic model {0} in the workfl...
Add an economic model to the workflow Parameters ---------- economicmodel: EconomicModel EconomicModel instance to add to the workflow. Unique characteristics (i.e. methods and attributes that are not shared among EconomicModel subclassses) of the model can be set prior to add the model to the workflow, o...
625941e73617ad0b5ed68365
@pytest.mark.usefixtures("clean_db") <NEW_LINE> @pytest.mark.usefixtures("null_db_instances") <NEW_LINE> def test_demo(database, monkeypatch): <NEW_LINE> <INDENT> monkeypatch.chdir(os.path.dirname(os.path.abspath(__file__))) <NEW_LINE> kleio.core.cli.main(["hunt", "--config", "./kleio_config.yaml", "./black_box.py", "-...
Test a simple usage scenario.
625941e70c0af96317bb8656
def str_to_hit(string): <NEW_LINE> <INDENT> return list(map(int, string.split(" ")))
Convert string to hit
625941e776d4e153a657efa0
def OBV(kline): <NEW_LINE> <INDENT> records = kline <NEW_LINE> kline_length = len(records) <NEW_LINE> close_array = np.zeros(kline_length) <NEW_LINE> t = 0 <NEW_LINE> for item in records: <NEW_LINE> <INDENT> close_array[t] = item[4] <NEW_LINE> t += 1 <NEW_LINE> <DEDENT> result = (talib.OBV(close_array, VOLUME(kline))) ...
OBV :param kline: 传入指定k线数据 :return: 返回一个一维数组
625941e7a8ecb033257d3539
def test_gh262_03(self): <NEW_LINE> <INDENT> table = self.h5file.root.table <NEW_LINE> data = table.get_where_list('(c1>5)&(~(c1>5))', start=0, step=2) <NEW_LINE> if common.verbose: <NEW_LINE> <INDENT> print() <NEW_LINE> print("data -->", data) <NEW_LINE> <DEDENT> self.assertEqual(len(data), 0)
Regression test for gh-262 (start=0, step=2)
625941e7a934411ee3751b03
def med_is_decimal(s): <NEW_LINE> <INDENT> return set(s) <= set('1234567890')
Takes a string and returns whether all characters of the string are digits.
625941e732920d7e50b28642
def __register_func_sig(f, d): <NEW_LINE> <INDENT> bits = f.split(maxsplit=1) <NEW_LINE> first_bracket=bits[1].find('(') <NEW_LINE> f=bits[1][:first_bracket] <NEW_LINE> rest=bits[1][first_bracket:] <NEW_LINE> d[f]=rest
registers all function names in global:functions. Only useful for print_funcs and get_function_signature right now, but later could be useful for online help #todo parse for signature and callback
625941e724f1403a92600fd0
def execute(args): <NEW_LINE> <INDENT> def split_out_subentries(sfm_records): <NEW_LINE> <INDENT> recs = [] <NEW_LINE> for record in sfm_records: <NEW_LINE> <INDENT> pieces = record.split(SES) <NEW_LINE> for piece in pieces: <NEW_LINE> <INDENT> recs.append(piece) <NEW_LINE> <DEDENT> <DEDENT> return recs <NEW_LINE> <DED...
Split out any subentries, then pass each (sub)entry into the chosen function for processing.
625941e724f1403a92600fd1
def init_process_group(backend, init_method='env://', **kwargs): <NEW_LINE> <INDENT> world_size = kwargs.pop('world_size', -1) <NEW_LINE> group_name = kwargs.pop('group_name', '') <NEW_LINE> rank = kwargs.pop('rank', -1) <NEW_LINE> assert len(kwargs) == 0, "got unexpected keyword arguments: %s" % ",".join(kwargs.keys()...
Initializes the distributed package. Arguments: backend (str): Name of the backend to use. Depending on build-time configuration valid values include: ``tcp``, ``mpi`` and ``gloo``. init_method (str, optional): URL specifying how to initialize the package. world_size (int, optional): Number of proc...
625941e7b5575c28eb68e472
def test_expected_gpg_command(self, m_subp, m_sleep): <NEW_LINE> <INDENT> key, keyserver = ("DEADBEEF", "keyserver.example.com") <NEW_LINE> retries = (1, 2, 4) <NEW_LINE> m_subp.return_value = ('', '') <NEW_LINE> gpg.recv_key(key, keyserver, retries=retries) <NEW_LINE> m_subp.assert_called_once_with( ['gpg', '--no-tty'...
Verify gpg is called with expected args.
625941e74f88993c3716c4d1
def __init__(self,term_order_tuple): <NEW_LINE> <INDENT> self.val = term_order_tuple
Takes in a tuple
625941e75fdd1c0f98dc06a3
def str2int(s): <NEW_LINE> <INDENT> ret = 0 <NEW_LINE> mult = 1 <NEW_LINE> for i in range(len(s)): <NEW_LINE> <INDENT> ret += (ord(s[~i]) - 48) * mult <NEW_LINE> mult *= 10 <NEW_LINE> <DEDENT> return ret
Convert string representation of integer to int.
625941e782261d6c526ab914
def load_vgg_dataset(basename): <NEW_LINE> <INDENT> return Bundle(cameras=load_vgg_cameras(basename), points=load_vgg_points(basename), tracks=load_vgg_tracks(basename))
Load a VGG-format dataset in which: - cameras are in a file named BASENAME.NNN.P for N = 0,1,... - feature positions are a in a file named BASENAME.MMM.corners for M = 0,1,... - tracks are represented by a list of camera/feature indices in BASENAME.nview-corners - 3D points are in a file named BASENAME.p3d
625941e79b70327d1c4e1246
def test_update_no_data(self): <NEW_LINE> <INDENT> with requests_mock.Mocker() as mock_request: <NEW_LINE> <INDENT> mock_request.register_uri( 'GET', r'http://%s/Status_Wireless.live.asp' % TEST_HOST, [{'text': load_fixture('Ddwrt_Status_Wireless.txt')}, {'text': None}]) <NEW_LINE> mock_request.register_uri( 'GET', r'h...
Test error handling of no response when active devices checked.
625941e730bbd722463cc237
def unique(input, sorted=False, return_inverse=False, dim=None): <NEW_LINE> <INDENT> if dim is not None: <NEW_LINE> <INDENT> output, inverse_indices = torch._unique_dim( input, dim, sorted=sorted, return_inverse=return_inverse ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output, inverse_indices = torch._unique( inpu...
Returns the unique scalar elements of the input tensor as a 1-D tensor. Arguments: input (Tensor): the input tensor sorted (bool): Whether to sort the unique elements in ascending order before returning as output. return_inverse (bool): Whether to also return the indices for where elements ...
625941e7a4f1c619b28b049d
def set_info(self, name, value): <NEW_LINE> <INDENT> info = self.root.find("info") <NEW_LINE> if info is None: <NEW_LINE> <INDENT> info = etree.SubElement(self.root, "info") <NEW_LINE> <DEDENT> info.set(name, value)
Set a piece of info about the user.
625941e7507cdc57c6307154
def mark_as_seen(self, watched_at=None): <NEW_LINE> <INDENT> add_to_history(self, watched_at)
Mark this episode as seen
625941e7d486a94d0b98e5b5
def grab(self, evt): <NEW_LINE> <INDENT> if evt.pick == self: <NEW_LINE> <INDENT> self.drag_pos = evt.pickpos <NEW_LINE> self.scene.bind('mousemove', self.move) <NEW_LINE> self.scene.bind('mouseup', self.drop)
Grab the mouse and bind some more events.
625941e7c4546d3d9de72ea6
def test_as_text(self): <NEW_LINE> <INDENT> section = self.section <NEW_LINE> self.assertEqual( section['option_text'].as_text(), u'Description of this nice option') <NEW_LINE> self.assertEqual(section['option_empty'].as_text(), u'')
Test getting an option as text content
625941e7090684286d50f15b
def _restore(self): <NEW_LINE> <INDENT> self.params = [] <NEW_LINE> return
Restore state.
625941e707f4c71912b118f3
def add(self, *args): <NEW_LINE> <INDENT> return _libsedml.XMLErrorLog_add(self, *args)
add(XMLErrorLog self, XMLError error) add(XMLErrorLog self, std::vector< XMLError *,std::allocator< XMLError * > > const & errors)
625941e75fc7496912cc3dec
def build_finetune_functions(self, train_set_x, train_set_y, learning_rate, mode, profile): <NEW_LINE> <INDENT> i_idx_0 = T.iscalar('input_start') <NEW_LINE> i_idx_1 = T.iscalar('input_stop') <NEW_LINE> t_idx_0 = T.iscalar('target_start') <NEW_LINE> t_idx_1 = T.iscalar('target_stop') <NEW_LINE> print('Compiling') <NEW_...
type train_set_x: T.matrix() param train_set_x: training input sequences of the network type train_set_y: T.ivector() param train_set_y: training output sequences of the network type learning_rate: float32 param learning_rate: learning_rate of the training algorithm type mode: str param mode: theano function compile...
625941e7cc0a2c11143dd300
def test_place_new_sm_order(self): <NEW_LINE> <INDENT> pass
Test case for place_new_sm_order Place a New Super Multiple order # noqa: E501
625941e7566aa707497f49d1
def isAbove(self,query): <NEW_LINE> <INDENT> for p in self.getAllParents_G(): <NEW_LINE> <INDENT> if p.value == query: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
returns True if this Node or any parent Node has requested value
625941e776e4537e8c351ae4
def xaccSplitMakeStockSplit(*args): <NEW_LINE> <INDENT> return _gnucash_core_c.xaccSplitMakeStockSplit(*args)
xaccSplitMakeStockSplit(Split s)
625941e78c0ade5d55d3ee2d
def register(self, call_id): <NEW_LINE> <INDENT> if call_id is None or call_id in self.calls.history: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> metadata = CallMetadata(expiration=time.time() + self.call_lifetime) <NEW_LINE> self.calls.history.append(call_id) <NEW_LINE> self.calls.metadata[call_id] = metadata <NEW_...
register Call-ID and its' metadata.
625941e71f037a2d8b94666b
def get_ports_for_service(self, service, protocol): <NEW_LINE> <INDENT> regexp = "(.*?)\t(.*?/.*?)\t(.*?)($|\t)(#.*){0,1}" <NEW_LINE> re.compile(regexp) <NEW_LINE> list = [] <NEW_LINE> f = FileOperations.open(self.get_nmap_services_file()) <NEW_LINE> for line in f.readlines(): <NEW_LINE> <INDENT> if line.lower().find(s...
Get ports for different services :param service: Service name :type service: `str` :param protocol: Protocol :type protocol: `str` :return: List of ports :rtype: `list`
625941e78e05c05ec3eea7e7
def __mark_tree(self, file_list, idx, mark_all=False): <NEW_LINE> <INDENT> total_marked = 0 <NEW_LINE> for element in file_list: <NEW_LINE> <INDENT> marked = 0 <NEW_LINE> if (element[1] == idx) or mark_all: <NEW_LINE> <INDENT> if element[3]: <NEW_LINE> <INDENT> marked = self.__mark_tree(element[3], idx, True) <NEW_LINE...
Given file_list of TorrentDetail and index of file or folder, recursively selects all files contained as well as marks folders higher in hierarchy as partially selected
625941e7e5267d203edce106
def run_extension(self, name: str, **extension_init_params) -> None: <NEW_LINE> <INDENT> if typing.TYPE_CHECKING: <NEW_LINE> <INDENT> BaseExtension = typing.Type[T] <NEW_LINE> <DEDENT> extension: BaseExtension = self.extensions.get(name) <NEW_LINE> if not extension: <NEW_LINE> <INDENT> raise RuntimeError("Undefined ext...
:param name: name of the extension :param extension_init_params: params which accept the extension constructor :return:
625941e745492302aab5e736
def test_remove_section_from_config_when_last_option_removed(self): <NEW_LINE> <INDENT> self.config.remove('séction5', 'öption1') <NEW_LINE> self.config.remove('séction5', 'öption2') <NEW_LINE> self.config.remove('séction5', 'öption3') <NEW_LINE> self._assert_section_removed()
Section is removed from configuration when last option is removed from the configuration.
625941e7eab8aa0e5d26dfc8
def GetNumberOfPixelsCounted(self): <NEW_LINE> <INDENT> return _itkImageToImageMetricPython.itkImageToImageMetricIF3IF3_GetNumberOfPixelsCounted(self)
GetNumberOfPixelsCounted(self) -> unsigned long
625941e7be7bc26dc91cda66
def __init__( self: ToolLogger, name: str, level: LogLevel, logfmt: str = LOG_FMT ) -> None: <NEW_LINE> <INDENT> super().__init__(name, level=level) <NEW_LINE> self.set_format(logfmt)
Create a ToolLogger with the specified name, level, and format. Log format gets applied immediately.
625941e7377c676e91272616
def ndcToWindow(self, ndcX, ndcY, checkInside=True): <NEW_LINE> <INDENT> if (checkInside and (ndcX < -1. or ndcX > 1. or ndcY < -1. or ndcY > 1.)): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ox, oy = self._origin <NEW_LINE> width, height = self.size <NEW_LINE> winx = ox + width * 0.5 * (ndcX + 1.) <NEW_LINE> w...
Convert position from normalized device coordinates (NDC) to window. :param float ndcX: X NDC coord. :param float ndcY: Y NDC coord. :param bool checkInside: If True, returns None if position is outside viewport. :return: (x, y) window coordinates or None. Origin top-left, x to the ri...
625941e7e64d504609d74caf
def test_pickling(self): <NEW_LINE> <INDENT> pwm = self.pwm <NEW_LINE> pwm.delta1 = 1 <NEW_LINE> pwm.delta2 = 2 <NEW_LINE> pwm.qbroad = 3 <NEW_LINE> pwm2 = pickle.loads(pickle.dumps(pwm)) <NEW_LINE> self.assertEqual(JeongPeakWidth, type(pwm2)) <NEW_LINE> self.assertEqual(1, pwm2.delta1) <NEW_LINE> self.assertEqual(2, p...
check pickling of the DebyeWallerPeakWidth class
625941e7046cf37aa974d1b2
def __contains__(self, key): <NEW_LINE> <INDENT> return key.lower() in self._dictionary
turn on contains
625941e74f6381625f114eab
def strdchk(file): <NEW_LINE> <INDENT> firststrand = 0 <NEW_LINE> secondstrand = 0 <NEW_LINE> total = 0 <NEW_LINE> for read in file.fetch(region = test_region): <NEW_LINE> <INDENT> if read.proper_pair and read.aligned and not read.failed_platform_qc and read.optional_field('NH') == 1: <NEW_LINE> <INDENT> if ...
Check if the library is first (dUTP method) or second strand or unstranded
625941e74f6381625f114eaa
def afni_not_installed(): <NEW_LINE> <INDENT> if afni.Info.version is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
XXX: This test assumes that AFNI.Info.version will not crash on a system without AFNI installed
625941e7925a0f43d254a2ea
def find_best_telescope(comparitive_values): <NEW_LINE> <INDENT> sensor_status, unused_comparitives = get_sensors(comparitive_values) <NEW_LINE> sensor_status_sums = np.sum(sensor_status, axis = 1) <NEW_LINE> good_telescopes = np.where(sensor_status_sums == 0) <NEW_LINE> bad_telescopes = np.where(sensor_status_sums != ...
A function for finding the best telescope. The first telescope with no triggered sensors is selected. The value returned corresponds to this telescope. A value of 4 signifies no telescope without a triggered sensor exists. An array of all the good telescopes and one for the bad telescopes is also returned.
625941e70a50d4780f667305
def plotMPTPSpikeRates(mptp_file): <NEW_LINE> <INDENT> data = loadtxt(mptp_file, unpack=True) <NEW_LINE> data = data.T <NEW_LINE> stn = np.array([row for row in data if 0 <= (row[1]-global_gidoffset) < 10]) <NEW_LINE> gpe = np.array([row for row in data if 10 <= (row[1]-global_gidoffset) < 40]) <NEW_LINE> gpi = np.arra...
Takes mptp spikes file as input, processes data, and plots spike rates
625941e7dd821e528d63b614
@app.route("/quote", methods=["GET", "POST"]) <NEW_LINE> @helpers.login_required <NEW_LINE> def quote(): <NEW_LINE> <INDENT> quote = None <NEW_LINE> if flask.request.method == "POST": <NEW_LINE> <INDENT> if not flask.request.form.get("symbol"): <NEW_LINE> <INDENT> return helpers.apology("must provide symbol", 400) <NEW...
Get stock quote (via helpers.lookup).
625941e76fb2d068a760f513
def train(self, o1, a, r, o2, t, l, u, w): <NEW_LINE> <INDENT> train_op, losses, loss = self.sess.run([self.train_op, self.losses, self.loss], feed_dict={self.observation:o1, self.actions:a, self.rewards:r, self.next_observation:o2, self.terminals:t, self.max_ls:l, self.min_us:u, self.importance_sampling_weights:w}) <N...
train network on batch of experiences Args: o1: first observations a: actions taken r: rewards received o2: succeeding observations
625941e767a9b606de4a8326
def get_cpu_info(): <NEW_LINE> <INDENT> cpu_cores = cpu_count() <NEW_LINE> cpu_info = open('/proc/cpuinfo').read().split("\n\n")[0] <NEW_LINE> cpu_name = re.search(r"^model name\s+: (.*)$", cpu_info, re.M).groups()[0] <NEW_LINE> mem_info = check_output('free -m', shell=True).decode('utf-8') <NEW_LINE> mem_info = mem_in...
Get CPU name, memory, and core count.
625941e771ff763f4b549b02
def humansize(size): <NEW_LINE> <INDENT> multiplier = 1024.0 <NEW_LINE> if size < multiplier: <NEW_LINE> <INDENT> return "%dB" % size <NEW_LINE> <DEDENT> for unit in ['Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: <NEW_LINE> <INDENT> size /= multiplier <NEW_LINE> if size < multiplier: <NEW_LINE> <INDENT> if size < 10: <NEW...
Return a human readable string of the given size in bytes.
625941e74c3428357757c794
def get_problems_by_statement_id(statement_id: int, filter_hidden=True) -> list: <NEW_LINE> <INDENT> problems_statement_problems = db.session.query(Problem, StatementProblem) .join(StatementProblem, StatementProblem.problem_id == Problem.id) .filter(StatementProblem.statement_id == statement_id) .o...
Get all problems from is's id SELECT mdl_problems.id, mdl_statements_problems_correlation.rank, mdl_problems.name, mdl_statements_problems_correlation.hidden as cur_hidden, mdl_ejudge_problem.short_id, mdl_problems.pr_id, mdl_ejudge_problem.contest_id FROM mdl_problems, mdl_statements_p...
625941e7b57a9660fec33cf9
def get_pid(self): <NEW_LINE> <INDENT> if self.child is not None: <NEW_LINE> <INDENT> return self.child.pid+1
Returns the PID of the child.
625941e72eb69b55b151cd25
def get_recipients(self): <NEW_LINE> <INDENT> User = get_user_model() <NEW_LINE> emails = [] <NEW_LINE> if not self.is_filtered: <NEW_LINE> <INDENT> users = User.objects.filter(is_active=True).only('email') <NEW_LINE> for user in users: <NEW_LINE> <INDENT> if not user.email in emails: <NEW_LINE> <INDENT> emails += [use...
Determine recipients depending on selected filtering which can be either: * group based * layer based * user based Choosing "group" and "layer" filtering together has the effect of sending the message only to users for which the following conditions are both true: * have a node assigned to one of the s...
625941e7e76e3b2f99f3ac73
def test_a_sendCons1(self): <NEW_LINE> <INDENT> self.log.info('sendConsultation:正确性测试') <NEW_LINE> params = getConsParams.getParam(config.appDBConf,'sendConsultation',config.primid2) <NEW_LINE> result=httpRequest.postRequest(config.app_url,params) <NEW_LINE> self.assertEqual(result['code'],"200") <NEW_LINE> message=jso...
sendConsultation,正确性测试
625941e7a17c0f6771cbe4be
def apply_gain(self, trim=True): <NEW_LINE> <INDENT> datasec_img = self.spectrograph.get_datasec_img(self.files[0], det=self.det) <NEW_LINE> if trim: <NEW_LINE> <INDENT> datasec_img = procimg.trim_frame(datasec_img, datasec_img < 1) <NEW_LINE> <DEDENT> if self.stack.shape != datasec_img.shape: <NEW_LINE> <INDENT> raise...
Apply gain (instead of ampsec scale) Parameters ---------- Returns ------- self.mspixelflat -- Modified internally
625941e73cc13d1c6d3c77e7
def pad_a(self, a, padchar="X"): <NEW_LINE> <INDENT> if len(a)%2 == 1: <NEW_LINE> <INDENT> a.append(self.getIndex(padchar)) <NEW_LINE> <DEDENT> return a
Add the numerical value of padchar (default 'X') to list a if length of a is odd
625941e755399d3f05588b26
def setUp(self): <NEW_LINE> <INDENT> self.proto = MemCacheProtocol() <NEW_LINE> self.clock = Clock() <NEW_LINE> self.proto.callLater = self.clock.callLater <NEW_LINE> self.transport = StringTransportWithDisconnection() <NEW_LINE> self.transport.protocol = self.proto <NEW_LINE> self.proto.makeConnection(self.transport)
Create a memcache client, connect it to a string protocol, and make it use a deterministic clock.
625941e750485f2cf553d20b
def _tokenize(str, errors): <NEW_LINE> <INDENT> tokens = [] <NEW_LINE> lines = str.split('\n') <NEW_LINE> linenum = 0 <NEW_LINE> while linenum < len(lines): <NEW_LINE> <INDENT> line = lines[linenum] <NEW_LINE> indent = len(line)-len(line.lstrip()) <NEW_LINE> if indent == len(line): <NEW_LINE> <INDENT> linenum += 1 <NEW...
Split a given formatted docstring into an ordered list of C{Token}s, according to the epytext markup rules. @param str: The epytext string @type str: C{string} @param errors: A list where any errors generated during parsing will be stored. If no list is specified, then errors will generate exceptions. @type ...
625941e723e79379d52ee9cd
def t110230_x24(): <NEW_LINE> <INDENT> if not CheckSpecificPersonTalkHasEnded(0): <NEW_LINE> <INDENT> ClearTalkProgressData() <NEW_LINE> StopEventAnimWithoutForcingConversationEnd(0) <NEW_LINE> ReportConversationEndToHavokBehavior() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> """State 2""" <N...
State 0,1
625941e7be8e80087fb210ab
def update_when_done(func: CallableT) -> CallableT: <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> async def wrapper(self: EvilGeniusEntity, *args: Any, **kwargs: Any) -> Any: <NEW_LINE> <INDENT> result = await func(self, *args, **kwargs) <NEW_LINE> await self.coordinator.async_request_refresh() <NEW_LINE> return result <...
Decorate function to trigger update when function is done.
625941e7a17c0f6771cbe4bf
def set_manager(self, account_type, first_name, last_name): <NEW_LINE> <INDENT> manager = first_name + " " + last_name <NEW_LINE> if account_type.lower() == "bill": <NEW_LINE> <INDENT> self.single_selection_from_kendo_dropdown(self.billing_manager_dropdown_locator, manager) <NEW_LINE> <DEDENT> elif account_type.lower()...
Implementing set manager functionality :param account_type: :param first_name: :param last_name: :return:
625941e7627d3e7fe0d692c1
def register_resource(self, resource): <NEW_LINE> <INDENT> self.resources.append(resource) <NEW_LINE> if self.backend: <NEW_LINE> <INDENT> resource.contribute_api(self.backend)
Register a resource with the Api This will cause the resource's backend attribute to be populated. Args: resource (:class:`~repose.resources.Resource`): The resource class to register
625941e74e696a04525c98bd
def replace_text(self, text, replace_dict): <NEW_LINE> <INDENT> for key, value in replace_dict.iteritems(): <NEW_LINE> <INDENT> text = text.replace(key, value) <NEW_LINE> <DEDENT> return text
Substitute items in a text string. text: A string with embedded %tags%. replace_dict: A dict, where key: Corresponds to the % delimited tag in text. value: Text to swap in.
625941e7d53ae8145f87a6d6
def test__url_to_search_params_range_multi_3(self): <NEW_LINE> <INDENT> q = QueryDict('RINGGEOphase1=0&RINGGEOphase2=355.201&RINGGEOphase1_1=10&RINGGEOphase2_1=255.201&qtype-RINGGEOphase=only&qtype-RINGGEOphase_1=all&qtype-RINGGEOphase_2=only') <NEW_LINE> (selections, extras) = url_to_search_params(q) <NEW_LINE> sel_ex...
[test_search.py] url_to_search_params: range multi 3
625941e7a8370b7717052d0d
def merge_sort(thelist): <NEW_LINE> <INDENT> if len(thelist) > 1: <NEW_LINE> <INDENT> mid = len(thelist) // 2 <NEW_LINE> lefthalf = thelist[:mid] <NEW_LINE> righthalf = thelist[mid:] <NEW_LINE> merge_sort(lefthalf) <NEW_LINE> merge_sort(righthalf) <NEW_LINE> i = 0 <NEW_LINE> j = 0 <NEW_LINE> k = 0 <NEW_LINE> while i < ...
Sorts a list using MergeSort function.
625941e77cff6e4e81117df5
def _parse_message(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _, values = data.split(':') <NEW_LINE> values = values.split(',') <NEW_LINE> if len(values) <= 3: <NEW_LINE> <INDENT> self.event_data, self.partition, self.event_type = values <NEW_LINE> self.version = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <I...
Parses the raw message from the device. :param data: message data to parse :type data: string :raises: :py:class:`~alarmdecoder.util.InvalidMessageError`
625941e78c0ade5d55d3ee2e
def test_sanitize_mapping_file(self): <NEW_LINE> <INDENT> o_sanitized_headers, o_sanitized_data = sanitize_mapping_file( UNSANITZIED_MAPPING_DATA, ['SampleID', 'BarcodeSequence', 'LinkerPrimerSequence', 'Treatment', 'DOB', 'Descr"""""iption']) <NEW_LINE> self.assertEquals(o_sanitized_data, ['SampleID', 'BarcodeSequence...
Check the mapping file strings are sanitized for it's use in JS
625941e7462c4b4f79d1db3f
def __init__(self, config, logger): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.logger = logger
Object initialization.
625941e730c21e258bdfa911
def namespace_prepend(namespace): <NEW_LINE> <INDENT> return type("Prepend_%s" % namespace, (PrependerAction,), {"prepend_text": CVRF_Syntax.NAMESPACES[namespace]})
Returns a dynamic class (not instance) with appropriate prepend_text.
625941e75fc7496912cc3ded
def test_attctl(self): <NEW_LINE> <INDENT> boundary_x = 200 <NEW_LINE> boundary_y = 100 <NEW_LINE> boundary_z = 50 <NEW_LINE> self.wait_for_topics(60) <NEW_LINE> self.wait_for_landed_state(mavutil.mavlink.MAV_LANDED_STATE_ON_GROUND, 10, -1) <NEW_LINE> self.log_topic_vars() <NEW_LINE> self.set_mode("OFFBOARD", 5) <NEW_L...
Test offboard attitude control
625941e76e29344779a62a7f
def fraction_to_midi(fraction): <NEW_LINE> <INDENT> return max(5, 20 + int(10 * math.log(1000 * fraction)))
Args: fraction: A number between zero and one Returns: An integer for midi
625941e7b830903b967e9d76
def get_service_class(name): <NEW_LINE> <INDENT> return ServiceType.get_class(name, default=True)
Return service class specified by it's name
625941e74527f215b584c8c2
def __logout__(self): <NEW_LINE> <INDENT> if not self.__check_log_statue__(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> print(self.dbg_info["info"] % "bye~bye") <NEW_LINE> self.bkjw.logout() <NEW_LINE> self.log_statue = False
登出 :return:None
625941e7566aa707497f49d2
def keep_empty_group(self, group): <NEW_LINE> <INDENT> bool_keep = EditCommand.keep_empty_group(self, group) <NEW_LINE> if not bool_keep: <NEW_LINE> <INDENT> if isinstance(group, self.assy.DnaGroup): <NEW_LINE> <INDENT> bool_keep = True <NEW_LINE> <DEDENT> <DEDENT> return bool_keep
Returns True if the empty group should not be automatically deleted. otherwise returns False. The default implementation always returns False. Subclasses should override this method if it needs to keep the empty group for some reasons. Note that this method will only get called when a group has a class constant autde...
625941e76e29344779a62a80
def corner_offsets(self, offsets, x_first=False): <NEW_LINE> <INDENT> for corner in self.corners(): <NEW_LINE> <INDENT> def new(coordinates): <NEW_LINE> <INDENT> return self.EdgePoint(coordinates, corner.displacement_factors) <NEW_LINE> <DEDENT> x = corner.displaced(offsets) <NEW_LINE> y = corner.displaced(offsets[::-1...
A generator of 4 pairs of points, each at symmetric offsets. The offsets argument is expected to be a Point, or treatable as such, where the x coordinate is larger than the y coordinate. This produces a pattern like the following: 2 3 1 4 8 5 7 6 Used to generate frames.
625941e7a4f1c619b28b049e
def safe_factorial(fact): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> n = input("Введите число для расчёта факториала " "(Enter - чтобы выйти): ") <NEW_LINE> if not n: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> n = int(n) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pri...
Обработка пользовательского ввода и расчёт факториала с выводом результата на экран Аргументы: fact (анонимная функция): вычисляет факториал
625941e721a7993f00bc8167
@app.route('/', methods=['GET', 'POST']) <NEW_LINE> def index(): <NEW_LINE> <INDENT> page = request.values.get('page', 1, type=int) <NEW_LINE> size = request.values.get('size', 1, type=int) <NEW_LINE> query = Query(request.values.get('q', ''))[(page-1)*size:page*size] <NEW_LINE> response = current_search_client.search(...
Query Elasticsearch using Invenio query syntax.
625941e78e7ae83300e4b43e
def JSD(self, P, Q): <NEW_LINE> <INDENT> P[P<=0] = 1e-100 <NEW_LINE> Q[Q<=0] = 1e-100 <NEW_LINE> P_normed = P / norm(P, ord=1) <NEW_LINE> Q_normed = Q / norm(Q, ord=1) <NEW_LINE> M = 0.5 * (P + Q) <NEW_LINE> return 0.5 * (entropy(P,M) + entropy(Q,M))
Arguments: P,Q - discrete probability distribution Return: Jensen-Shannon divergence
625941e7a934411ee3751b04
def RequestJson(*args, **kwargs): <NEW_LINE> <INDENT> return json.loads(Request(*args, **kwargs))
Fetch a URL and JSON-decode the response. See the documentation for Request() for details about the arguments and exceptions.
625941e763f4b57ef000157c
def trajectories_table(fname, first=None, last=None): <NEW_LINE> <INDENT> outfile = tables.open_file(fname, mode='r') <NEW_LINE> table = outfile.get_node('/particles') <NEW_LINE> query_string = ('(trajid == trid)') <NEW_LINE> if first is not None: <NEW_LINE> <INDENT> query_string += " & (time >= %d)" % first <NEW_LINE>...
Reads trajectories from a PyTables HDF5 file, as saved by save_particles_table(). Arguments: fname - path to file to read. first, last - inclusive range of frames to read. Returns: trajects - a list of Trajectory objects, each trimmed to the frame range.
625941e7656771135c3ebce4
def UpdateItems(self, selected='SAME'): <NEW_LINE> <INDENT> gList = self.gList <NEW_LINE> items = set(self.data.keys()) <NEW_LINE> index = 0 <NEW_LINE> if selected == 'SAME': selected = set(self.GetSelected()) <NEW_LINE> while index < gList.GetItemCount(): <NEW_LINE> <INDENT> item = self.GetItem(index) <NEW_LINE> if it...
Update all items.
625941e77d43ff24873a3113
def get_bundle_widget_types_details_using_get_with_http_info(self, is_system, bundle_alias, **kwargs): <NEW_LINE> <INDENT> all_params = ['is_system', 'bundle_alias'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LIN...
Get all Widget types details for specified Bundle (getBundleWidgetTypes) # noqa: E501 Returns an array of Widget Type Details objects that belong to specified Widget Bundle.Widget Type Details extend Widget Type and add image and description properties. Those properties are useful to edit the Widget Type but they are...
625941e796565a6dacc8fb3a
def close ( self ): <NEW_LINE> <INDENT> if self.fh: self.fh.close()
Closes this listener (closes the file handle if open).
625941e77b180e01f3dc4c64
def _serialize(self): <NEW_LINE> <INDENT> result = {'host_id': self.id, 'parent_id': self.parent.dagobah_id, 'host_name': self.name } <NEW_LINE> return result
Serialize a representation of this Host to a Python dict.
625941e7d8ef3951e32439ad
def get_pet_labels(image_dir): <NEW_LINE> <INDENT> in_files = listdir(image_dir) <NEW_LINE> results_dic = dict() <NEW_LINE> for idx in range(0, len(in_files), 1): <NEW_LINE> <INDENT> if in_files[idx][0] != ".": <NEW_LINE> <INDENT> pet_label = "" <NEW_LINE> for files in in_files[idx]: <NEW_LINE> <INDENT> pet_label = fil...
Creates a dictionary of pet labels (results_dic) based upon the filenames of the image files. These pet image labels are used to check the accuracy of the labels that are returned by the classifier function, since the filenames of the images contain the true identity of the pet in the image. Be sure to format the pe...
625941e78c3a873295158830