code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
def logout(self): <NEW_LINE> <INDENT> self.api.logout() | Logout from FortiManager. | 625941b816aa5153ce3622c0 |
def has_medside_castling_rights(self, color): <NEW_LINE> <INDENT> backrank = BB_RANK_1 if color == WHITE else BB_RANK_8 <NEW_LINE> king_mask = self.kings & self.occupied_co[color] & backrank & ~self.promoted <NEW_LINE> if not king_mask: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> castling_rights = self.clean_castling_rights() & backrank <NEW_LINE> while castling_rights: <NEW_LINE> <INDENT> rook = castling_rights & -castling_rights <NEW_LINE> if rook < king_mask: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> castling_rights = castling_rights & (castling_rights - 1) <NEW_LINE> <DEDENT> return False | Checks if the given side has medside (that is a-side in Chess960)
castling rights. | 625941b8be8e80087fb20a98 |
def serve(self): <NEW_LINE> <INDENT> with selectors.DefaultSelector() as sel, self.server_socket as sock: <NEW_LINE> <INDENT> print(sel) <NEW_LINE> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> sock.bind(self.server_address) <NEW_LINE> sock.listen(20) <NEW_LINE> print(sock) <NEW_LINE> sel.register(sock, selectors.EVENT_READ) <NEW_LINE> while True: <NEW_LINE> <INDENT> events = sel.select(timeout=1.0) <NEW_LINE> if events: <NEW_LINE> <INDENT> self._handle_request() | Run server loop | 625941b826238365f5f0ecb2 |
def copy_all_a(input_a, *other_inputs, **kwargs): <NEW_LINE> <INDENT> output = [] <NEW_LINE> while input_a.count() > 0: <NEW_LINE> <INDENT> output.append(input_a.pop()) <NEW_LINE> <DEDENT> for input_x in other_inputs: <NEW_LINE> <INDENT> input_x.skip_all() <NEW_LINE> <DEDENT> return output | Copy all readings in input a into the output.
All other inputs are skipped so that after this function runs there are no
readings left in any of the input walkers when the function finishes, even
if it generated no output readings.
Returns:
list(IOTileReading) | 625941b83346ee7daa2b2bb2 |
def test_correct_assets_passing_tag_string(self): <NEW_LINE> <INDENT> recordings = get_recordings(self.session1.id, str(self.tag1.id)) <NEW_LINE> self.assertEqual([self.asset1, self.asset3], recordings) <NEW_LINE> tag_string = str(self.tag1.id) + "," + str(self.tag2.id) <NEW_LINE> recordings = get_recordings(self.session1.id, tag_string) <NEW_LINE> self.assertEqual([self.asset3], recordings) | Pass tag lists and check for correct assets
| 625941b830bbd722463cbc0b |
def list(self, request): <NEW_LINE> <INDENT> api_keys = ['44GNCB5WPC55EERS', '1UOV5PHVK5K49QYS', '4V7E9U7J09JFR0SB', '7H32FTP7OP61FATO', '7RE7REQLUXM0RAH1', '9RN7A9SVJOY6OSJZ', 'FYOFKJO0ED94X9WB', 'PGSQR6KMR0V0YQDF', '44GNCB5WPC55EERS', '1UOV5PHVK5K49QYS', '4V7E9U7J09JFR0SB', '7H32FTP7OP61FATO', '7RE7REQLUXM0RAH1', '9RN7A9SVJOY6OSJZ', 'FYOFKJO0ED94X9WB', 'PGSQR6KMR0V0YQDF', ] <NEW_LINE> instances = [] <NEW_LINE> request_counter = 0 <NEW_LINE> for api_key in api_keys: <NEW_LINE> <INDENT> stocks = Stocks.objects.all() <NEW_LINE> for stock in stocks: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print(stock.symbol, api_key) <NEW_LINE> ts = TimeSeries(key=api_key, output_format='json') <NEW_LINE> data_ts, meta_data_ts = ts.get_weekly_adjusted(symbol=stock.symbol) <NEW_LINE> dict_items = data_ts.items() <NEW_LINE> sorted_items = sorted(dict_items) <NEW_LINE> for key, value in sorted_items: <NEW_LINE> <INDENT> open_price = value.get('1. open') <NEW_LINE> high_price = value.get('2. high') <NEW_LINE> low_price = value.get('3. low') <NEW_LINE> close_price = value.get('4. close') <NEW_LINE> adj_close_price = value.get('5. adjusted close') <NEW_LINE> volume = value.get('6. volume') <NEW_LINE> if not StocksPrices.objects.filter(stock=stock, date_time=key, open=open_price, high=high_price, low=low_price, close=close_price, adj_close=adj_close_price, volume=volume).exists(): <NEW_LINE> <INDENT> instances.append(StocksPrices(stock=stock, date_time=key, open=open_price, high=high_price, low=low_price, close=close_price, adj_close=adj_close_price, volume=volume)) <NEW_LINE> <DEDENT> <DEDENT> request_counter += 1 <NEW_LINE> if request_counter % 5 == 0: <NEW_LINE> <INDENT> print('Waiting 60 seconds') <NEW_LINE> if len(instances) > 0: <NEW_LINE> <INDENT> StocksPrices.objects.bulk_create(instances) <NEW_LINE> <DEDENT> instances = [] <NEW_LINE> time.sleep(60) <NEW_LINE> <DEDENT> <DEDENT> except ValueError as err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> <DEDENT> <DEDENT> break <NEW_LINE> <DEDENT> result = {'data': 'Results Processed go to --> '} <NEW_LINE> return Response(result) | Load History Prices Data From https://www.alphavantage.co/ and saving to Database
:param request:
:return: | 625941b86e29344779a6245e |
def user_registration_assert_in(self, query, expected_response): <NEW_LINE> <INDENT> response = self.app_test.post('/mt?query=' + query) <NEW_LINE> self.assertIn(expected_response, str(response.data)) | Login a user | 625941b866673b3332b91ee0 |
def quat_mult(p,q): <NEW_LINE> <INDENT> return np.array([p[3]*q[0] + q[3]*p[0] + p[1]*q[2] - p[2]*q[1], p[3]*q[1] + q[3]*p[1] + p[2]*q[0] - p[0]*q[2], p[3]*q[2] + q[3]*p[2] + p[0]*q[1] - p[1]*q[0], p[3]*q[3] - (p[0]*q[0] + p[1]*q[1] + p[2]*q[2])]) | Perform quaternion product p*q | 625941b83eb6a72ae02ec323 |
def load_template_content(self, template_content): <NEW_LINE> <INDENT> self.__template_content = template_content | Load template content.
:param template_content: template content. | 625941b8d7e4931a7ee9dd64 |
def get_svc_alias(): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> for d in AVAIL_SVR_DIRS: <NEW_LINE> <INDENT> for el in glob.glob(os.path.join(d, '*')): <NEW_LINE> <INDENT> if not os.path.islink(el): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> psvc = os.readlink(el) <NEW_LINE> if not os.path.isabs(psvc): <NEW_LINE> <INDENT> psvc = os.path.join(d, psvc) <NEW_LINE> <DEDENT> nsvc = os.path.basename(psvc) <NEW_LINE> if nsvc not in ret: <NEW_LINE> <INDENT> ret[nsvc] = [] <NEW_LINE> <DEDENT> ret[nsvc].append(el) <NEW_LINE> <DEDENT> <DEDENT> return ret | Returns the list of service's name that are aliased and their alias path(s) | 625941b85fc7496912cc37ce |
def place_order(self, price, qty, code, trd_side=TrdSide.NONE, order_type=OrderType.NORMAL, adjust_limit=0, trd_env=TrdEnv.REAL, acc_id=0): <NEW_LINE> <INDENT> ret, msg = self._check_trd_env(trd_env) <NEW_LINE> if ret != RET_OK: <NEW_LINE> <INDENT> return ret, msg <NEW_LINE> <DEDENT> ret, msg , acc_id = self._check_acc_id(trd_env, acc_id) <NEW_LINE> if ret != RET_OK: <NEW_LINE> <INDENT> return ret, msg <NEW_LINE> <DEDENT> ret, msg, stock_code = self._check_stock_code(code) <NEW_LINE> if ret != RET_OK: <NEW_LINE> <INDENT> return ret, msg <NEW_LINE> <DEDENT> query_processor = self._get_sync_query_processor( PlaceOrder.pack_req, PlaceOrder.unpack_rsp) <NEW_LINE> kargs = { 'trd_side': trd_side, 'order_type': order_type, 'price': float(price), 'qty': float(qty), 'code': str(stock_code), 'adjust_limit': float(adjust_limit), 'trd_mkt': self.__trd_mkt, 'trd_env': trd_env, 'acc_id': acc_id, 'conn_id': self.get_sync_conn_id() } <NEW_LINE> ret_code, msg, order_id = query_processor(**kargs) <NEW_LINE> if ret_code != RET_OK: <NEW_LINE> <INDENT> return RET_ERROR, msg <NEW_LINE> <DEDENT> order_item = {'trd_env': trd_env, 'order_id': order_id} <NEW_LINE> for x in range(3): <NEW_LINE> <INDENT> ret_code, ret_data = self._order_list_query_impl(order_id=order_id,status_filter_list=[], code="", start="", end="", trd_env=trd_env, acc_id=acc_id) <NEW_LINE> if ret_code == RET_OK and len(ret_data) > 0: <NEW_LINE> <INDENT> order_item = ret_data[0] <NEW_LINE> order_item['trd_env'] = trd_env <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> col_list = [ "code", "stock_name", "trd_side", "order_type", "order_status", "order_id", "qty", "price", "create_time", "updated_time", "dealt_qty", "dealt_avg_price", "last_err_msg" ] <NEW_LINE> order_list = [order_item] <NEW_LINE> order_table = pd.DataFrame(order_list, columns=col_list) <NEW_LINE> return RET_OK, order_table | place order
use set_handle(HKTradeOrderHandlerBase) to recv order push ! | 625941b8507cdc57c6306b1c |
def eng_string(x, format='%s', si=False): <NEW_LINE> <INDENT> sign = '' <NEW_LINE> x = float(x) <NEW_LINE> if x < 0: <NEW_LINE> <INDENT> x = -x <NEW_LINE> sign = '-' <NEW_LINE> <DEDENT> if x == 0.0: <NEW_LINE> <INDENT> exp = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> exp = int(math.floor(math.log10(x))) <NEW_LINE> <DEDENT> exp3 = exp - (exp % 3) <NEW_LINE> x3 = x / (10 ** exp3) <NEW_LINE> if si and exp3 >= -24 and exp3 <= 24 and exp3 != 0: <NEW_LINE> <INDENT> index_f = ( exp3 - (-24)) / 3 <NEW_LINE> index = int(index_f) <NEW_LINE> exp3_text = 'yzafpnum kMGTPEZY'[index] <NEW_LINE> <DEDENT> elif exp3 == 0: <NEW_LINE> <INDENT> exp3_text = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> exp3_text = 'e%s' % exp3 <NEW_LINE> <DEDENT> return ('%s'+format+'%s') % (sign, x3, exp3_text) | Returns float/int value <x> formatted in a simplified engineering format -
using an exponent that is a multiple of 3.
format: printf-style string used to format the value before the exponent.
si: if true, use SI suffix for exponent, e.g. k instead of e3, n instead of
e-9 etc.
E.g. with format='%.2f':
1.23e-08 => 12.30e-9
123 => 123.00
1230.0 => 1.23e3
-1230000.0 => -1.23e6
and with si=True:
1230.0 => 1.23k
-1230000.0 => -1.23M | 625941b8aad79263cf390884 |
@permission_required("core.manage_shop") <NEW_LINE> def set_orders_page(request): <NEW_LINE> <INDENT> order_id = request.GET.get("order-id", 1) <NEW_LINE> html = ( ("#orders-inline", orders_inline(request)), ("#orders-filters-inline", orders_filters_inline(request)), ) <NEW_LINE> result = json.dumps({ "html": html, }, cls=LazyEncoder) <NEW_LINE> return HttpResponse(result, mimetype='application/json') | Sets the page of selectable orders.
| 625941b89b70327d1c4e0c1c |
def _minmaxcoord(min_threshold, max_threshold, sp_res): <NEW_LINE> <INDENT> res = float(sp_res) <NEW_LINE> minval = int(math.ceil(min_threshold / res)) * res <NEW_LINE> maxval = int(math.floor(max_threshold / res)) * res <NEW_LINE> if minval != maxval: <NEW_LINE> <INDENT> if minval - (res / 2) < min_threshold: <NEW_LINE> <INDENT> minval += res / 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> minval -= res / 2 <NEW_LINE> <DEDENT> if maxval + (res / 2) > max_threshold: <NEW_LINE> <INDENT> maxval -= res / 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> maxval += res / 2 <NEW_LINE> <DEDENT> <DEDENT> return minval, maxval | Gets min and max coordinates of a specific grid.
Based on the frame of a global grid.
Parameters
----------
min_threshold : float
Minimum value of coordinate
max_threshold : float
Maximum value of coordinate
sp_res : float or int
Spatial resolution or the grid
Returns
-------
minval : float
Updated minimum coordinate
maxval : float
Updated maximum coordinate | 625941b8cdde0d52a9e52e77 |
def get_occupation_numbers(self, kpt=0, spin=0): <NEW_LINE> <INDENT> return np.ones(42) | Return occupation number array. | 625941b8b7558d58953c4d64 |
def Argument(self): <NEW_LINE> <INDENT> from .argument import Argument <NEW_LINE> return self.mount_as(Argument) | Mount the UnmountedType as Argument | 625941b83cc13d1c6d3c71cd |
def view_bag(request): <NEW_LINE> <INDENT> return render(request, 'bag/bag.html') | Renders bag contents page | 625941b830dc7b76659017b3 |
def load_class_by_string(class_path): <NEW_LINE> <INDENT> parts = class_path.split('.') <NEW_LINE> module_name = '.'.join(parts[:-1]) <NEW_LINE> class_name = parts[-1] <NEW_LINE> return load_class(module_name, class_name) | Load a class when given it's full name, including modules in python
dot notation
>>> load_class_by_string('vumi.workers.base.VumiWorker')
<class 'base.VumiWorker'>
>>> | 625941b8cdde0d52a9e52e78 |
def sample_transition_bootstrap(x_train_hist, u_train_hist, t=None, n=None, m=None, Nb=None, log_diagnostics=True): <NEW_LINE> <INDENT> if n is None: <NEW_LINE> <INDENT> n = x_train_hist.shape[1] <NEW_LINE> <DEDENT> if m is None: <NEW_LINE> <INDENT> m = u_train_hist.shape[1] <NEW_LINE> <DEDENT> if t is None: <NEW_LINE> <INDENT> t = u_train_hist.shape[0] <NEW_LINE> <DEDENT> Ahat_boot = np.zeros([Nb, n, n]) <NEW_LINE> Bhat_boot = np.zeros([Nb, n, m]) <NEW_LINE> tag_str_list = [] <NEW_LINE> for i in range(Nb): <NEW_LINE> <INDENT> idx = npr.randint(t, size=t) <NEW_LINE> while np.unique(idx).size < n+m: <NEW_LINE> <INDENT> if log_diagnostics: <NEW_LINE> <INDENT> tag_str_list.append(create_tag('Bootstrap drew a noninvertible sample, resampling.')) <NEW_LINE> <DEDENT> idx = npr.randint(t, size=t) <NEW_LINE> <DEDENT> Ahat_boot[i], Bhat_boot[i] = least_squares(x_train_hist, u_train_hist, t, idx=idx) <NEW_LINE> <DEDENT> Ahat_boot_reshaped = np.reshape(Ahat_boot, [Nb, n*n], order='F') <NEW_LINE> Bhat_boot_reshaped = np.reshape(Bhat_boot, [Nb, n*m], order='F') <NEW_LINE> Ahat_boot_mean_reshaped = np.mean(Ahat_boot_reshaped, axis=0) <NEW_LINE> Bhat_boot_mean_reshaped = np.mean(Bhat_boot_reshaped, axis=0) <NEW_LINE> Abar = Ahat_boot_reshaped - Ahat_boot_mean_reshaped <NEW_LINE> Bbar = Bhat_boot_reshaped - Bhat_boot_mean_reshaped <NEW_LINE> SigmaA = mdot(Abar.T, Abar)/(Nb-1) <NEW_LINE> SigmaB = mdot(Bbar.T, Bbar)/(Nb-1) <NEW_LINE> SigmaAeigvals, SigmaAeigvecs = la.eigh(SigmaA) <NEW_LINE> SigmaBeigvals, SigmaBeigvecs = la.eig(SigmaB) <NEW_LINE> alpha = SigmaAeigvals <NEW_LINE> beta = SigmaBeigvals <NEW_LINE> Aa = np.reshape(SigmaAeigvecs, [n*n, n, n], order='F') <NEW_LINE> Bb = np.reshape(SigmaBeigvecs, [n*m, n, m], order='F') <NEW_LINE> return alpha, Aa, beta, Bb, tag_str_list | Compute estimate of model uncertainty (covariance) via sample-transition bootstrap
:param t: Time up to which to use the available data.
:param Nb: Number of bootstrap samples | 625941b8d10714528d5ffb28 |
def _receive_node_owner(self, node_id, user_id): <NEW_LINE> <INDENT> print("MY node_owner(): ", "node_id: ", node_id, " ,user_id: ", user_id) <NEW_LINE> try: <NEW_LINE> <INDENT> node = self.nodes[node_id] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> node.user_id = user_id | Callback function for node owner | 625941b8baa26c4b54cb0f6c |
def get_free(self): <NEW_LINE> <INDENT> self.initialize() <NEW_LINE> vram = [pynvml.nvmlDeviceGetMemoryInfo(handle).free / (1024 * 1024) for handle in self.handles] <NEW_LINE> self.shutdown() <NEW_LINE> return vram | Return the vram available | 625941b857b8e32f524832e9 |
def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> oldFood = currentGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <NEW_LINE> newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] <NEW_LINE> return successorGameState.getScore() | The evaluation function takes in the current and proposed successor
GameStates (pacman.py) and returns a number, where higher numbers are better.
The code below extracts some useful information from the state, like the
remaining food (oldFood) and Pacman position after moving (newPos).
newScaredTimes holds the number of moves that each ghost will remain
scared because of Pacman having eaten a power pellet. | 625941b8bf627c535bc1301f |
def create_credential(macaddress, nonce, upload_key, from_eyefi=False): <NEW_LINE> <INDENT> if from_eyefi: <NEW_LINE> <INDENT> cred_binary = binascii.unhexlify(macaddress + upload_key + nonce) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cred_binary = binascii.unhexlify(macaddress + nonce + upload_key) <NEW_LINE> <DEDENT> cred_md5 = hashlib.md5() <NEW_LINE> cred_md5.update(cred_binary) <NEW_LINE> credential = cred_md5.hexdigest() <NEW_LINE> return credential | Returns an EyeFi credential.
Generates the credential used by the EyeFi for authentication purposes. The
credential is generated slightly differently based on if it is EyeFlask
authenticating the EyeFi or the other way around. | 625941b810dbd63aa1bd29f8 |
def login_as_user(self, username, password): <NEW_LINE> <INDENT> self._send_keys(username, Login.USERNAME_FIELD) <NEW_LINE> self._send_keys(password, Login.PASSWORD_FIELD) <NEW_LINE> self._click_to_element(Login.LOG_IN_BUTTON) <NEW_LINE> self._wait_for_loading(Dashboard.YT_LOGO) <NEW_LINE> return self | Log In to site as User or Admin | 625941b80a50d4780f666cd8 |
def get_download_url(self): <NEW_LINE> <INDENT> return reverse('snippets:bundle_download', kwargs={'pk': self.pk}) | Returns the download link to this bundle. | 625941b863d6d428bbe44338 |
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> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(FileTypeList, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result | Returns the model properties as a dict | 625941b850485f2cf553cbe2 |
def clearDups(Population, lb, ub): <NEW_LINE> <INDENT> newPopulation = numpy.unique(Population, axis=0) <NEW_LINE> oldLen = len(Population) <NEW_LINE> newLen = len(newPopulation) <NEW_LINE> if newLen < oldLen: <NEW_LINE> <INDENT> nDuplicates = oldLen - newLen <NEW_LINE> newPopulation = numpy.append(newPopulation, numpy.random.uniform(0,1,(nDuplicates,len(Population[0]))) * (numpy.array(ub) - numpy.array(lb)) + numpy.array(lb), axis=0) <NEW_LINE> <DEDENT> return newPopulation | It removes individuals duplicates and replace them with random ones
Parameters
----------
objf : function
The objective function selected
lb: list
lower bound limit list
ub: list
Upper bound limit list
Returns
-------
list
newPopulation: the updated list of individuals | 625941b8fff4ab517eb2f282 |
def update(self): <NEW_LINE> <INDENT> if not self.rect[0] <= 0: <NEW_LINE> <INDENT> self.rect[0] -= self.speed[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rect.topleft = self.respawn() | Move asteroids. | 625941b831939e2706e4ccb9 |
def log_saved_model(saved_model_dir, signature_def_key, artifact_path): <NEW_LINE> <INDENT> run_id = _get_or_start_run().info.run_uuid <NEW_LINE> mlflow_model = Model(artifact_path=artifact_path, run_id=run_id) <NEW_LINE> pyfunc.add_to_model(mlflow_model, loader_module="mlflow.tensorflow") <NEW_LINE> mlflow_model.add_flavor("tensorflow", saved_model_dir=saved_model_dir, signature_def_key=signature_def_key) <NEW_LINE> mlflow_model.save(os.path.join(saved_model_dir, "MLmodel")) <NEW_LINE> log_artifacts(saved_model_dir, artifact_path) | Log a TensorFlow model as an MLflow artifact for the current run.
:param saved_model_dir: Directory where the TensorFlow model is saved.
:param signature_def_key: The signature definition to use when loading the model again.
See `SignatureDefs in SavedModel for TensorFlow Serving
<https://www.tensorflow.org/serving/signature_defs>`_ for details.
:param artifact_path: Path (within the artifact directory for the current run) to which
artifacts of the model are saved. | 625941b824f1403a926009b3 |
def __init__(self, hosts=None, transport_class=Transport, **kwargs): <NEW_LINE> <INDENT> self.transport = transport_class(_normalize_hosts(hosts), **kwargs) <NEW_LINE> self.async_search = AsyncSearchClient(self) <NEW_LINE> self.autoscaling = AutoscalingClient(self) <NEW_LINE> self.cat = CatClient(self) <NEW_LINE> self.cluster = ClusterClient(self) <NEW_LINE> self.dangling_indices = DanglingIndicesClient(self) <NEW_LINE> self.indices = IndicesClient(self) <NEW_LINE> self.ingest = IngestClient(self) <NEW_LINE> self.nodes = NodesClient(self) <NEW_LINE> self.remote = RemoteClient(self) <NEW_LINE> self.snapshot = SnapshotClient(self) <NEW_LINE> self.tasks = TasksClient(self) <NEW_LINE> self.xpack = XPackClient(self) <NEW_LINE> self.ccr = CcrClient(self) <NEW_LINE> self.data_frame = Data_FrameClient(self) <NEW_LINE> self.deprecation = DeprecationClient(self) <NEW_LINE> self.enrich = EnrichClient(self) <NEW_LINE> self.eql = EqlClient(self) <NEW_LINE> self.graph = GraphClient(self) <NEW_LINE> self.ilm = IlmClient(self) <NEW_LINE> self.license = LicenseClient(self) <NEW_LINE> self.logstash = LogstashClient(self) <NEW_LINE> self.migration = MigrationClient(self) <NEW_LINE> self.ml = MlClient(self) <NEW_LINE> self.monitoring = MonitoringClient(self) <NEW_LINE> self.rollup = RollupClient(self) <NEW_LINE> self.searchable_snapshots = SearchableSnapshotsClient(self) <NEW_LINE> self.security = SecurityClient(self) <NEW_LINE> self.slm = SlmClient(self) <NEW_LINE> self.sql = SqlClient(self) <NEW_LINE> self.ssl = SslClient(self) <NEW_LINE> self.text_structure = TextStructureClient(self) <NEW_LINE> self.transform = TransformClient(self) <NEW_LINE> self.watcher = WatcherClient(self) | :arg hosts: list of nodes, or a single node, we should connect to.
Node should be a dictionary ({"host": "localhost", "port": 9200}),
the entire dictionary will be passed to the :class:`~elasticsearch.Connection`
class as kwargs, or a string in the format of ``host[:port]`` which will be
translated to a dictionary automatically. If no value is given the
:class:`~elasticsearch.Connection` class defaults will be used.
:arg transport_class: :class:`~elasticsearch.Transport` subclass to use.
:arg kwargs: any additional arguments will be passed on to the
:class:`~elasticsearch.Transport` class and, subsequently, to the
:class:`~elasticsearch.Connection` instances. | 625941b8d7e4931a7ee9dd65 |
def cusp_number_from_signature(signature, N): <NEW_LINE> <INDENT> v2,v3 = signature <NEW_LINE> v2 = ZZ(v2); v3 = ZZ(v3); N = ZZ(N) <NEW_LINE> if v3-v2 > 0: <NEW_LINE> <INDENT> return v3*N/(4*v3-v2) <NEW_LINE> <DEDENT> if v3-v2 < 0: <NEW_LINE> <INDENT> return (3*v2+v3)*N/(8*v2+4*v3) <NEW_LINE> <DEDENT> return N/3 | The cusp signature of a cusp on X_1(N) is a pair (v2,v3).
Where v2 is the valuation of F_2 and v3 the valuation of F_3 | 625941b826068e7796caeb21 |
def generateParenthesis(self, n): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> new_str = '('*n+')'*n <NEW_LINE> result = [new_str] <NEW_LINE> self.bt(new_str, result) <NEW_LINE> return result | :type n: int
:rtype: List[str] | 625941b863b5f9789fde6f2e |
def render(world): <NEW_LINE> <INDENT> pass | Consumes a world and produces a string that will describe the current state
of the world. Does not print.
Args:
world (World): The current world to describe.
Returns:
str: A textual description of the world. | 625941b8dc8b845886cb537e |
def train_start(self): <NEW_LINE> <INDENT> self.txt_enc.train() | switch to train mode
| 625941b8796e427e537b040b |
def test2_get_user_nickname(self): <NEW_LINE> <INDENT> resultado_exitoso = {"email": None , "hash_key": "85721956" , "key": "fedcf7af-e9f0-69cc-1c68-362d8f5164ea" , "link_image": "http://abs.twimg.com/sticky/" + "default_profile_images/default_profile_5_normal.png" , "name": "anroco" , "nickname": "anroco" , "registered": "2014-05-09 23:59:59" , "score_answers": 827377 , "score_win_answers": 2323 , "skills": ["python", "flask", "dynamodb"] , "total_post": 2983} <NEW_LINE> resultado = self.client.get(url_for('endpoints.nickname' , token_user=token_anonymous , nickname='no_existe')) <NEW_LINE> self.assertTrue(resultado.status_code == 404) <NEW_LINE> resultado = self.client.get(url_for('endpoints.nickname' , token_user=token_anonymous , nickname='anroco')) <NEW_LINE> json_data = json.loads(resultado.data.decode('utf-8')) <NEW_LINE> self.assertDictEqual(resultado_exitoso, json_data) <NEW_LINE> self.assertTrue(resultado.status_code == 200) | () -> NoneType
realiza pruebas al recurso (/api/1.0/user/<string:nickname> -> GET)
verifica:
* El usuario se encuentra registrado.
* El response sea el correcto retorna los datos del usuario y
status_code = 200 (Proceso exitoso) | 625941b8379a373c97cfa994 |
def test_jacobian_times_vectorfield_transpose(bs, dim, disp): <NEW_LINE> <INDENT> defsh = tuple([bs, dim] + [res] * dim) <NEW_LINE> g = torch.randn(defsh, dtype=torch.float64).cuda() <NEW_LINE> u = torch.randn_like(g) <NEW_LINE> v = torch.randn_like(g) <NEW_LINE> Dgu = lm.jacobian_times_vectorfield(g, u, displacement=disp, transpose=False) <NEW_LINE> Dguv = (Dgu * v).sum() <NEW_LINE> DgTv = lm.jacobian_times_vectorfield(g, v, displacement=disp, transpose=True) <NEW_LINE> uDgTv = (u * DgTv).sum() <NEW_LINE> assert torch.allclose(Dguv, uDgTv), "Failed jacobian_times_vectorfield_transpose" | Test that the transpose argument gives the adjoint of point-wise
multiplication | 625941b894891a1f4081b8f1 |
def createFrameMiddle(self): <NEW_LINE> <INDENT> self.frm_middle = tk.LabelFrame(self.root, font=('Tempus Sans ITC', 10)) <NEW_LINE> self.frm_middle.grid(row = 1, column = 0, padx = 15, pady = 2, sticky = "wesn") <NEW_LINE> self.createFrameMiddleLeft() <NEW_LINE> self.createFrameMiddleRight() | Create LabelFrame Middle | 625941b8adb09d7d5db6c5dc |
def sync_server_topology(): <NEW_LINE> <INDENT> admin_srv = admin.Server(context.GLOBAL.ldap.conn) <NEW_LINE> servers = admin_srv.list({'cell': context.GLOBAL.cell}) <NEW_LINE> zkclient = context.GLOBAL.zk.conn <NEW_LINE> def _server_pod_rack(servername): <NEW_LINE> <INDENT> svr_hash = hashlib.md5(servername.encode()).hexdigest() <NEW_LINE> svr_id = int(svr_hash, 16) <NEW_LINE> pod = (svr_id >> (128 - 2)) <NEW_LINE> rack = (svr_id % (1 << (128 - 2))) % 16 <NEW_LINE> return (pod, rack) <NEW_LINE> <DEDENT> for server in servers: <NEW_LINE> <INDENT> servername = server['_id'] <NEW_LINE> partition = server.get('partition') <NEW_LINE> (pod, rack) = _server_pod_rack(servername) <NEW_LINE> pod_bucket = 'pod:{:04X}'.format(pod) <NEW_LINE> rack_bucket = 'rack:{:04X}'.format(rack) <NEW_LINE> _LOGGER.info('Update: %r(partition:%r) -> %r, %r', servername, partition, pod_bucket, rack_bucket) <NEW_LINE> masterapi.create_bucket(zkclient, pod_bucket, parent_id=None) <NEW_LINE> masterapi.cell_insert_bucket(zkclient, pod_bucket) <NEW_LINE> masterapi.create_bucket(zkclient, rack_bucket, parent_id=pod_bucket) <NEW_LINE> masterapi.create_server( zkclient, servername, rack_bucket, partition=partition ) <NEW_LINE> <DEDENT> ldap_servers = set(server['_id'] for server in servers) <NEW_LINE> zk_servers = set(masterapi.list_servers(zkclient)) <NEW_LINE> zk_server_presence = set(zkclient.get_children(z.SERVER_PRESENCE)) <NEW_LINE> for servername in zk_servers - ldap_servers: <NEW_LINE> <INDENT> if servername in zk_server_presence: <NEW_LINE> <INDENT> _LOGGER.warning('%s not in LDAP but node still present, skipping.', servername) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _LOGGER.info('Delete: %s', servername) <NEW_LINE> masterapi.delete_server(zkclient, servername) | Sync servers into buckets in the masterapi.
| 625941b81f5feb6acb0c499e |
def _apply_functor(self, R): <NEW_LINE> <INDENT> from sage.rings.polynomial.laurent_polynomial_ring import LaurentPolynomialRing, is_LaurentPolynomialRing <NEW_LINE> if self.multi_variate and is_LaurentPolynomialRing(R): <NEW_LINE> <INDENT> return LaurentPolynomialRing(R.base_ring(), (list(R.variable_names()) + [self.var])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return LaurentPolynomialRing(R, self.var) | Apply the functor to an object of ``self``'s domain.
TESTS::
sage: from sage.categories.pushout import LaurentPolynomialFunctor
sage: F1 = LaurentPolynomialFunctor('t')
sage: F2 = LaurentPolynomialFunctor('s', multi_variate=True)
sage: F3 = LaurentPolynomialFunctor(['s','t'])
sage: F1(F2(QQ)) # indirect doctest
Univariate Laurent Polynomial Ring in t over Univariate Laurent Polynomial Ring in s over Rational Field
sage: F2(F1(QQ))
Multivariate Laurent Polynomial Ring in t, s over Rational Field
sage: F3(QQ)
Multivariate Laurent Polynomial Ring in s, t over Rational Field | 625941b8e64d504609d7468a |
def get_reset_token(self, expires_in=1800): <NEW_LINE> <INDENT> serializer = Serializer(current_app.config['SECRET_KEY'], expires_in) <NEW_LINE> return serializer.dumps({'user_id': self.id}).decode('utf-8') | It is going to return or reset a token
Parameters
----------
expires_in: int
Total of seconds that the token is going to last | 625941b88da39b475bd64dc0 |
def __init__(self, host, telnet_port = 23, ftp_port = 21): <NEW_LINE> <INDENT> self.telnet = telnetlib.Telnet(host, telnet_port) | Constructs a new RepRap object, connecting via Telnet and FTP to the given host, on the
default ports for the respective services, unless overridden. | 625941b8d6c5a10208143e90 |
def turquoiseDiamond(s): <NEW_LINE> <INDENT> pencolor("#00ccff") <NEW_LINE> forward(s) <NEW_LINE> right(150) <NEW_LINE> forward(s) <NEW_LINE> right(30) <NEW_LINE> forward(s) <NEW_LINE> right(150) <NEW_LINE> forward(s) | Draws a turquoise diamond. Args: Size of diamond, s=length of one side. | 625941b8be7bc26dc91cd44f |
def update_page( self, page_id, name, parent_id, locked, collection_ids, card_ids, user_ids, group_ids ): <NEW_LINE> <INDENT> body = self.create_page_object( name=name, parent_id=parent_id, locked=locked, card_ids=card_ids, user_ids=user_ids, group_ids=group_ids, ) <NEW_LINE> body["collectionIds"] = collection_ids <NEW_LINE> self.log.info(f"Updating {page_id} to {body}") <NEW_LINE> return self.call_api( endpoint=f"v1/pages/{page_id}", method="PUT", headers=self.send_json_header(), data=json.dumps(body, default=str), ) | Update the specified Page.
https://developer.domo.com/docs/page-api-reference/page#Update%20a%20page
:param page_id: The ID of the page being updated
:param name: Will update the name of the page
:param parentId: If provided, will either make the page a subpage or simply move the subpage
to become a child of a different parent page. Integer
:param locked: Will restrict access to edit page, Boolean
:param collectionIds: Collections cannot be added or removed but the order can be updated based
on the order of IDs provided in the argument
:param cardIds: IDs provided will add or remove cards that are not a part of a page collection. Integer
:param visibility: Shares pages with users or groups
:param userIds: IDs provided will share page with associated users. Integer
:param groupIds: IDs provided will share page with associated groups. Integer
:return: | 625941b899fddb7c1c9de1dc |
def search_bytes(self, value, begin=0, end=0xFFFFFFFF): <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> return self.search(value, "b", begin, end) <NEW_LINE> <DEDENT> print("Error: search_bytes called with non-string value.") <NEW_LINE> return "" | value should be a string "fe ed fa ce" | 625941b830c21e258bdfa2e6 |
def bubblesort(mylist): <NEW_LINE> <INDENT> limit=len(mylist)-1 <NEW_LINE> while limit>0: <NEW_LINE> <INDENT> swap_place(mylist,limit) <NEW_LINE> limit=limit-1 <NEW_LINE> <DEDENT> return mylist | Objective: To place the highest element at its right position
Input parameters:
mylist: The original list entered by user
Return value: modified list is returned | 625941b8097d151d1a222ca5 |
def enumRegKeySubkeys(self, key): <NEW_LINE> <INDENT> hkey, key = self._getHiveAndKey(key) <NEW_LINE> aReg = reg.ConnectRegistry(None, hkey) <NEW_LINE> aKey = reg.OpenKey(aReg, key) <NEW_LINE> result = [] <NEW_LINE> index = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subkey = reg.EnumKey(aKey, index) <NEW_LINE> result.append(subkey) <NEW_LINE> index += 1 <NEW_LINE> <DEDENT> except EnvironmentError: <NEW_LINE> <INDENT> return result | List all sub-keys of a specified key in the windows registry
@param key: The registry key to check. The key should include the section. Eg. "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion"
@type key: string | 625941b8796e427e537b040c |
def __str__( self ) -> str: <NEW_LINE> <INDENT> indent = 2 <NEW_LINE> result = "DCS online Bibles object" <NEW_LINE> if self.onlineVersion: result += ('\n' if result else '') + ' '*indent + _("Online version: {}").format( self.onlineVersion ) <NEW_LINE> if self.languageList: result += ('\n' if result else '') + ' '*indent + _("Languages: {}").format( len(self.languageList) ) <NEW_LINE> if self.versionList: result += ('\n' if result else '') + ' '*indent + _("Versions: {}").format( len(self.versionList) ) <NEW_LINE> if self.volumeList: result += ('\n' if result else '') + ' '*indent + _("Volumes: {}").format( len(self.volumeList) ) <NEW_LINE> if self.volumeNameDict: result += ('\n' if result else '') + ' '*indent + _("Displayable volumes: {}").format( len(self.volumeNameDict) ) <NEW_LINE> return result | Create a string representation of the DCSBibles object. | 625941b8eab8aa0e5d26d9a8 |
def sameOrign(self, url): <NEW_LINE> <INDENT> url_netloc = urlparse.urlparse(url).netloc <NEW_LINE> if self.netloc.find(url_netloc) > -1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | 判断同源 | 625941b821a7993f00bc7b33 |
def get_global_matches_by_class(self, clid, start, stop): <NEW_LINE> <INDENT> if self.global_matches is None: <NEW_LINE> <INDENT> return EMPTY <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> idx = (self.global_matches[:, 0] >= start) & (self.global_matches[:, 0] <= stop) & (self.global_matches[:, 1] == clid) <NEW_LINE> return self.global_matches[idx, :] | Returns index of globally matched spikes between
start and stop | 625941b8d18da76e2353231b |
def _get_restart_time(self): <NEW_LINE> <INDENT> return self.__restart_time | Getter method for restart_time, mapped from YANG variable /bgp/neighbors/neighbor/graceful_restart/config/restart_time (uint16)
YANG Description: Estimated time (in seconds) for the local BGP speaker to
restart a session. This value is advertise in the graceful
restart BGP capability. This is a 12-bit value, referred to
as Restart Time in RFC4724. Per RFC4724, the suggested
default value is <= the hold-time value.
| 625941b8b57a9660fec336c9 |
def init_app(app): <NEW_LINE> <INDENT> app.teardown_appcontext(close_db) <NEW_LINE> app.cli.add_command(init_db_command) | app.teardown_appcontext() 告诉 Flask 在返回响应后进行清理的时候调用此函数。
app.cli.add_command() 添加一个新的 可以与 flask 一起工作的命令。
在工厂中导入并调用这个函数。在工厂函数中把新的代码放到 函数的尾部,返回应用代码的前面。
:param app:
:return: | 625941b82c8b7c6e89b3560d |
def get_average_signature(self, nodes, bin_type, bin_n, remove=None): <NEW_LINE> <INDENT> avg_sgn = np.zeros(self.max_rank) <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> ss = self.signatures[node] <NEW_LINE> ss.update(bin_type, bin_n, avg=True) <NEW_LINE> avg_sgn += ss.average_signature <NEW_LINE> <DEDENT> avg_sgn /= len(nodes) <NEW_LINE> self.average_signature = avg_sgn | Compute signature given a list of nodes that adhere to certain condition (e.g. length > y) | 625941b876d4e153a657e97a |
def contains_sequence(dna1, dna2): <NEW_LINE> <INDENT> contains_sequence = False <NEW_LINE> if dna1.find(dna2) != -1: <NEW_LINE> <INDENT> contains_sequence = True <NEW_LINE> <DEDENT> return contains_sequence | (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False | 625941b8fb3f5b602dac34d8 |
@TASK <NEW_LINE> def capture_aml(): <NEW_LINE> <INDENT> global port_sensor, assembled_drop_it <NEW_LINE> update_results(error9999, error9999, error9999, False, "") <NEW_LINE> assembled_drop_it = True <NEW_LINE> being_tested = is_being_tested() <NEW_LINE> sensor_port_open() <NEW_LINE> initialize_additionals_table() <NEW_LINE> keep_looping = True <NEW_LINE> while keep_looping: <NEW_LINE> <INDENT> if being_tested: <NEW_LINE> <INDENT> one_byte = simulator_readchar() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> one_byte = port_sensor.readchar() <NEW_LINE> <DEDENT> if one_byte != -1: <NEW_LINE> <INDENT> assemble_data(one_byte) <NEW_LINE> <DEDENT> elif being_tested: <NEW_LINE> <INDENT> keep_looping = False <NEW_LINE> <DEDENT> if not being_tested: <NEW_LINE> <INDENT> if setup_read("Recording").upper() == "OFF": <NEW_LINE> <INDENT> keep_looping = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> sensor_port_close() | Captures data from the aml sensor.
Does not exit until the serial port is closed. | 625941b8cc0a2c11143dcce3 |
def translate_and_rotate(points): <NEW_LINE> <INDENT> n = int(len(points) / 3) <NEW_LINE> points = np.reshape(points, (n, 3)) <NEW_LINE> origin = points[0] <NEW_LINE> for i in range(1, n - 1): <NEW_LINE> <INDENT> points[i] = points[i] - origin <NEW_LINE> <DEDENT> points[0] = np.array([0, 0, 0]) <NEW_LINE> x = points[1][0] <NEW_LINE> z = points[1][2] <NEW_LINE> theta = np.arctan(x / z) <NEW_LINE> cos = np.cos(theta) <NEW_LINE> sin = np.sin(theta) <NEW_LINE> A = np.array([[cos, 0, -sin], [0, 1, 0], [sin, 0, cos]]) <NEW_LINE> for i in range(0, len(points)): <NEW_LINE> <INDENT> points[i] = np.dot(A, points[i]) <NEW_LINE> <DEDENT> if points[1][0] < .0005: <NEW_LINE> <INDENT> points[1][0] = 0. <NEW_LINE> <DEDENT> y = points[1][1] <NEW_LINE> z = points[1][2] <NEW_LINE> theta = np.arctan(y / z) <NEW_LINE> cos = np.cos(theta) <NEW_LINE> sin = np.sin(theta) <NEW_LINE> A = np.array([[1, 0, 0], [0, cos, -sin], [0, sin, cos]]) <NEW_LINE> for i in range(0, len(points)): <NEW_LINE> <INDENT> points[i] = np.dot(A, points[i]) <NEW_LINE> <DEDENT> if points[1][1] < .0005: <NEW_LINE> <INDENT> points[1][1] = 0. <NEW_LINE> <DEDENT> m, n = np.shape(points) <NEW_LINE> x = m * n <NEW_LINE> points = np.reshape(points, x) <NEW_LINE> return points | Translates and rotates a node configuration in order to ensure that the
first point is the origin, and that the second points is fixed on the z-axis.
:param points: single dimensional array representing a node configuration
:return: points - a translated and rotated node configuration that is in
line with Reality Check 13 | 625941b81b99ca400220a8fa |
def _csg_cap_lib(self, rev_cap_lib, _P): <NEW_LINE> <INDENT> return self.cast_from_entity_to_role(-rev_cap_lib * _P.csg.capital.glob, entity = 'foyer_fiscal', role = VOUS) | Calcule la CSG sur les revenus du capital soumis au prélèvement libératoire | 625941b8462c4b4f79d1d51a |
def set_global_state(st): <NEW_LINE> <INDENT> global _GlobalState <NEW_LINE> global _GlobalStateNotifyFunc <NEW_LINE> oldstate = _GlobalState <NEW_LINE> _GlobalState = st <NEW_LINE> if _GlobalStateNotifyFunc is not None and oldstate != _GlobalState: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _GlobalStateNotifyFunc(_GlobalState) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> lg.exc() | This method is called from State Machines when ``state`` is changed:
global_state.set_global_state('P2P ' + newstate) So ``st`` is a string
like: 'P2P CONNECTED'.
``_GlobalStateNotifyFunc`` can be used to keep track of changing
program states. | 625941b830c21e258bdfa2e7 |
def check_safe_from_pos(self, p_pos, p_range, p_is_x_axis, p_is_positive): <NEW_LINE> <INDENT> if p_is_positive: <NEW_LINE> <INDENT> coeff = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> coeff = -1 <NEW_LINE> <DEDENT> if p_is_x_axis: <NEW_LINE> <INDENT> for i in range(1, p_range): <NEW_LINE> <INDENT> new_x = p_pos[0] + coeff * i <NEW_LINE> if 0 <= new_x < width: <NEW_LINE> <INDENT> if self.area[p_pos[1],new_x] in [INT_EMPTY, INT_ITEM_EXTRA, INT_ITEM_RANGE]: <NEW_LINE> <INDENT> for j in [-1,1]: <NEW_LINE> <INDENT> new_y = p_pos[1] + j <NEW_LINE> if 0 <= new_y < height: <NEW_LINE> <INDENT> if self.area[new_y,new_x] in [INT_EMPTY, INT_ITEM_EXTRA, INT_ITEM_RANGE]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(1, p_range): <NEW_LINE> <INDENT> new_y = p_pos[1] + coeff * i <NEW_LINE> if 0 <= new_y < height: <NEW_LINE> <INDENT> if self.area[new_y,p_pos[0]] in [INT_EMPTY, INT_ITEM_EXTRA, INT_ITEM_RANGE]: <NEW_LINE> <INDENT> for j in [-1,1]: <NEW_LINE> <INDENT> new_x = p_pos[0] + j <NEW_LINE> if 0 <= new_x < width: <NEW_LINE> <INDENT> if self.area[new_y,new_x] in [INT_EMPTY, INT_ITEM_EXTRA, INT_ITEM_RANGE]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if p_is_x_axis: <NEW_LINE> <INDENT> new_x = p_pos[0] + (p_range + 1) * coeff <NEW_LINE> if 0 <= new_x < width and new_x != self.me[0]: <NEW_LINE> <INDENT> if self.area[p_pos[1],new_x] in [INT_EMPTY, INT_ITEM_EXTRA, INT_ITEM_RANGE]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> new_y = p_pos[1] + (p_range + 1) * coeff <NEW_LINE> if 0 <= new_y < height and new_y != self.me[1]: <NEW_LINE> <INDENT> if self.area[new_y,p_pos[0]] in [INT_EMPTY, INT_ITEM_EXTRA, INT_ITEM_RANGE]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False | Return True if there is a safe place from the position at the indicated range | 625941b871ff763f4b5494d8 |
def hexdump(self): <NEW_LINE> <INDENT> tokens = [] <NEW_LINE> def write(token, request_data=None): <NEW_LINE> <INDENT> tokens.append(util.hexlify(token) if not request_data else self.hexdump_request_data()) <NEW_LINE> <DEDENT> self._assemble(write) <NEW_LINE> return ' '.join(tokens) | Return a hexdump of the packet | 625941b8e5267d203edcdaeb |
def translate_js(js, HEADER=DEFAULT_HEADER): <NEW_LINE> <INDENT> parser = pyjsparser.PyJsParser() <NEW_LINE> parsed = parser.parse(js) <NEW_LINE> return HEADER + translating_nodes.trans(parsed) | js has to be a javascript source code.
returns equivalent python code. | 625941b87b25080760e392a4 |
def p_vap(mol="H2O", T=298.15, unit="Pa"): <NEW_LINE> <INDENT> dH = (dfH0[mol + "(g)"] - dfH0[mol + "(l)"]) * 1e3 <NEW_LINE> dS = S0[mol + "(g)"] - S0[mol + "(l)"] <NEW_LINE> if unit == "Pa": <NEW_LINE> <INDENT> p0 = 1e5 <NEW_LINE> <DEDENT> elif unit == "bar": <NEW_LINE> <INDENT> p0 = 1 <NEW_LINE> <DEDENT> elif unit == "mbar": <NEW_LINE> <INDENT> p0 = 1000 <NEW_LINE> <DEDENT> p = p0 * np.exp(-dH / (R * T) + dS / R) <NEW_LINE> return p | Returns the vapor pressure of a molecule at a given temperature, based on
data in dfH0 and S0 dictionaries. | 625941b8283ffb24f3c55756 |
def get_tick_prior(self, val): <NEW_LINE> <INDENT> dt = self._taxis.val_as_date(val, allfields=True) <NEW_LINE> d = dt.get('day', 1) <NEW_LINE> if val > self._taxis.date_as_val({'day':d}): d += 1 <NEW_LINE> from numpy import floor_divide <NEW_LINE> return {'day':floor_divide(d-1, self.mult) * self.mult} | get_tick_prior(val) - returns the year of the first tick prior to the
date represented by val. If a tick lies on val, it returns the index of the
previous tick. | 625941b8ac7a0e7691ed3f23 |
def __init__(self, address_string=None, capitalization_mode=None): <NEW_LINE> <INDENT> self._address_string = None <NEW_LINE> self._capitalization_mode = None <NEW_LINE> self.discriminator = None <NEW_LINE> if address_string is not None: <NEW_LINE> <INDENT> self.address_string = address_string <NEW_LINE> <DEDENT> if capitalization_mode is not None: <NEW_LINE> <INDENT> self.capitalization_mode = capitalization_mode | ParseAddressRequest - a model defined in Swagger | 625941b823e79379d52ee3b2 |
def bump_minor(self) -> "Version": <NEW_LINE> <INDENT> cls = type(self) <NEW_LINE> return cls(self._major, self._minor + 1) | Raise the minor part of the version, return a new object but leave self
untouched.
:return: new object with the raised minor part
>>> ver = semver.parse("3.4.5")
>>> ver.bump_minor()
Version(major=3, minor=5, patch=0, prerelease=None, build=None) | 625941b87b25080760e392a5 |
def __init__(self, account, benchmark_code='000300', benchmark_type=MARKET_TYPE.INDEX_CN, if_fq=True): <NEW_LINE> <INDENT> self.account = account <NEW_LINE> self.benchmark_code = benchmark_code <NEW_LINE> self.benchmark_type = benchmark_type <NEW_LINE> self.fetch = {MARKET_TYPE.STOCK_CN: QA_fetch_stock_day_adv, MARKET_TYPE.INDEX_CN: QA_fetch_index_day_adv} <NEW_LINE> self.market_data = QA_fetch_stock_day_adv( self.account.code, self.account.start_date, self.account.end_date) <NEW_LINE> self.if_fq = if_fq <NEW_LINE> self._assets = (self.market_value.sum( axis=1) + self.account.daily_cash.set_index('date').cash).fillna(method='pad') <NEW_LINE> self.time_gap = QA_util_get_trade_gap( self.account.start_date, self.account.end_date) <NEW_LINE> self.init_cash = self.account.init_cash <NEW_LINE> self.init_assets = self.account.init_assets | account: QA_Account类/QA_PortfolioView类
benchmark_code: [str]对照参数代码
benchmark_type: [QA.PARAM]对照参数的市场
if_fq: [Bool]原account是否使用复权数据
if_fq选项是@尧提出的,关于回测的时候成交价格问题(如果按不复权撮合 应该按不复权价格计算assets) | 625941b8a79ad161976cbf8f |
def add_ai_voltage_chan_with_excit( self, physical_channel, name_to_assign_to_channel="", terminal_config=TerminalConfiguration.DEFAULT, min_val=-10.0, max_val=10.0, units=VoltageUnits.VOLTS, bridge_config=BridgeConfiguration.NO_BRIDGE, voltage_excit_source=ExcitationSource.INTERNAL, voltage_excit_val=0.0, use_excit_for_scaling=False, custom_scale_name=""): <NEW_LINE> <INDENT> cfunc = lib_importer.windll.DAQmxCreateAIVoltageChanWithExcit <NEW_LINE> if cfunc.argtypes is None: <NEW_LINE> <INDENT> with cfunc.arglock: <NEW_LINE> <INDENT> if cfunc.argtypes is None: <NEW_LINE> <INDENT> cfunc.argtypes = [ lib_importer.task_handle, ctypes_byte_str, ctypes_byte_str, ctypes.c_int, ctypes.c_double, ctypes.c_double, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_double, c_bool32, ctypes_byte_str] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> error_code = cfunc( self._handle, physical_channel, name_to_assign_to_channel, terminal_config.value, min_val, max_val, units.value, bridge_config.value, voltage_excit_source.value, voltage_excit_val, use_excit_for_scaling, custom_scale_name) <NEW_LINE> check_for_error(error_code) <NEW_LINE> return self._create_chan(physical_channel, name_to_assign_to_channel) | Creates channel(s) to measure voltage. Use this instance for
custom sensors that require excitation. You can use the
excitation to scale the measurement.
Args:
physical_channel (str): Specifies the names of the physical
channels to use to create virtual channels. The DAQmx
physical channel constant lists all physical channels on
devices and modules installed in the system.
name_to_assign_to_channel (Optional[str]): Specifies a name
to assign to the virtual channel this function creates.
If you do not specify a value for this input, NI-DAQmx
uses the physical channel name as the virtual channel
name.
terminal_config (Optional[nidaqmx.constants.TerminalConfiguration]):
Specifies the input terminal configuration for the
channel.
min_val (Optional[float]): Specifies in **units** the
minimum value you expect to measure.
max_val (Optional[float]): Specifies in **units** the
maximum value you expect to measure.
units (Optional[nidaqmx.constants.VoltageUnits]): Specifies
the units to use to return voltage measurements.
bridge_config (Optional[nidaqmx.constants.BridgeConfiguration]):
Specifies what type of Wheatstone bridge the sensor is.
voltage_excit_source (Optional[nidaqmx.constants.ExcitationSource]):
Specifies the source of excitation.
voltage_excit_val (Optional[float]): Specifies in volts the
amount of excitation supplied to the sensor. Refer to
the sensor documentation to determine appropriate
excitation values.
use_excit_for_scaling (Optional[bool]): Specifies if NI-
DAQmx divides the measurement by the excitation. You
should typically set **use_excit_for_scaling** to True
for ratiometric transducers. If you set
**use_excit_for_scaling** to True, set **max_val** and
**min_val** to reflect the scaling.
custom_scale_name (Optional[str]): Specifies the name of a
custom scale for the channel. If you want the channel to
use a custom scale, specify the name of the custom scale
to this input and set **units** to
**FROM_CUSTOM_SCALE**.
Returns:
nidaqmx._task_modules.channels.ai_channel.AIChannel:
Indicates the newly created channel object. | 625941b8004d5f362079a181 |
def create_snapshot(self, snapshot): <NEW_LINE> <INDENT> src_vol_id = snapshot.volume_id <NEW_LINE> src_vol_name = snapshot.volume_name <NEW_LINE> src_vol = self._get_vol_by_id(src_vol_id) <NEW_LINE> self._do_clone_volume(src_vol, src_vol_name, snapshot) <NEW_LINE> snapshot.provider_location = src_vol.provider_location <NEW_LINE> LOG.debug("VeritasNFSDriver create_snapshot %r", snapshot.provider_location) <NEW_LINE> return {'provider_location': snapshot.provider_location} | Create a snapshot of the volume. | 625941b8046cf37aa974cb95 |
def bind_socket(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print("Binding the Port: " + str(self.port)) <NEW_LINE> self.soc.bind((self.host, self.port)) <NEW_LINE> self.soc.listen(5) <NEW_LINE> <DEDENT> except socket.error as msg: <NEW_LINE> <INDENT> print("Socket Binding error" + str(msg) + "\n" + "Retrying...") <NEW_LINE> self.bind_socket() | Binding the socket and listening for connections | 625941b850812a4eaa59c170 |
def key_size(self, bucket_name, key): <NEW_LINE> <INDENT> assert bucket_name, "bucket_name must be specified" <NEW_LINE> assert key, "Key must be specified" <NEW_LINE> k = self.s3.Object(bucket_name, key) <NEW_LINE> return k.content_length // 1024 | Returns the size of a key based on a HEAD request
Args:
bucket_name: the name of the S3 bucket to use (bucket name only, not ARN)
key: the key of the object to delete from the bucket
Returns:
Size in kb | 625941b84e4d5625662d4227 |
def __new__(cls, s): <NEW_LINE> <INDENT> if isinstance(s, tuple): <NEW_LINE> <INDENT> self = tuple.__new__(cls, s) <NEW_LINE> self._raw, self._ref = s, list(range(len(s))) <NEW_LINE> return self <NEW_LINE> <DEDENT> raw = cls._splitquoted.split(s) <NEW_LINE> ref = [] <NEW_LINE> self = tuple.__new__(cls, cls.parse(raw, ref)) <NEW_LINE> self._raw, self._ref = raw, ref <NEW_LINE> return self | >>> Arguments(r"one two three")
('one', 'two', 'three')
>>> Arguments(r"spam 'escaping \'works\''")
('spam', "escaping 'works'")
>>> # For testing purposes we can pass a preparsed tuple
>>> Arguments(('foo', 'bar', 'baz az'))
('foo', 'bar', 'baz az') | 625941b8507cdc57c6306b1d |
def fetch(self): <NEW_LINE> <INDENT> for filename in self.urls: <NEW_LINE> <INDENT> self.fetchone(filename, self.urls.get(filename), do_stream=False) <NEW_LINE> self.write_status() | MTA downloads do not stream. | 625941b850485f2cf553cbe3 |
def _deinit_webhooks(event) -> None: <NEW_LINE> <INDENT> webhooks = self.rachio.notification.getDeviceWebhook( self.controller_id)[1] <NEW_LINE> for webhook in webhooks: <NEW_LINE> <INDENT> if webhook[KEY_EXTERNAL_ID].startswith(WEBHOOK_CONST_ID) or webhook[KEY_ID] == current_webhook_id: <NEW_LINE> <INDENT> self.rachio.notification.deleteWebhook(webhook[KEY_ID]) | Stop getting updates from the Rachio API. | 625941b8a17c0f6771cbde9e |
def __init__(self) -> None: <NEW_LINE> <INDENT> self._schemas = {} <NEW_LINE> self.spec_context = None | Construct. | 625941b84f88993c3716bebe |
def rename_course(course_id, name, code): <NEW_LINE> <INDENT> req_data = {} <NEW_LINE> if name: <NEW_LINE> <INDENT> req_data['course[name]'] = name <NEW_LINE> <DEDENT> if code: <NEW_LINE> <INDENT> req_data['course[code]'] = code <NEW_LINE> <DEDENT> if req_data: <NEW_LINE> <INDENT> api.put('courses/{}'.format(course_id), req_data) | update a course's name and/or code | 625941b832920d7e50b28016 |
def _add_deflection(position, observer, deflector, rmass): <NEW_LINE> <INDENT> pq = observer + position - deflector <NEW_LINE> pe = observer - deflector <NEW_LINE> pmag = length_of(position) <NEW_LINE> qmag = length_of(pq) <NEW_LINE> emag = length_of(pe) <NEW_LINE> phat = position / pmag <NEW_LINE> qhat = pq / qmag <NEW_LINE> ehat = pe / emag <NEW_LINE> pdotq = dots(phat, qhat) <NEW_LINE> qdote = dots(qhat, ehat) <NEW_LINE> edotp = dots(ehat, phat) <NEW_LINE> make_no_correction = abs(edotp) > 0.99999999999 <NEW_LINE> fac1 = 2.0 * GS / (C * C * emag * AU * rmass) <NEW_LINE> fac2 = 1.0 + qdote <NEW_LINE> position += where(make_no_correction, 0.0, fac1 * (pdotq * ehat - edotp * qhat) / fac2 * pmag) | Correct a position vector for how one particular mass deflects light.
Given the ICRS `position` [x,y,z] of an object (AU) together with
the positions of an `observer` and a `deflector` of reciprocal mass
`rmass`, this function updates `position` in-place to show how much
the presence of the deflector will deflect the image of the object. | 625941b81f5feb6acb0c499f |
def semi2deg(pos): <NEW_LINE> <INDENT> DEGREES = 180.0 <NEW_LINE> SEMICIRCLES = 0x80000000 <NEW_LINE> return float(pos) * DEGREES / SEMICIRCLES | Based on https://github.com/adiesner/Fit2Tcx/blob/master/src/Fit2TcxConverter.cpp | 625941b8cad5886f8bd26e2c |
def handle_m2m_field(self, obj, field): <NEW_LINE> <INDENT> if field.rel.through._meta.auto_created: <NEW_LINE> <INDENT> with recursion_depth('handle_m2m_field') as recursion_level: <NEW_LINE> <INDENT> if recursion_level > getattr(settings, 'RECURSION_LIMIT', sys.getrecursionlimit() / 10): <NEW_LINE> <INDENT> raise Exception(MANY_TO_MANY_RECURSION_LIMIT_ERROR % (field.name, obj.__class__.__name__, field.rel.to.__name__)) <NEW_LINE> <DEDENT> self._start_relational_field(field) <NEW_LINE> s = RecursiveXmlSerializer() <NEW_LINE> s.serialize( getattr(obj, field.name).iterator(), xml=self.xml, stream=self.stream) <NEW_LINE> self.xml.endElement("field") | while easymode follows inverse relations for foreign keys,
for manytomayfields it follows the forward relation.
While easymode excludes all relations to "self" you could
still create a loop if you add one extra level of indirection. | 625941b85510c4643540f242 |
def test_one_big_zone(cli, digger, zone_size): <NEW_LINE> <INDENT> t0 = time.time() <NEW_LINE> zn = 'bigzone-%s.org.' % gen_random_name(12) <NEW_LINE> delete_zone_by_name(cli, zn, ignore_missing=True) <NEW_LINE> zone = create_zone_with_retry_on_duplicate(cli, digger, zn, dig=True) <NEW_LINE> assert 'serial' in zone, zone <NEW_LINE> assert 'id' in zone, zone <NEW_LINE> try: <NEW_LINE> <INDENT> digger.reset_goals() <NEW_LINE> digger.add_goal(('zone_serial_ge', zn, int(zone['serial']))) <NEW_LINE> digger.probe_resolver(timeout=60) <NEW_LINE> record_creation_threads = [] <NEW_LINE> for record_num in range(zone_size): <NEW_LINE> <INDENT> record_name = "rec%d" % record_num <NEW_LINE> ipaddr = "127.%d.%d.%d" % ( (record_num >> 16) % 256, (record_num >> 8) % 256, record_num % 256, ) <NEW_LINE> t = Thread(target=create_and_probe_a_record, args=(cli, digger, zone['id'], record_name, ipaddr)) <NEW_LINE> t.start() <NEW_LINE> record_creation_threads.append(t) <NEW_LINE> time.sleep(.5) <NEW_LINE> <DEDENT> digger.wait_on_prober() <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> log.info("Exiting on keyboard") <NEW_LINE> raise <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> digger.stop_prober() <NEW_LINE> delete_zone_by_name(cli, zone['name']) <NEW_LINE> log.info("Done in %ds" % (time.time() - t0)) | Create a zone with many records,
perform CRUD on records and monitor for propagation time | 625941b86aa9bd52df036bec |
def required_iam_permissions(self): <NEW_LINE> <INDENT> return [ "redshift:DescribeClusterSnapshots", "redshift:DescribeClusterSubnetGroups", ] | Return a list of IAM Actions required for this Service to function
properly. All Actions will be shown with an Effect of "Allow"
and a Resource of "*".
:returns: list of IAM Action strings
:rtype: list | 625941b88a43f66fc4b53eb4 |
def symplectic_isomorphisms(self, other = None, hom_basis = None, b = None, r = None): <NEW_LINE> <INDENT> if not other: <NEW_LINE> <INDENT> other = self <NEW_LINE> <DEDENT> if hom_basis: <NEW_LINE> <INDENT> Rs = hom_basis <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Rs = self.homomorphism_basis(other = other, b = b, r = r) <NEW_LINE> <DEDENT> r = len(Rs) <NEW_LINE> g = self.genus <NEW_LINE> A = PolynomialRing(QQ, r, 'x') <NEW_LINE> gensA = A.gens() <NEW_LINE> R = sum( gensA[i]*Rs[i].change_ring(A) for i in range(r) ) <NEW_LINE> tr = (R*self.rosati_involution(R)).trace() <NEW_LINE> M = Matrix(ZZ, r, r, [ tr.derivative(gen1).derivative(gen2) for gen1 in gensA for gen2 in gensA ]) <NEW_LINE> vs = M.__pari__().qfminim(4*g)[2].sage().transpose() <NEW_LINE> vs = [ v for v in vs if v * M * v == 4*g ] <NEW_LINE> vs += [ -v for v in vs ] <NEW_LINE> RsIso = [ ] <NEW_LINE> for v in vs: <NEW_LINE> <INDENT> R = sum( v[i]*Rs[i] for i in range(r) ) <NEW_LINE> if R*self.rosati_involution(R) == 1: <NEW_LINE> <INDENT> RsIso.append(R) <NEW_LINE> <DEDENT> <DEDENT> return RsIso | Numerically compute symplectic isomorphisms.
INPUT:
- ``other`` (default: ``self``) -- the codomain, another Riemann
surface.
- ``hom_basis`` (default: ``None``) -- a `\ZZ`-basis of the
homomorphisms from ``self`` to ``other``, as obtained from
:meth:`homomorphism_basis`. If you have already calculated this
basis, it saves time to pass it via this keyword argument. Otherwise
the method will calculate it.
- ``b`` -- integer (default provided): as for
:meth:`homomorphism_basis`, and used in its invocation if
(re)calculating said basis.
- ``r`` -- integer (default: ``b/4``). as for
:meth:`homomorphism_basis`, and used in its invocation if
(re)calculating said basis.
OUTPUT:
Returns the combinations of the elements of :meth:`homomorphism_basis`
that correspond to symplectic isomorphisms between the Jacobians of
``self`` and ``other``.
EXAMPLES::
sage: from sage.schemes.riemann_surfaces.riemann_surface import RiemannSurface
sage: R.<x,y> = QQ[]
sage: f = y^2 - (x^6 + 2*x^4 + 4*x^2 + 8)
sage: X = RiemannSurface(f, prec = 100)
sage: P = X.period_matrix()
sage: g = y^2 - (x^6 + x^4 + x^2 + 1)
sage: Y = RiemannSurface(g, prec = 100)
sage: Q = Y.period_matrix()
sage: Rs = X.symplectic_isomorphisms(Y)
sage: Ts = X.tangent_representation_numerical(Rs, other = Y)
sage: test1 = all([ ((T*P - Q*R).norm() < 2^(-80)) for [ T, R ] in zip(Ts, Rs) ])
sage: test2 = all([ det(R) == 1 for R in Rs ])
sage: test1 and test2
True | 625941b8e8904600ed9f1d73 |
def fit( self, data, estimator=None, state_names=[], complete_samples_only=True, n_jobs=-1, **kwargs, ): <NEW_LINE> <INDENT> from pgmpy.estimators import MaximumLikelihoodEstimator, BaseEstimator <NEW_LINE> if estimator is None: <NEW_LINE> <INDENT> estimator = MaximumLikelihoodEstimator <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not issubclass(estimator, BaseEstimator): <NEW_LINE> <INDENT> raise TypeError("Estimator object should be a valid pgmpy estimator.") <NEW_LINE> <DEDENT> <DEDENT> _estimator = estimator( self, data, state_names=state_names, complete_samples_only=complete_samples_only, ) <NEW_LINE> cpds_list = _estimator.get_parameters(n_jobs=n_jobs, **kwargs) <NEW_LINE> self.add_cpds(*cpds_list) | Estimates the CPD for each variable based on a given data set.
Parameters
----------
data: pandas DataFrame object
DataFrame object with column names identical to the variable names of the network.
(If some values in the data are missing the data cells should be set to `numpy.NaN`.
Note that pandas converts each column containing `numpy.NaN`s to dtype `float`.)
estimator: Estimator class
One of:
- MaximumLikelihoodEstimator (default)
- BayesianEstimator: In this case, pass 'prior_type' and either 'pseudo_counts'
or 'equivalent_sample_size' as additional keyword arguments.
See `BayesianEstimator.get_parameters()` for usage.
- ExpectationMaximization
state_names: dict (optional)
A dict indicating, for each variable, the discrete set of states
that the variable can take. If unspecified, the observed values
in the data set are taken to be the only possible states.
complete_samples_only: bool (default `True`)
Specifies how to deal with missing data, if present. If set to `True` all rows
that contain `np.Nan` somewhere are ignored. If `False` then, for each variable,
every row where neither the variable nor its parents are `np.NaN` is used.
n_jobs: int (default: -1)
Number of threads/processes to use for estimation. It improves speed only
for large networks (>100 nodes). For smaller networks might reduce
performance.
Returns
-------
Fitted Model: None
Modifies the network inplace and adds the `cpds` property.
Examples
--------
>>> import pandas as pd
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.estimators import MaximumLikelihoodEstimator
>>> data = pd.DataFrame(data={'A': [0, 0, 1], 'B': [0, 1, 0], 'C': [1, 1, 0]})
>>> model = BayesianNetwork([('A', 'C'), ('B', 'C')])
>>> model.fit(data)
>>> model.get_cpds()
[<TabularCPD representing P(A:2) at 0x7fb98a7d50f0>,
<TabularCPD representing P(B:2) at 0x7fb98a7d5588>,
<TabularCPD representing P(C:2 | A:2, B:2) at 0x7fb98a7b1f98>] | 625941b838b623060ff0ac39 |
def make_body(self, address): <NEW_LINE> <INDENT> root = ET.Element('AddressValidationRequest') <NEW_LINE> info = {'Request': { 'TransactionReference': { 'CustomerContext':'foo', 'XpciVersion':'1.0',}, 'RequestAction':'XAV', 'RequestOption':'3'}, 'AddressKeyFormat': address } <NEW_LINE> dicttoxml(info, root) <NEW_LINE> return root | address keys:
AddressLine
PoliticalDivision2 #city
PoliticalDiction #state
PostcodePrimaryLow #zip
CountryCode | 625941b86aa9bd52df036bed |
def testConstructorKwargs(self): <NEW_LINE> <INDENT> class SomeMessage(messages.Message): <NEW_LINE> <INDENT> name = messages.StringField(1) <NEW_LINE> number = messages.IntegerField(2) <NEW_LINE> <DEDENT> expected = SomeMessage() <NEW_LINE> expected.name = 'my name' <NEW_LINE> expected.number = 200 <NEW_LINE> self.assertEquals(expected, SomeMessage(name='my name', number=200)) | Test kwargs via constructor. | 625941b826238365f5f0ecb4 |
def is_punct(node): <NEW_LINE> <INDENT> return node.layer.ID == LAYER_ID and node.punct | Returns whether the unit is a layer0 punctuation (for all Units). | 625941b89c8ee82313fbb5bf |
def update(): <NEW_LINE> <INDENT> util.run(util.add_root(["pacman", "-Syu"])) | Update packages | 625941b8d8ef3951e3243388 |
def decode(self, buffer): <NEW_LINE> <INDENT> self.size = struct.calcsize(self.decoder) <NEW_LINE> self.value = struct.unpack(self.decoder, str(buffer[0:self.size]))[0] <NEW_LINE> return self.size | Decode.
Read a value from the beginning of the buffer
PARAMETERS
buffer: BinaryFileBuffer or string
RETURNS
size in bytes of the decoded data in the buffer | 625941b82eb69b55b151c6f5 |
def execute_action(self, name, params, sg_publish_data): <NEW_LINE> <INDENT> app = self.parent <NEW_LINE> app.logger.debug( "Execute action called for action %s. " "Parameters: %s. Publish Data: %s" % (name, params, sg_publish_data) ) <NEW_LINE> path = six.ensure_text(self.get_publish_path(sg_publish_data)) <NEW_LINE> if self.parent.engine.is_adobe_sequence(path): <NEW_LINE> <INDENT> frame_range = self.parent.engine.find_sequence_range(path) <NEW_LINE> if frame_range: <NEW_LINE> <INDENT> glob_path = re.sub( r"[\[]?([#@]+|%0\d+d)[\]]?", "*{}".format(frame_range[0]), path ) <NEW_LINE> for each_path in sorted(glob.glob(glob_path)): <NEW_LINE> <INDENT> path = each_path <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not os.path.exists(path): <NEW_LINE> <INDENT> raise IOError("File not found on disk - '%s'" % path) <NEW_LINE> <DEDENT> if name == _ADD_TO_COMP: <NEW_LINE> <INDENT> self._add_to_comp(path) <NEW_LINE> <DEDENT> if name == _ADD_TO_PROJECT: <NEW_LINE> <INDENT> self.parent.engine.import_filepath(path) | Execute a given action. The data sent to this be method will
represent one of the actions enumerated by the generate_actions method.
:param name: Action name string representing one of the items returned
by generate_actions.
:param params: Params data, as specified by generate_actions.
:param sg_publish_data: Shotgun data dictionary with all the standard
publish fields. | 625941b82ae34c7f2600cf7c |
def get_kern(self, font1, fontclass1, sym1, fontsize1, font2, fontclass2, sym2, fontsize2, dpi): <NEW_LINE> <INDENT> return 0. | Get the kerning distance for font between *sym1* and *sym2*.
*fontX*: one of the TeX font names::
tt, it, rm, cal, sf, bf or default/regular (non-math)
*fontclassX*: TODO
*symX*: a symbol in raw TeX form. e.g., '1', 'x' or '\sigma'
*fontsizeX*: the fontsize in points
*dpi*: the current dots-per-inch | 625941b8a4f1c619b28afe8c |
def test_users_post(self): <NEW_LINE> <INDENT> pass | Test case for users_post
Creates a new user account. | 625941b8f8510a7c17cf954f |
def _calc_size(self): <NEW_LINE> <INDENT> (total_halfx, total_halfy) = (self.rect.right, self.rect.top) <NEW_LINE> if self._colorbar.orientation in ["bottom", "top"]: <NEW_LINE> <INDENT> (total_major_axis, total_minor_axis) = (total_halfx, total_halfy) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (total_major_axis, total_minor_axis) = (total_halfy, total_halfx) <NEW_LINE> <DEDENT> major_axis = total_major_axis * (1.0 - self._major_axis_padding) <NEW_LINE> minor_axis = major_axis * self._minor_axis_ratio <NEW_LINE> minor_axis = np.minimum(minor_axis, total_minor_axis * (1.0 - self._minor_axis_padding)) <NEW_LINE> return (major_axis, minor_axis) | Calculate a size
| 625941b8ff9c53063f47c048 |
def test_include_end_02(self): <NEW_LINE> <INDENT> with codec_open('a.bdf', 'w') as bdf_file: <NEW_LINE> <INDENT> bdf_file.write('CEND\n') <NEW_LINE> bdf_file.write('BEGIN BULK\n') <NEW_LINE> bdf_file.write('GRID,1,,1.0\n') <NEW_LINE> bdf_file.write("INCLUDE 'b.bdf'\n\n") <NEW_LINE> bdf_file.write('GRID,4,,4.0\n') <NEW_LINE> <DEDENT> with codec_open('b.bdf', 'w') as bdf_file: <NEW_LINE> <INDENT> bdf_file.write('GRID,2,,2.0\n') <NEW_LINE> bdf_file.write("INCLUDE 'c.bdf'\n\n") <NEW_LINE> bdf_file.write('GRID,5,,5.0\n') <NEW_LINE> <DEDENT> with codec_open('c.bdf', 'w') as bdf_file: <NEW_LINE> <INDENT> bdf_file.write('GRID,3,,3.0\n\n') <NEW_LINE> <DEDENT> model = BDF(log=log, debug=False) <NEW_LINE> model.read_bdf('a.bdf') <NEW_LINE> model.write_bdf('a.out.bdf') <NEW_LINE> os.remove('a.bdf') <NEW_LINE> os.remove('b.bdf') <NEW_LINE> os.remove('c.bdf') <NEW_LINE> os.remove('a.out.bdf') <NEW_LINE> self.assertEqual(len(model.nodes), 5) <NEW_LINE> self.assertEqual(model.nnodes, 5, 'nnodes=%s' % model.nnodes) | tests multiple levels of includes | 625941b88e05c05ec3eea1bc |
def from_json(self, d: dict) -> Contract.ABI: <NEW_LINE> <INDENT> self.name = d['name'] if 'name' in d else '' <NEW_LINE> self.args = d['args'] if 'args' in d else [] <NEW_LINE> if 'amountLimit' in d: <NEW_LINE> <INDENT> for al in d['amountLimit']: <NEW_LINE> <INDENT> token = al['token'] if 'token' in al else '' <NEW_LINE> value = al['val'] if 'val' in al else '' <NEW_LINE> self.amount_limit.append(AmountLimit(token, value)) <NEW_LINE> <DEDENT> <DEDENT> return self | Deserializes a dictionary to update this object's members.
Warnings:
This seems to use an old format as input: ``amount_limit`` is written ``amountLimit``
and ``value`` is written ``val``.
Args:
d: The dictionary.
Returns:
Itself. | 625941b8377c676e91271ff5 |
def is_path_searchable(path, uid, username): <NEW_LINE> <INDENT> if os.path.isdir(path): <NEW_LINE> <INDENT> dirname = path <NEW_LINE> base = "-" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dirname, base = os.path.split(path) <NEW_LINE> <DEDENT> fixlist = [] <NEW_LINE> while base: <NEW_LINE> <INDENT> if not _is_dir_searchable(dirname, uid, username): <NEW_LINE> <INDENT> fixlist.append(dirname) <NEW_LINE> <DEDENT> dirname, base = os.path.split(dirname) <NEW_LINE> <DEDENT> return fixlist | Check each dir component of the passed path, see if they are
searchable by the uid/username, and return a list of paths
which aren't searchable | 625941b8099cdd3c635f0aa7 |
def __init__(self, username, email, password, permissions): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.email = email <NEW_LINE> self.password = password <NEW_LINE> self.permissions = permissions | Constructor de Superusers.
Argumentos:
username - nombre del superusuario
email - correo
password - contraseña
permissions - Array de permisos | 625941b88e71fb1e9831d5f8 |
def main(args: Optional[List[str]] = None) -> int: <NEW_LINE> <INDENT> parser = get_parser() <NEW_LINE> parsed_args: argparse.Namespace = parser.parse_args(args) <NEW_LINE> if parsed_args.line_by_line: <NEW_LINE> <INDENT> for line in sys.stdin: <NEW_LINE> <INDENT> with discarded_stdout(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> output = json.dumps(process_json(line)) <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> output = json.dumps({"error": str(error), "traceback": traceback.format_exc()}) <NEW_LINE> <DEDENT> <DEDENT> print(output) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with discarded_stdout(): <NEW_LINE> <INDENT> output = json.dumps(process_json(sys.stdin.read())) <NEW_LINE> <DEDENT> print(output) <NEW_LINE> <DEDENT> return 0 | Run the main program.
This function is executed when you type `pytkdocs` or `python -m pytkdocs`.
Arguments:
args: Arguments passed from the command line.
Returns:
An exit code. | 625941b857b8e32f524832eb |
@node.commandWrap <NEW_LINE> def NodeEditorAddIterationStatePorts(*args, **kwargs): <NEW_LINE> <INDENT> u <NEW_LINE> return cmds.NodeEditorAddIterationStatePorts(*args, **kwargs) | :rtype: list|str|basestring|DagNode|AttrObject|ArrayAttrObject|Components1Base | 625941b83cc13d1c6d3c71cf |
def merge_peak_and_uvvis_obj(row_compound, value_indices, ext_indices): <NEW_LINE> <INDENT> for index in value_indices: <NEW_LINE> <INDENT> if len(row_compound.uvvis_spectra[index].peaks) == len(ext_indices) and len(ext_indices) > 1: <NEW_LINE> <INDENT> row_compound.uvvis_spectra[index].merge_peaks_and_uvvis(row_compound.uvvis_spectra, ext_indices) <NEW_LINE> j = 0 <NEW_LINE> for e in ext_indices: <NEW_LINE> <INDENT> del row_compound.uvvis_spectra[e - j] <NEW_LINE> j = j + 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if value_indices != [] and ext_indices != [] and len(value_indices) == len(ext_indices): <NEW_LINE> <INDENT> for (v, e) in zip(value_indices, ext_indices): <NEW_LINE> <INDENT> row_compound.uvvis_spectra[v].merge_uvvis(row_compound.uvvis_spectra[e]) <NEW_LINE> <DEDENT> k = 0 <NEW_LINE> for e in ext_indices: <NEW_LINE> <INDENT> del row_compound.uvvis_spectra[e - k] <NEW_LINE> k = k + 1 <NEW_LINE> <DEDENT> <DEDENT> return row_compound | Merges all peak and uvvis objects when on different scopes
:param chemdataextractor.model.Compound row_compound : Compound with unresolved uvvis peaks and values
:param list[int] value_indices : List of indices of uvvis value objects
:param list[int] ext_indices : List of indices of uvvis extinction coefficient objects
:returns chemdataextractor.model.Compound row_compound : Compound with resolved uvvis peaks and values | 625941b84f6381625f114891 |
def osd_find(self, id): <NEW_LINE> <INDENT> id_validator = ceph_argparse.CephInt(range='0') <NEW_LINE> id_validator.valid(id) <NEW_LINE> cmd = {'prefix': 'osd find', 'id': id} <NEW_LINE> return run_ceph_command(self.rados_config_file, cmd, inbuf='') | find osd <id> in the CRUSH map and show its location
:param id: int min=0
:return: (string outbuf, string outs)
:raise CephError: Raises CephError on command execution errors
:raise rados.Error: Raises on rados errors | 625941b8d10714528d5ffb2a |
def mutation(agents, length): <NEW_LINE> <INDENT> mutation_rate = 0.3 <NEW_LINE> for agent in agents: <NEW_LINE> <INDENT> for ind, char in enumerate(agent.chromosome_x): <NEW_LINE> <INDENT> if random.uniform(0.0, 1.0) <= mutation_rate: <NEW_LINE> <INDENT> agent.chromosome_x = agent.chromosome[0:ind] + [float(agent.chromosome[ind]) + random.uniform(-2, 2)] + agent.chromosome[ind+1:length] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return agents | Mutate Chromosome at the mutation rate of 0.3. Select random gene then mutate the selected index | 625941b866656f66f7cbbff5 |
def post_process(self): <NEW_LINE> <INDENT> self._disks = self._find_cerebrum_disks() <NEW_LINE> self._disk_name_order = self._disks.keys() <NEW_LINE> self._disk_name_order.sort(self._disk_sort_by_name) <NEW_LINE> self._disk_count_order = self._disks.keys() <NEW_LINE> self._resort_disk_count() | Call once you have finished calling add_disk_def | 625941b8baa26c4b54cb0f6e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.