code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _Net_set_mean(self, input_, mean_f, mode='elementwise'): <NEW_LINE> <INDENT> if not hasattr(self, 'mean'): <NEW_LINE> <INDENT> self.mean = {} <NEW_LINE> <DEDENT> if input_ not in self.inputs: <NEW_LINE> <INDENT> raise Exception('Input not in {}'.format(self.inputs)) <NEW_LINE> <DEDENT> in_shape = self.blobs[input_]...
Set the mean to subtract for data centering. Take input_: which input to assign this mean. mean_f: path to mean .npy with ndarray (input dimensional or broadcastable) mode: elementwise = use the whole mean (and check dimensions) channel = channel constant (e.g. mean pixel instead of mean image)
625941c68e7ae83300e4aff4
def __Database__export_server(self, dev_info): <NEW_LINE> <INDENT> if not isinstance(dev_info, collections_abc.Sequence) and not isinstance(dev_info, DbDevExportInfo): <NEW_LINE> <INDENT> raise TypeError( 'Value must be a DbDevExportInfos, a seq<DbDevExportInfo> or ' 'a DbDevExportInfo') <NEW_LINE> <DEDENT> ...
export_server(self, dev_info) -> None Export a group of devices to the database. Parameters : - devinfo : (sequence<DbDevExportInfo> | DbDevExportInfos | DbDevExportInfo) containing the device(s) to export information Return : None Throws : ConnectionFailed, Co...
625941c650485f2cf553cdc1
def __call__(self, labels): <NEW_LINE> <INDENT> if not isinstance(labels, torch.Tensor): <NEW_LINE> <INDENT> labels = torch.tensor(labels) <NEW_LINE> <DEDENT> if labels.dim() == 0: <NEW_LINE> <INDENT> n_labels = torch.zeros(self.classes, dtype=self.dtype) <NEW_LINE> n_labels[int(labels)] = 1 <NEW_LINE> return n_labels ...
Args: labels (torch.tensor): Input to be made categorical. Returns: torch.tensor: A categorical representation of the input labels.
625941c6507cdc57c6306d00
def new_service(): <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> try: <NEW_LINE> <INDENT> sock.bind(('localhost', 3368)) <NEW_LINE> sock.listen(1000) <NEW_LINE> print("bind 3368,ready to use") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("Server is already running,quit...
start a service socket and listen when coms a connection, start a new thread to handle it
625941c650812a4eaa59c34b
def get_snmp_request(ibmc): <NEW_LINE> <INDENT> token = ibmc.bmc_token <NEW_LINE> url = ibmc.manager_uri + "/SnmpService" <NEW_LINE> headers = {'content-type': 'application/json', 'X-Auth-Token': token} <NEW_LINE> payload = {} <NEW_LINE> try: <NEW_LINE> <INDENT> request_result = ibmc.request('GET', resource=url, header...
Function: Get the return result of the redfish interface Args: ibmc : Class that contains basic information about iBMC Returns: SNMP request info Raises: Get SNMP resource info failed! Date: 2019/10/29 21:47
625941c6adb09d7d5db6c7b8
def jacobian(self, points): <NEW_LINE> <INDENT> raise NotImplementedError()
Transposed Jacobian of the transform with respect to its parameters Parameters ---------- x : array-like, shape (n_points, n_dimensions) Location of the Jacobian to be calculated Returns ------- J : array-like, shape (n_points, n_parameters, n_dimensions) :math:`J = D^T_\theta\phi(x)`
625941c68a43f66fc4b5408e
def query_one_row(QUERY, desfile=os.path.join(os.environ['HOME'], '.desservices.ini'), section=None): <NEW_LINE> <INDENT> recs = make_db_query(QUERY, desfile=desfile, section=section) <NEW_LINE> if len(recs) != 1: <NEW_LINE> <INDENT> err = 'Exactly one row expected, got {nr} rows instead!\nQUERY:{Q}' <NEW_LINE> if logg...
Funtion opens a DB connection, gets a cursor, executes the QUERY, expects exactly one row to be returned, raises Exception otherwise.
625941c61d351010ab855b44
def login(ask_credentials=True): <NEW_LINE> <INDENT> g.CACHE.invalidate() <NEW_LINE> try: <NEW_LINE> <INDENT> if ask_credentials: <NEW_LINE> <INDENT> ui.ask_credentials() <NEW_LINE> <DEDENT> if not common.make_call('login'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> except Mis...
Perform a login
625941c6498bea3a759b9ad7
def checkParameters(self): <NEW_LINE> <INDENT> self.DEBUG("EDPluginExecEpydocv1_0.checkParameters") <NEW_LINE> self.checkMandatoryParameters(self.getDataInput(), "Data Input is None") <NEW_LINE> self.checkMandatoryParameters(self.getDataInput().getDocPath(), "No output documentation path provided") <NEW_LINE> self.chec...
Checks the mandatory parameters.
625941c6a17c0f6771cbe07a
def printCustomSetup(customDict, uniVals = "Universe"): <NEW_LINE> <INDENT> title = "Custom %s Values" % uniVals <NEW_LINE> print("\n\n\n%s%s%s\n" % ("-" * 20, title, "-" * 20)) <NEW_LINE> for i in iter(customDict): <NEW_LINE> <INDENT> if isinstance(customDict[i], dict): <NEW_LINE> <INDENT> print(i) <NEW_LINE> for x in...
prints out the custom setup.
625941c6cb5e8a47e48b7ad4
def practice0(method = 1): <NEW_LINE> <INDENT> src_num = (1,2,3,4) <NEW_LINE> dst_num = [] <NEW_LINE> if method == 1: <NEW_LINE> <INDENT> for i in src_num: <NEW_LINE> <INDENT> for j in src_num: <NEW_LINE> <INDENT> for k in src_num: <NEW_LINE> <INDENT> if (i != j) and (i != k) and (j != k): <NEW_LINE> <INDENT> str_com =...
数字组合
625941c6379a373c97cfab6c
def output_policies(self, learned_policies, obstacles, policy_file): <NEW_LINE> <INDENT> with open(policy_file, mode='w') as f: <NEW_LINE> <INDENT> for i, (x, y) in enumerate(product(range(self.maze_dimension[0]), range(self.maze_dimension[1]))): <NEW_LINE> <INDENT> if (x, y) not in obstacles: <NEW_LINE> <INDENT> f.wri...
Output learned policies \pi(s) to file.
625941c67cff6e4e811179ae
def test_push_configuration_status(device_fixture): <NEW_LINE> <INDENT> device = device_fixture <NEW_LINE> r_value = ('{"message":"[root@LINUX-FW ~]# [root@LINUX-FW ~]#\n ",' '"date":"27-06-2018 09:15:33","status":"ENDED"}') <NEW_LINE> with patch('requests.get') as mock_call_get: <NEW_LINE> <INDENT> mock_call_get.retur...
Test push configuration
625941c691f36d47f21ac519
def strStr(self, haystack, needle): <NEW_LINE> <INDENT> if needle=='': <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if haystack=='' or len(haystack)<len(needle): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> return haystack.find(needle)
:type haystack: str :type needle: str :rtype: int
625941c6be383301e01b54b0
def _pretty_logging(data): <NEW_LINE> <INDENT> def _picker(x): <NEW_LINE> <INDENT> if isinstance(x, DataFlowAbstraction): <NEW_LINE> <INDENT> return x.name <NEW_LINE> <DEDENT> elif isinstance(x, DataFrame): <NEW_LINE> <INDENT> return "pd.DataFrame({})".format(str(x.columns)) <NEW_LINE> <DEDENT> elif isinstance(x, tuple...
Returns the dictionary 'data' with a suitable form for logging
625941c629b78933be1e56d6
def message_ports_in(self): <NEW_LINE> <INDENT> return _howto_swig.sc_fdma_interleaver_sptr_message_ports_in(self)
message_ports_in(sc_fdma_interleaver_sptr self) -> swig_int_ptr
625941c632920d7e50b281f7
def get_high_d_function_caller_from_low_d_func(domain_dim, low_d_func, low_d_domain_bounds, low_d_opt_val, low_d_opt_pt, **kwargs): <NEW_LINE> <INDENT> group_dim = len(low_d_domain_bounds) <NEW_LINE> high_d_func, num_groups = get_high_d_function_from_low_d(domain_dim, group_dim, low_d_func) <NEW_LINE> high_d_domain_bou...
Gets a low dimensional function caller from a high dimensional one.
625941c6d58c6744b4257c88
def test_hisHers(self): <NEW_LINE> <INDENT> self.assertEqual(fourForms(hisHers), (u"hers", u"his", u"its", u"theirs"))
L{Noun.hisHers} returns a gender-appropriate substantival possessive pronoun.
625941c6bf627c535bc131f7
def save_residual_plot(file_path, list_data, height, width, overwrite=True, dpi=100): <NEW_LINE> <INDENT> if "\\" in file_path: <NEW_LINE> <INDENT> raise ValueError( "Please use a file path following the Unix convention") <NEW_LINE> <DEDENT> _create_folder(file_path) <NEW_LINE> if not overwrite: <NEW_LINE> <INDENT> fil...
Save the plot of residual against radius to an image. Useful to check the accuracy of unwarping results. Parameters ---------- file_path : str Output file path. list_data : array_like 2D array. List of [residual, radius] of each dot. height : int Height of the output image. width : int Width of the out...
625941c64e4d5625662d4402
def slow(self, callback=False): <NEW_LINE> <INDENT> self.speed += 5
Down arrow key
625941c67b25080760e39482
def tr(self, message): <NEW_LINE> <INDENT> return QCoreApplication.translate('ocwPlugin', message)
Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString
625941c67d43ff24873a2cc8
def audit_compulsory(self, encrypt_seed, amount, fee): <NEW_LINE> <INDENT> amount = str_num_to_decimal(amount) <NEW_LINE> fee = str_num_to_decimal(fee) <NEW_LINE> if not amount: <NEW_LINE> <INDENT> return CodeMsg.CM(1008, '金额有误') <NEW_LINE> <DEDENT> if not fee: <NEW_LINE> <INDENT> return CodeMsg.CM(1009, '手续费有误') <NEW_...
审核通用代码
625941c6851cf427c661a538
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) <NEW_LINE> def do_unrescue(cs, args): <NEW_LINE> <INDENT> _find_server(cs, args.server).unrescue()
Unrescue a server.
625941c6fbf16365ca6f61ea
def __init__(self, config, basename, centerName): <NEW_LINE> <INDENT> JudgmentVerification.__init__(self, config, basename) <NEW_LINE> self.bi = centerName() <NEW_LINE> pass
:param config: 头文件所在位置 :param basename: 执行用例的文件名 :param centerName: 参数定义的类对象
625941c6377c676e912721d1
def best_wild_hand(hand): <NEW_LINE> <INDENT> hands = set(best_hand(h) for h in itertools.product(*map(replacements, hand))) <NEW_LINE> return list(max(hands, key=hand_rank))
Try all values for jokers in all 5-card selections.
625941c630dc7b7665901990
def _timestamp_check(timestamp_client): <NEW_LINE> <INDENT> now_time = int(time.time()) <NEW_LINE> if -300 < now_time-timestamp_client < 300: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
校队客户端请求的时间戳是否在允许范围之内
625941c6a8ecb033257d30f6
def box_volume(h, w=None, b=None, base_area=None): <NEW_LINE> <INDENT> if base_area: <NEW_LINE> <INDENT> return h * base_area <NEW_LINE> <DEDENT> if b is None: <NEW_LINE> <INDENT> b = h <NEW_LINE> <DEDENT> if w is None: <NEW_LINE> <INDENT> w = h <NEW_LINE> <DEDENT> base_area = rectangle_area(w, b) <NEW_LINE> return h *...
Calculate the volume of a box (rectangular cuboid) with side lengths «h», «w» and «b». https://en.wikipedia.org/wiki/Cuboid
625941c6442bda511e8be442
def t_QUOTE(t): <NEW_LINE> <INDENT> t.lexer.begin('quoted') <NEW_LINE> return t
"
625941c610dbd63aa1bd2bcc
def test_appending_records_with_io_stream(): <NEW_LINE> <INDENT> schema = { "type": "record", "name": "test_appending_records_with_io_stream", "fields": [{ "name": "field", "type": "string", }] } <NEW_LINE> stream = MemoryIO() <NEW_LINE> fastavro.writer(stream, schema, [{"field": "foo"}]) <NEW_LINE> fastavro.writer(str...
https://github.com/fastavro/fastavro/issues/276
625941c6956e5f7376d70e97
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AchievementDefinitionResource): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c615baa723493c3f9d
def accept(self, *args): <NEW_LINE> <INDENT> return _pilot.OptimizerLoop_accept(self, *args)
accept(OptimizerLoop self, Visitor visitor)
625941c6ad47b63b2c509fa8
def do_schedule(self, timer=True): <NEW_LINE> <INDENT> state = self.get_state() <NEW_LINE> self._update_torrents() <NEW_LINE> if state == 'Green': <NEW_LINE> <INDENT> self.__apply_set_functions() <NEW_LINE> <DEDENT> elif state == 'Yellow': <NEW_LINE> <INDENT> settings = { 'active_limit': self.config['low_active'], 'act...
This is where we apply schedule rules.
625941c666673b3332b920b9
def __init__(self, id=None, reference_id=None, from_state=None, to_state=None, location_id=None, catalog_object_id=None, catalog_object_type=None, quantity=None, total_price_money=None, occurred_at=None, created_at=None, source=None, employee_id=None, transaction_id=None, refund_id=None, purchase_order_id=None, goods_r...
InventoryAdjustment - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941c6c4546d3d9de72a5b
def Grandezza_vettore(Vettore): <NEW_LINE> <INDENT> Grand = round(np.sqrt(np.dot(Vettore, Vettore)), Vers_dec) <NEW_LINE> return Grand
Calcola la grandezza di un vettore. ================================================================================= ARGOMENTI --------------------------------------------------------------------------------- :param Vettore: ==> Tipo: numpy.array Vettore, deve essere in form...
625941c68c3a8732951583e2
def start_soffice(self): <NEW_LINE> <INDENT> if self.sub: <NEW_LINE> <INDENT> return_code = self.sub.poll() <NEW_LINE> if return_code: <NEW_LINE> <INDENT> self.sub.wait() <NEW_LINE> <DEDENT> <DEDENT> self.sub = subprocess.Popen( args=[ "/usr/bin/soffice", "--impress", "--accept=socket,host=localhost," "port=2002;urp;St...
Start a new soffice process and listen on port 2002.
625941c657b8e32f524834c3
def create_token( self, registry_address, initial_alloc=10 ** 6, name='raidentester', symbol='RDT', decimals=2, timeout=60, auto_register=True, ): <NEW_LINE> <INDENT> contract_path = get_contract_path('HumanStandardToken.sol') <NEW_LINE> with gevent.Timeout(timeout): <NEW_LINE> <INDENT> token_proxy = self._chain.client...
Create a proxy for a new HumanStandardToken (ERC20), that is initialized with Args(below). Per default it will be registered with 'raiden'. Args: initial_alloc (int): amount of initial tokens. name (str): human readable token name. symbol (str): token shorthand symbol. decimals (int): decimal places. ...
625941c699fddb7c1c9de3ba
def FWHM_s(FWHM): <NEW_LINE> <INDENT> return FWHM/(2*np.sqrt(2*np.log(2)))
Given the FWHM of a Gaussian, returns the width (sigma)
625941c6435de62698dfdc75
def __init__(self, name=None, callerid_id=None, whitelabel=None, phone=None, extension=None): <NEW_LINE> <INDENT> self.swagger_types = { 'name': 'str', 'callerid_id': 'str', 'whitelabel': 'bool', 'phone': 'str', 'extension': 'str' } <NEW_LINE> self.attribute_map = { 'name': 'name', 'callerid_id': 'callerid_id', 'whitel...
CreateRecordingByPhoneParameters - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941c656b00c62f0f14681
def decrypt(self, data): <NEW_LINE> <INDENT> d = b64decode(data) <NEW_LINE> c = AES.new(self._key, self._mode, d[:self._bs]) <NEW_LINE> return self._unpad(c.decrypt(d[self._bs:])).decode('utf-8')
Decrypts data specified Args: data (str): Base64-encoded data to be decrypted Returns: (str): Decrypted data
625941c6e76e3b2f99f3a836
def _configure_learning_rate(num_samples_per_epoch, global_step): <NEW_LINE> <INDENT> decay_steps = int(num_samples_per_epoch * FLAGS.num_epochs_per_decay / FLAGS.batch_size) <NEW_LINE> if FLAGS.sync_replicas: <NEW_LINE> <INDENT> decay_steps /= FLAGS.replicas_to_aggregate <NEW_LINE> <DEDENT> if FLAGS.learning_rate_deca...
Configures the learning rate. Args: num_samples_per_epoch: The number of samples in each epoch of training. global_step: The global_step tensor. Returns: A `Tensor` representing the learning rate. Raises: ValueError: if
625941c60a366e3fb873e842
def _collect_pp_hooks(self, descriptor): <NEW_LINE> <INDENT> pp_graph_hooks = set() <NEW_LINE> pp_node_hooks = set() <NEW_LINE> for feat in descriptor: <NEW_LINE> <INDENT> pp_graph_hooks.update(feat.pp_graph_hooks) <NEW_LINE> pp_node_hooks.update(feat.pp_node_hooks) <NEW_LINE> <DEDENT> return pp_graph_hooks, pp_node_ho...
collect all preprocessing hooks
625941c610dbd63aa1bd2bcd
def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> out = self.modules["linear1"].forward(X) <NEW_LINE> out = self.modules["relu1"].forward(out) <NEW_LINE> scores = self.modules["linear2"].forward(out) <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, dout = self.m...
Compute loss and gradient for a minibatch of data. Args: - X: Array of input data of shape (N, C), where N is batch size and C is input_dim. - y: Array of labels of shape (N,). y[i] gives the label for X[i]. Return: - loss: Loss for a current minibatch of data.
625941c656ac1b37e62641fb
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, TransactionsResponseMeta): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c6c4546d3d9de72a5c
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
625941c6e1aae11d1e749cdf
def moveZeroes(self, nums: List[int]) -> None: <NEW_LINE> <INDENT> lastfound = 0 <NEW_LINE> for current in range(len(nums)): <NEW_LINE> <INDENT> if nums[current] != 0 : <NEW_LINE> <INDENT> nums[lastfound],nums[current] = nums[current],nums[lastfound] <NEW_LINE> lastfound+=1
Do not return anything, modify nums in-place instead.
625941c6a4f1c619b28b0065
def step(self, new_state, reward, terminal, action_list, test=False): <NEW_LINE> <INDENT> assert len(action_list) > 0, "action_list has to have at least one action" <NEW_LINE> new_state_ = self._encode_state(new_state) <NEW_LINE> if not test: <NEW_LINE> <INDENT> self._add_new_state_action_if_unknown(new_state_, action_...
Take a sigle step of the agent :param new_state: state observed by agent :param float reward: reward as a result of (state, action, new_state) triple :param bool terminal: Terminal flag :param list action_list: action set at new_state A(s) as a list of strings :param bool test: :return:
625941c63cc13d1c6d3c73a4
def __init__(self, shape, xlim, ycenter): <NEW_LINE> <INDENT> self.xmin = 0. <NEW_LINE> self.xmax = 0. <NEW_LINE> self.set_shape(shape) <NEW_LINE> self.set_xlim(xlim) <NEW_LINE> self.set_ycenter(ycenter) <NEW_LINE> self.components = []
.. todo:: WRITEME
625941c62c8b7c6e89b357ea
def authorize(name=None, source_group_name=None, source_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None, group_id=None, source_group_group_id=None, region=None, key=None, keyid=None, profile=None, vpc_id=None, vpc_name=None, egress=False): <NEW_LINE> <INDENT> conn = _get_conn(region=re...
Add a new rule to an existing security group. CLI example:: salt myminion boto_secgroup.authorize mysecgroup ip_protocol=tcp from_port=80 to_port=80 cidr_ip='['10.0.0.0/8', '192.168.0.0/24']'
625941c6c432627299f04c6e
def hr_to_triggers(hr, first, last): <NEW_LINE> <INDENT> rr = 1 / hr * 60 * 1000 <NEW_LINE> num_beats = math.ceil((last - first) / rr) + 1 <NEW_LINE> triggers = np.arange(num_beats) * rr + first <NEW_LINE> return triggers
Calculates trigger times based on a constant heart rate. Args: hr (float): A constant heart rate (bpm). first (float): Time stamp of first k-space line (in ms). last (float): Time stamp of last k-space line (in ms). Returns: triggers (array): 1D array containing simulated cardiac trigger times.
625941c660cbc95b062c656c
def preprocess_LCG(formula, LCG, num_vars): <NEW_LINE> <INDENT> for cn in range(len(formula)): <NEW_LINE> <INDENT> for var in formula[cn]: <NEW_LINE> <INDENT> if var > 0: <NEW_LINE> <INDENT> LCG.add_edge(var, cn + 2 * num_vars + 1) <NEW_LINE> <DEDENT> elif var < 0: <NEW_LINE> <INDENT> LCG.add_edge(abs(var) + num_vars, ...
Builds LCG
625941c650812a4eaa59c34c
def Clone(self): <NEW_LINE> <INDENT> pass
Clone(self: DataGridViewColumn) -> object Returns: An System.Object that represents the cloned System.Windows.Forms.DataGridViewBand.
625941c6fb3f5b602dac36bb
def update_lr_ind(opt, lr): <NEW_LINE> <INDENT> for param_group in opt.param_groups: <NEW_LINE> <INDENT> param_group['lr'] = lr
Decay learning rates of the generator and discriminator.
625941c623e79379d52ee58e
def subdMatchTopology(*args, **kwargs): <NEW_LINE> <INDENT> pass
Command matches topology across multiple subdiv surfaces - at all levels. Flags: - frontOfChain : foc (bool) [create] This command is used to specify that the new addTopology node should be placed ahead (upstream) of existing deformer and skin nodes in the shape's history (but not ah...
625941c65fcc89381b1e16e7
def read(self, timeout=None) -> Message: <NEW_LINE> <INDENT> if self.m2_used: <NEW_LINE> <INDENT> response = "" <NEW_LINE> start_reading = False <NEW_LINE> char = '' <NEW_LINE> self._m2.timeout = timeout <NEW_LINE> while True: <NEW_LINE> <INDENT> if not self._acknowledged_flush: <NEW_LINE> <INDENT> response = "" <NEW_L...
Reads one message from device, creates python-can Message, and returns it If optional timeout occurs, return None
625941c66fece00bbac2d766
def load(self, istream, **kwargs): <NEW_LINE> <INDENT> encoding = kwargs.pop('encoding', 'utf-8') <NEW_LINE> expression = istream.read().decode(encoding) <NEW_LINE> return self.loads(expression, **kwargs)
Deserializes a haiku expression from an input stream in “Simple Expression” notation to Python objects.
625941c6cc0a2c11143dceba
def _delete(self, thing): <NEW_LINE> <INDENT> self._db.execute( 'DELETE FROM potential_subreddits WHERE subreddit_name = ?', (thing.subreddit.display_name,), )
Removes the thing's subreddit from the database
625941c676d4e153a657eb5a
def test_IntegerPosStep(self): <NEW_LINE> <INDENT> ir = infrange() <NEW_LINE> for i in range(0, 10): <NEW_LINE> <INDENT> self.assertEqual(i, next(ir))
Range of positive integers from 0-9
625941c6de87d2750b85fdbb
def _ND(omega, delta): <NEW_LINE> <INDENT> return ne.evaluate( "((omega*(omega+2.0))/(2.0*(omega+1.0)**2.0)) * (1.0 + (sqrt(2*omega)*(omega+3.0)*arctan(sqrt(2.0/omega)))/(4.0*(omega+1.0)) + (delta*sqrt(2.0*omega)*(omega-1.0)*(omega+2.0)*log((1.0+delta*sqrt(2.0*omega))/(1.0-delta*sqrt(2.0*omega))) ) / (8.0*(omega+1.0)) ...
See page 210
625941c60fa83653e4656fe5
def as_training_data(self): <NEW_LINE> <INDENT> raise NotImplementedError
Convert this ``IndexedInstance`` to NumPy arrays suitable for use as training data to models. Returns ------- train_data : (inputs, label) The ``IndexedInstance`` as NumPy arrays to be used in the model. Note that ``inputs`` might itself be a complex tuple, depending on the ``Instance`` type.
625941c6ac7a0e7691ed40f8
def main(): <NEW_LINE> <INDENT> parser = get_parser() <NEW_LINE> args = parser.parse_args() <NEW_LINE> with open(args.inf, 'r') if args.inf else sys.stdin as inf: <NEW_LINE> <INDENT> reader = csv.DictReader(filter(lambda row: row[0] != '#', inf), delimiter='\t') <NEW_LINE> line = 0 <NEW_LINE> for in_row in reader: <NEW...
Validate BEDPE format.
625941c629b78933be1e56d7
def trans(ttable, s): <NEW_LINE> <INDENT> translation = "" <NEW_LINE> for c in s: <NEW_LINE> <INDENT> translation += ttable.get(c, c) <NEW_LINE> <DEDENT> return translation
Return Translation of string s using translation table ttable
625941c67c178a314d6ef487
def inverse_target_map(data, cls=Token): <NEW_LINE> <INDENT> dataitems = data.find(instance_of=cls) <NEW_LINE> if len(dataitems) == 0: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> inverse_map = {} <NEW_LINE> for k, v in dataitems[0].target_map.items(): <NEW_LINE> <INDENT> inverse_map[int(as_scalar(v))] = k <NEW_LI...
Return mapping from index to tag string.
625941c6d10714528d5ffd0b
def draw_rectangle_rounded(center_x, center_y, width, height, radius, color): <NEW_LINE> <INDENT> shape_list = arcade.ShapeElementList() <NEW_LINE> shape_list.append(arcade.create_rectangle_filled(center_x, center_y, width, height - radius*2, color)) <NEW_LINE> shape_list.append(arcade.create_rectangle_filled(center_x,...
Custom function to draw a rounded rectangle
625941c685dfad0860c3ae84
def cliCmd(self,cmd,log = True): <NEW_LINE> <INDENT> cmd = 'echo "%s" | /opt/tms/bin/cli -m config' % cmd <NEW_LINE> return self.runCmd(cmd,log)
To run cli command
625941c6e64d504609d74869
def _import_batch_file(self, sg_publish_data): <NEW_LINE> <INDENT> app = self.parent <NEW_LINE> app.log_debug("Importing batch file using '%s'" % sg_publish_data) <NEW_LINE> setup_path = self.get_publish_path(sg_publish_data) <NEW_LINE> if setup_path and os.path.exists(setup_path): <NEW_LINE> <INDENT> flame.batch.go_to...
Imports a Batch setup into Flame. This function import the Batch setup into the current Batch Group. :param dict sg_publish_data: Shotgun data dictionary with all the standard publish fields.
625941c607f4c71912b114ab
def _resolve_mapping_column(self, p_column): <NEW_LINE> <INDENT> if p_column in self.m_cache: <NEW_LINE> <INDENT> return self.m_cache[p_column] <NEW_LINE> <DEDENT> samples = self.mapping.get_samples() <NEW_LINE> column_count = {} <NEW_LINE> for sample in samples: <NEW_LINE> <INDENT> if sample[p_column] in column_count:...
Help ``_resolve_column``
625941c67047854f462a1435
def _start_threads(self): <NEW_LINE> <INDENT> for i in range(self._thread_count): <NEW_LINE> <INDENT> if self._thread_items is None: <NEW_LINE> <INDENT> args = () <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args = (self._thread_items[i],) <NEW_LINE> <DEDENT> self._threads.append(threading.Thread(target=self.download_...
Distribute items to threads as equally as possible, then start threads.
625941c61f037a2d8b946228
def radial_sort(points, origin, normal): <NEW_LINE> <INDENT> axis0 = [normal[0], normal[2], -normal[1]] <NEW_LINE> axis1 = np.cross(normal, axis0) <NEW_LINE> ptVec = points - origin <NEW_LINE> pr0 = np.dot(ptVec, axis0) <NEW_LINE> pr1 = np.dot(ptVec, axis1) <NEW_LINE> angles = np.arctan2(pr0, pr1) <NEW_LINE> return poi...
Sorts a set of points radially (by angle) around an an axis specified by origin and normal vector. Parameters -------------- points : (n, 3) float Points in space origin : (3,) float Origin to sort around normal : (3,) float Vector to sort around Returns -------------- ordered : (n, 3) float Same as input p...
625941c6eab8aa0e5d26db81
def parseError(error): <NEW_LINE> <INDENT> errorCondition = True <NEW_LINE> errorMsg = error <NEW_LINE> if 'ERROR: proxy has expired\n' in error: <NEW_LINE> <INDENT> errorCondition = True <NEW_LINE> errorMsg = 'CRITICAL ERROR: Your proxy has expired!\n' <NEW_LINE> <DEDENT> elif '999100\n' in error: <NEW_LINE> <IN...
Do some basic condor error parsing
625941c626068e7796caed06
def load_files(self, directory: str, file_suffix: str) -> namedtuple: <NEW_LINE> <INDENT> self._directory = directory <NEW_LINE> self._file_suffix = file_suffix <NEW_LINE> self.file_names = self._get_file_names() <NEW_LINE> self._file_tuple = self._create_file_tuple() <NEW_LINE> self.loaded_files = self._file_tuple(*se...
"Reads all files within directory and returns a namedtuple containing files read
625941c68e05c05ec3eea39d
def test_executes_interactor(self): <NEW_LINE> <INDENT> self.__target.get_page(self.__params) <NEW_LINE> self.__interactor.execute.assert_called_with(Genre.from_dict(self.__params))
Test that AddGenreHandler.get_page executes AddGenreInteractor.execute
625941c65fc7496912cc39a8
def build_constructor(): <NEW_LINE> <INDENT> construct = CONSTRUCT_IN.render( build_channel=CONDA_OUT.as_uri(), py_min=PY_MIN, py_max=PY_MAX, node_min=NODE_MIN, node_max=NODE_MAX, rf_version=RF_VERSION, version=VERSION, cd_version=CHROMEDRIVER_VERSION, ipyw_version=IPYWIDGETS_VERSION, ) <NEW_LINE> CONSTRUCT.write_text(...
Use the local build artifacts in constructor Care should be taken to avoid `noarch: python` packages
625941c6dd821e528d63b1d4
def cross_entropy_loss(logits, labels, label_smoothing=0.0, mode=tf.estimator.ModeKeys.TRAIN): <NEW_LINE> <INDENT> cross_entropy = _softmax_cross_entropy(logits, labels, label_smoothing, mode) <NEW_LINE> loss = tf.reduce_sum(cross_entropy) <NEW_LINE> loss_normalizer = tf.cast(tf.shape(cross_entropy)[0], loss.dtype) <NE...
Computes the cross entropy loss. Args: logits: The unscaled probabilities. labels: The true labels. label_smoothing: The label smoothing value. mode: A ``tf.estimator.ModeKeys`` mode. Returns: The cumulated loss and the loss normalizer.
625941c6d7e4931a7ee9df47
def sample(self, bqm, chain_strength=1.0, force_embed=False, chain_break_fraction=True, **parameters): <NEW_LINE> <INDENT> embedding_parameters = self._embedding_parameters <NEW_LINE> candidates_parameters = self._candidates_parameters <NEW_LINE> child = self.child <NEW_LINE> __, target_edgelist, target_adjacency = chi...
Sample from the provided binary quadratic model. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. chain_strength (float, optional, default=1.0): Magnitude of the quadratic bias (in SPIN-space) applied between variables to create chains. Note tha...
625941c6656771135c3eb897
def _load_geometry(self): <NEW_LINE> <INDENT> self.template = getattr(neuron.h, self.templatename)(self.templateargs) <NEW_LINE> seccount = 0 <NEW_LINE> for sec in self.template.all: <NEW_LINE> <INDENT> seccount += 1 <NEW_LINE> <DEDENT> if seccount == 0: <NEW_LINE> <INDENT> fileEnding = self.morphology.split('.')[-1] <...
Load the morphology-file in NEURON
625941c60a50d4780f666ebb
def get_absolute_url(self, link='detail'): <NEW_LINE> <INDENT> if link == 'detail': <NEW_LINE> <INDENT> url = reverse('user_view', args=[str(self.pk)]) <NEW_LINE> <DEDENT> elif link == 'update': <NEW_LINE> <INDENT> url = reverse('user_edit', args=[str(self.pk)]) <NEW_LINE> <DEDENT> elif link == 'delete': <NEW_LINE> <IN...
Return the URL to the user.
625941c626238365f5f0ee97
def _run_once_naive_(self): <NEW_LINE> <INDENT> box_list = np.zeros(12) <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> index = random.randint(0, 11) <NEW_LINE> box_list[index] += 1 <NEW_LINE> <DEDENT> count = 0 <NEW_LINE> for box in box_list: <NEW_LINE> <INDENT> if box == 0: <NEW_LINE> <INDENT> count += 1 <NEW_LINE...
Return 0 for False, return 1 for True
625941c6d99f1b3c44c675ba
def count_steps(input_str): <NEW_LINE> <INDENT> counter = Counter(input_str) <NEW_LINE> return counter['('] - counter[')']
Count steps up/down ( '(' / ')' )
625941c6c432627299f04c6f
@autojit_py3doc <NEW_LINE> def test_bitwise_and(a, b): <NEW_LINE> <INDENT> return a & b
>>> test_bitwise_and(0b01, 0b10) 0 >>> test_bitwise_and(0b01, 0b11) 1 >>> test_bitwise_and(0b01, 2.0) Traceback (most recent call last): ... NumbaError: 27:15: Expected an int, or object, or bool >>> test_bitwise_and(2.0, 0b01) Traceback (most recent call last): ... NumbaError: 27:11: Expected an int, or obje...
625941c632920d7e50b281f9
def test_mini_missing_attributes(self, mock_resp): <NEW_LINE> <INDENT> camera = BlinkCameraMini(self.blink.sync) <NEW_LINE> self.blink.sync.network_id = None <NEW_LINE> self.blink.sync.name = None <NEW_LINE> attr = camera.attributes <NEW_LINE> for key in attr: <NEW_LINE> <INDENT> self.assertEqual(attr[key], None)
Test that attributes return None if missing.
625941c629b78933be1e56d8
def search(index, doc_type, q_string): <NEW_LINE> <INDENT> multi_query = { 'query': { 'multi_match': { 'query': q_string, 'type': 'best_fields', 'analyzer': 'english_synonym', 'fields': ['name', 'description', 'tags'], 'fuzziness': 'AUTO' } } } <NEW_LINE> single_query = { 'query': { 'match': { 'description': { 'query':...
search index for matching query docs
625941c6be383301e01b54b2
def reverseString(self, s): <NEW_LINE> <INDENT> j=len(s)-1 <NEW_LINE> for i in range(len(s)//2): <NEW_LINE> <INDENT> s[i],s[j] = s[j],s[i] <NEW_LINE> j-=1 <NEW_LINE> <DEDENT> return s
Do not return anything, modify s in-place instead.
625941c6a219f33f34628996
def set_token(self, token: Optional[str] = None) -> None: <NEW_LINE> <INDENT> self._requests.session.cookies[".ROBLOSECURITY"] = token
Authenticates the client with the passed .ROBLOSECURITY token. This method does not send any requests and will not throw if the token is invalid. Arguments: token: A .ROBLOSECURITY token to authenticate the client with.
625941c64f6381625f114a65
def is_active(self, key, *instances, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> switch = self[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if switch.status == GLOBAL: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif switch.status == DISABLED: <NEW_L...
Returns ``True`` if any of ``instances`` match an active switch. Otherwise returns ``False``. >>> gargoyle.is_active('my_feature', request) #doctest: +SKIP
625941c6283ffb24f3c5592c
def choose_word(wordlist): <NEW_LINE> <INDENT> return random.choice(wordlist)
Function to choose a random word from a wordlist.
625941c64f6381625f114a66
def run(self): <NEW_LINE> <INDENT> self.Edone = False <NEW_LINE> g4mp2_function = [ self.quick_optimize, self.optimize, self.E_zpe, self.prepare_scf_vectors, self.E_hf_g3lxp, self.E_hf1, self.E_hf2, self.reset_symmetry, self.E_mp2, self.E_ccsdt, self.E_mp2_g3lxp, self.E_cbs, self.E_hlc, self.spin_orbit_energy, self.E_g...
Calculate G4MP2 energy for a system that has already been prepared.
625941c68e71fb1e9831d7d4
def _get_piuparts_content(self, suite): <NEW_LINE> <INDENT> url = 'https://piuparts.debian.org/{suite}/sources.txt' <NEW_LINE> return get_resource_content(url.format(suite=suite))
:returns: The content of the piuparts report for the given package or ``None`` if there is no data for the particular suite.
625941c68da39b475bd64f9c
def roll_pitch_yaw_rates_thrust_setpoint_encode(self, time_boot_ms, roll_rate, pitch_rate, yaw_rate, thrust): <NEW_LINE> <INDENT> msg = MAVLink_roll_pitch_yaw_rates_thrust_setpoint_message(time_boot_ms, roll_rate, pitch_rate, yaw_rate, thrust) <NEW_LINE> msg.pack(self) <NEW_LINE> return msg
Setpoint in roll, pitch, yaw rates and thrust currently active on the system. time_boot_ms : Timestamp in milliseconds since system boot (uint32_t) roll_rate : Desired roll rate in radians per second (float) pitch_rate : Desired pitch rate in radians per second (float) yaw_r...
625941c6b57a9660fec338ad
def remove_target(tree, target_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> target = find_target(tree, target_id) <NEW_LINE> target.getparent().remove(target) <NEW_LINE> <DEDENT> except AclTargetNotFound: <NEW_LINE> <INDENT> raise LibraryError(reports.id_not_found(target_id, "user"))
Removes acl_target element from tree with specified id. Raises LibraryError if target with id target_id doesn't exist. tree -- etree node target_id -- id of target element to remove
625941c64428ac0f6e5ba81c
def __str__(self) -> str: <NEW_LINE> <INDENT> res = '' <NEW_LINE> for atom in self.atoms: <NEW_LINE> <INDENT> res = res + str(atom) + ', ' <NEW_LINE> <DEDENT> res = res[:-2] <NEW_LINE> return '({0}, ({1}))'.format(self.name, res)
Return a string representation of this Molecule in this format: (NAME, (ATOM1, ATOM2, ...))
625941c6ac7a0e7691ed40f9
def calculate_avg_score(res): <NEW_LINE> <INDENT> c_star_score = 6 <NEW_LINE> avg_score = 0.0 <NEW_LINE> nb_reviews = 0 <NEW_LINE> for comment in res: <NEW_LINE> <INDENT> if comment[c_star_score] > 0: <NEW_LINE> <INDENT> avg_score += comment[c_star_score] <NEW_LINE> nb_reviews += 1 <NEW_LINE> <DEDENT> <DEDENT> if nb_re...
private function Calculate the avg score of reviews present in res :param res: tuple of tuple returned from query_retrieve_comments_or_remarks :return: a float of the average score rounded to the closest 0.5
625941c67d43ff24873a2cca
def run_search_query( self , query_string , search_locs=None , results_fmt="excerpt" , adv_syntax=False , page_no=1 , page_size=10 ) : <NEW_LINE> <INDENT> api_args = { "query": query_string , "fidf": results_fmt , "advsyn": adv_syntax , "page": page_no , "pageSize": page_size , "format": "json" } <NEW_LINE> if search_l...
Run the specified search query.
625941c65f7d997b87174ac1
def start_node(i, dirname, extra_args=None, rpchost=None): <NEW_LINE> <INDENT> datadir = os.path.join(dirname, "node"+str(i)) <NEW_LINE> args = [ os.getenv("BITCOIND", "suprad"), "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ] <NEW_LINE> if extra_args is not None: args.extend(extra_args) <NEW_LINE> bitcoind...
Start a suprad and return RPC connection to it
625941c6fbf16365ca6f61ec
def choose_action(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.next_waypoint = self.planner.next_waypoint() <NEW_LINE> action = None <NEW_LINE> actions = [None, 'left', 'forward', 'right'] <NEW_LINE> random_action = random.choice(actions) <NEW_LINE> highest_Q = self.get_maxQ(state) <NEW_LINE> ac...
The choose_action function is called when the agent is asked to choose which action to take, based on the 'state' the smartcab is in.
625941c6004d5f362079a35e
def rrsa(myArray,bestval,val): <NEW_LINE> <INDENT> sacount = 0 <NEW_LINE> max_eval = 50 <NEW_LINE> totalval = 0 <NEW_LINE> while sacount < max_eval: <NEW_LINE> <INDENT> remaining_eval = max_eval - sacount <NEW_LINE> sa(myArray) <NEW_LINE> if val > bestval or bestval is None: <NEW_LINE> <INDENT> val = bestval <NEW_LINE>...
Repeatedly calls hillclimb for 50 times :return: max and avg of values
625941c63eb6a72ae02ec504
def addBinary(self, a, b): <NEW_LINE> <INDENT> n1 = len(a)-1 <NEW_LINE> n2 = len(b)-1 <NEW_LINE> carry = 0 <NEW_LINE> ret = "" <NEW_LINE> while n1>=0 or n2>=0: <NEW_LINE> <INDENT> left = int(a[n1]) if n1>=0 else 0 <NEW_LINE> right = int(b[n2]) if n2>=0 else 0 <NEW_LINE> if left!= right: <NEW_LINE> <INDENT> if carry == ...
:type a: str :type b: str :rtype: str
625941c64d74a7450ccd41ee
def menu(fenetre): <NEW_LINE> <INDENT> top=Menu(fenetre) <NEW_LINE> fenetre.config(menu=top) <NEW_LINE> J=Menu(top) <NEW_LINE> top.add_cascade(label='Jeu',menu=J,underline=0) <NEW_LINE> J.add_command(label='Nouvelle partie',command=jouer,underline=0) <NEW_LINE> J.add_command(label='Essai',command=nouvelessai,underline=...
Barre de menu
625941c6287bf620b61d3a8f
def split_letters(image, num_letters=4, debug=False): <NEW_LINE> <INDENT> binary = prep_img(image) <NEW_LINE> contours = find_contours(binary, 0.5) <NEW_LINE> contours = [[ [int(floor(min(contour[:, 1]))), 0], [int(ceil(max(contour[:, 1]))), 30] ] for contour in contours] <NEW_LINE> contours = sorted(contours, key=lamb...
split full captcha image into `num_letters` lettersself. return list of letters binary image (0: white, 255: black)
625941c65fdd1c0f98dc025d
def test_all_options_links_no_pks(self): <NEW_LINE> <INDENT> class Fake(ResourceBase): <NEW_LINE> <INDENT> @apimethod(no_pks=True) <NEW_LINE> def fake(cls, request): <NEW_LINE> <INDENT> return cls() <NEW_LINE> <DEDENT> <DEDENT> class MyResource(AllOptionsResource): <NEW_LINE> <INDENT> linked_resource_classes = (Fake,) ...
Tests getting the links for a class with only no_pks apimethods
625941c630dc7b7665901992
def create_windows(x, y, window_size, overlap=True): <NEW_LINE> <INDENT> windows_x = [] <NEW_LINE> windows_y = [] <NEW_LINE> i = 0 <NEW_LINE> while i < len(y)-window_size: <NEW_LINE> <INDENT> window_x = np.expand_dims(np.concatenate(x[i:i+window_size], axis=0), axis=0) <NEW_LINE> window_y = y[i+window_size-1] <NEW_LINE...
Concatenate along dim-1 to meet the desired window_size. We'll skip any windows that reach beyond the end. Two options (examples for window_size=5): Overlap - e.g. window 0 will be a list of examples 0,1,2,3,4 and the label of example 4; and window 1 will be 1,2,3,4,5 and the label of example 5 ...
625941c69f2886367277a8b9