code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, device, low, high): <NEW_LINE> <INDENT> super().__init__(device) <NEW_LINE> self.low = low <NEW_LINE> self.high = high <NEW_LINE> self.seq_len = seq_len = 20 <NEW_LINE> self.build_model()
Initialize the model Args: device: the device (cpu/gpu) to place the tensors low: (float) low range high: (float) high range seq_len: (int) len of the sequece
625941f150812a4eaa59c8cd
def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.logger.info('初始化 Redis 连接') <NEW_LINE> self.redis_pool = redis.ConnectionPool(host='127.0.0.1', port=6379, password='', db=11) <NEW_LINE> self.redis_db = redis.Redis(connection_pool=self.redis_pool)
初始化 Redis 连接 :param kwargs: 传递参数
625941f121a7993f00bc82ac
def read_stderr(self): <NEW_LINE> <INDENT> if not self.reset: <NEW_LINE> <INDENT> value = sys.stderr.getvalue() <NEW_LINE> self.truncate_stderr() <NEW_LINE> return value
Reads stderr and returns value
625941f1377c676e91272758
def has_won(): <NEW_LINE> <INDENT> if current_room == rooms["Reception"]: <NEW_LINE> <INDENT> required_items = current_room["required_items"] <NEW_LINE> items_found = find_required_items(inventory, required_items) <NEW_LINE> if items_found: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> if has_won(): <NEW...
This function determines whether or not the user has won the game. It defines the victory criteria. The victory criteria are that all items in the game must be dropped at reception.
625941f1c432627299f051fc
def _create_predict_matrix(self, X): <NEW_LINE> <INDENT> n_samples = X.shape[0] <NEW_LINE> valid_estimators = np.nonzero(self.alphas)[0] <NEW_LINE> n_valid_estimators = valid_estimators.shape[0] <NEW_LINE> X_stacking = np.zeros((n_samples, n_valid_estimators)) <NEW_LINE> for estimator in range(n_valid_estimators): <NEW...
A private method used ot create the data for the stacking combiner, used sa a second level model. for each record, each of the models of the ensamble create a prediction which is later used as new features for the regression model. :param X: the data set. :return: a new data set in the size of the X with features as th...
625941f16fb2d068a760f658
def test_filter_dict_correctly_filters_out_values(self): <NEW_LINE> <INDENT> expected_ret = {3: 'c', 4: 'd'} <NEW_LINE> status, ret = hubblestack.fdg.process.filter_dict( starting_dict={1: 'a', 2: 'b', 3: 'c'}, filter_values=True, chained={1: 'b', 3: 'd', 4: 'd'}, gt='a', ne='b', le='d') <NEW_LINE> assert status is Tru...
Test that given correct input, the function correctly filters by values
625941f17b25080760e39a07
def __getitem__(self, i): <NEW_LINE> <INDENT> return self._items[i]
Gets `i` in sorted collection. Returns item.
625941f101c39578d7e753ed
def ycomps(self): <NEW_LINE> <INDENT> return list(self._ycomps.keys())
Returns list of yield component keys.
625941f1ec188e330fd5ad44
def __init__(__self__, __name__, __opts__=None, description=None, name=None, name_prefix=None, path=None, policy=None): <NEW_LINE> <INDENT> if not __name__: <NEW_LINE> <INDENT> raise TypeError('Missing resource name argument (for URN creation)') <NEW_LINE> <DEDENT> if not isinstance(__name__, basestring): <NEW_LINE> <I...
Create a Policy resource with the given unique name, props, and options.
625941f18e05c05ec3eea92b
def interface_disable(self, interface_id): <NEW_LINE> <INDENT> res = self.dgilib.interface_disable( self.dgi_hndl, interface_id) <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> print(f"\t{res} interface_disable: {interface_id}") <NEW_LINE> <DEDENT> if res: <NEW_LINE> <INDENT> raise DeviceReturnError(f"interface_disable...
`interface_disable`. Disables the specified interface. `int interface_disable(uint32_t dgi_hndl, int interface_id)` +------------+------------+ | Parameter | Description | +============+============+ | *dgi_hndl* | Handle of the connection | | *interface_id* | The ID of the interface to disable. | +------------+---...
625941f1379a373c97cfb0f9
def attach_kernel_driver(self, interface): <NEW_LINE> <INDENT> self._ctx.managed_open() <NEW_LINE> self._ctx.backend.attach_kernel_driver( self._ctx.handle, interface)
Re-attach an interface's kernel driver, which was previously detached using detach_kernel_driver(). The interface parameter is the device interface number to attach the driver to.
625941f1dc8b845886cb5ae9
def strip_divs(body, start=None, end=None): <NEW_LINE> <INDENT> DIV = re.compile('<div') <NEW_LINE> UNDIV = re.compile('</div') <NEW_LINE> body_lines = body[1:-1] <NEW_LINE> L = [] <NEW_LINE> count = 0 <NEW_LINE> div_start = 0 <NEW_LINE> for i, line in enumerate(body_lines): <NEW_LINE> <INDENT> if not line: <NEW_LINE> ...
Strip divs from the body for partial notebook insertion If L represents the list of parsed main divs, then this returns the document corresponding to the divs L[start:end]. body should be a list of lines in the body of the html file.
625941f14e4d5625662d4981
def save(self, f, threshold=3, nwords=-1): <NEW_LINE> <INDENT> if isinstance(f, str): <NEW_LINE> <INDENT> os.makedirs(os.path.dirname(f), exist_ok=True) <NEW_LINE> with open(f, 'w', encoding='utf-8') as fd: <NEW_LINE> <INDENT> return self.save(fd, threshold, nwords) <NEW_LINE> <DEDENT> <DEDENT> cnt = 0 <NEW_LINE> for i...
Stores dictionary into a text file
625941f1099cdd3c635f120a
def __init__(self, polygon: geometry_utils.Polygon, target_size: typing.Optional[float] = None): <NEW_LINE> <INDENT> if len(polygon) != 4: <NEW_LINE> <INDENT> raise WrongShapeError("Incorrect number of points.") <NEW_LINE> <DEDENT> if not geometry_utils.all_approx_square(polygon): <NEW_LINE> <INDENT> raise WrongShapeEr...
Create a new Square. If the points don't form a valid square, raises a WrongShapeError. Args: polygon: The polygon to check. Points will be stored such that the first point stored is the first point in this polygon, but the rest of the polygon may be reversed to clockwise. target_size: If provid...
625941f1b5575c28eb68e5b8
def plot_predictions(predictions): <NEW_LINE> <INDENT> dfX = np.genfromtxt('../raw_input.csv', delimiter=',') <NEW_LINE> dfY = np.genfromtxt('../raw_label.csv', delimiter=',') <NEW_LINE> testX, testY = split_data('test', dfX, dfY) <NEW_LINE> for i in range(len(predictions)): <NEW_LINE> <INDENT> err = sqrt(mean_squared_...
Plot the entire dataset in blue
625941f1f548e778e58cdb32
def is_local(self): <NEW_LINE> <INDENT> if self._current_partition is None: <NEW_LINE> <INDENT> return self.local <NEW_LINE> <DEDENT> return self.local or self._current_partition.scheduler.is_local
Check if the test will execute locally. A test executes locally if the :attr:`local` attribute is set or if the current partition's scheduler does not support job submission.
625941f15fdd1c0f98dc07e8
def test_watchdog_send_good_data_image(self): <NEW_LINE> <INDENT> m = Main() <NEW_LINE> m.tcp_connect() <NEW_LINE> m.send_connect([('login', '4.test'), ('passcode', 'test')]) <NEW_LINE> m.get_frame() <NEW_LINE> m.send_frame('SUBSCRIBE', [('destination', config.TEST_WATCHDOG_TOPIC[0][0] + 'image'), ('x-ebu-nofastreply',...
Test if the watchdog send excepted data on topic /image
625941f1f7d966606f6aa5bd
def test_jd_from_datetime_utc(): <NEW_LINE> <INDENT> one_second = 1.0 / (24.0 * 3600.0) <NEW_LINE> datetime_j2000 = datetime(2000, 1, 1, 0, 0, 0).replace(tzinfo=timezone.utc) <NEW_LINE> assert util.jd_from_datetime_utc(datetime_j2000) == pytest.approx(2451544.5, abs=one_second) <NEW_LINE> assert util.jd_from_datetime_u...
This test imported from test_util.py of photrix (E. Dose).
625941f1e8904600ed9f24e9
def test_generic_resources_serialization(self): <NEW_LINE> <INDENT> generic_resources_requests_model = {} <NEW_LINE> generic_resources_requests_model['cpu'] = '100m' <NEW_LINE> generic_resources_requests_model['memory'] = '256M' <NEW_LINE> generic_resource_limits_model = {} <NEW_LINE> generic_resource_limits_model['cpu...
Test serialization/deserialization for GenericResources
625941f1fbf16365ca6f6782
def _fact(context, device): <NEW_LINE> <INDENT> fact_name = _fact_name(device) <NEW_LINE> return context[fact_name]
Return the fact associated with an interface.
625941f1711fe17d82542910
def multiply(self, num1, num2): <NEW_LINE> <INDENT> num1_len, num2_len = len(num1), len(num2) <NEW_LINE> res = ['0'] * (num1_len + num2_len) <NEW_LINE> for i in range(num2_len-1, -1, -1): <NEW_LINE> <INDENT> for j in range(num1_len-1, -1, -1): <NEW_LINE> <INDENT> tmp = int(num1[j]) * int(num2[i]) + int(res[i + j + 1]) ...
:type num1: str :type num2: str :rtype: str
625941f192d797404e30473f
def input_card_info(dict_value, tip_message): <NEW_LINE> <INDENT> result_str = input(tip_message) <NEW_LINE> if len(result_str) > 0: <NEW_LINE> <INDENT> return result_str <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dict_value
输入名片信息 :param dict_value: 字典中原有的值 :param tip_message: 输入的提示文字 :return:
625941f1fff4ab517eb2f9f2
def set_active_rss(feeds): <NEW_LINE> <INDENT> with R.pipeline(transaction=False) as p: <NEW_LINE> <INDENT> for feed in feeds: <NEW_LINE> <INDENT> p.set(settings.REDIS_ACTIVE_RSS_KEY % feed, 1, 2*24*3600) <NEW_LINE> <DEDENT> p.execute()
访问过的源,设置一个标识,3天缓存 :param feeds: :return:
625941f1a17c0f6771cbe601
def grdsf(nu): <NEW_LINE> <INDENT> p = numpy.array([[8.203343e-2, -3.644705e-1, 6.278660e-1, -5.335581e-1, 2.312756e-1], [4.028559e-3, -3.697768e-2, 1.021332e-1, -1.201436e-1, 6.412774e-2]]) <NEW_LINE> q = numpy.array([[1.0000000e0, 8.212018e-1, 2.078043e-1], [1.0000000e0, 9.599102e-1, 2.918724e-1]]) <NEW_LINE> _, np =...
Calculate PSWF using an old SDE routine re-written in Python Find Spheroidal function with M = 6, alpha = 1 using the rational approximations discussed by Fred Schwab in 'Indirect Imaging'. This routine was checked against Fred's SPHFN routine, and agreed to about the 7th significant digit. The gridding function is (1...
625941f132920d7e50b28787
def test_to_knx(self): <NEW_LINE> <INDENT> xknx = XKNX() <NEW_LINE> rv_datetime = RemoteValueDateTime(xknx, value_type="datetime") <NEW_LINE> array = rv_datetime.to_knx( time.strptime("2017-11-28 23:7:24", "%Y-%m-%d %H:%M:%S") ) <NEW_LINE> assert array.value == (0x75, 0x0B, 0x1C, 0x57, 0x07, 0x18, 0x20, 0x80)
Testing date time object.
625941f199cbb53fe6793197
def readParquetTable( self, file_path: Union[str, Path], table_name: str = None ) -> DataFrame: <NEW_LINE> <INDENT> if table_name is None: <NEW_LINE> <INDENT> table_name = Path(file_path).stem <NEW_LINE> <DEDENT> if isinstance(file_path, Path): <NEW_LINE> <INDENT> file_path = str(file_path) <NEW_LINE> <DEDENT> meta_fil...
Reads parquet files using the PySpark Table API to return a DataFrame with bucketing information retained. Bucketing info is only kept when writing the DataFrame using the `saveParquetTable` method. Args: file_path: Path to parquet file table_name: Name of table to create when reading parquet file Returns: ...
625941f1dd821e528d63b756
@api_view(["GET", "POST", "PATCH"]) <NEW_LINE> @permission_classes([]) <NEW_LINE> def who_am_i(request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> token = request.auth.token <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return HttpResponse("Unauthorized", status=HTTPStatus.UNAUTHORIZED) <NEW_LINE> <...
Return the current user. This view is behind a login.
625941f18a43f66fc4b54611
def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=None, redirect_stderr=False): <NEW_LINE> <INDENT> datadir = os.path.join(dirname, "node"+str(i)) <NEW_LINE> if binary is None: <NEW_LINE> <INDENT> binary = os.getenv("acedD", "acedd") <NEW_LINE> <DEDENT> args = [ binary, "-datadir="+datadir...
Start a acedd and return RPC connection to it
625941f16fece00bbac2dcf8
def sign_out_response(response): <NEW_LINE> <INDENT> cookie = request.cookies.get(current_app.config['COOKIE_NAME']).split('+').pop() <NEW_LINE> response.set_cookie(current_app.config['COOKIE_NAME'], '+'+cookie, httponly=True) <NEW_LINE> return response
return a sign out response with cookie deleted
625941f163f4b57ef00016ba
def check_macos(): <NEW_LINE> <INDENT> print("Checking macOS SDK version...") <NEW_LINE> result = subprocess.run(["xcrun", "--show-sdk-version"], stdout=subprocess.PIPE, universal_newlines=True) <NEW_LINE> if not result.returncode is 0: <NEW_LINE> <INDENT> raise Exception("xcrun command returned non-zero exit code {}"....
Checks macOS-specific requirements
625941f18e71fb1e9831dd59
def model_average(pred1, pred2, w1, w2, pred_fun): <NEW_LINE> <INDENT> assert callable(pred_fun) <NEW_LINE> assert w1 + w2 == 1 <NEW_LINE> if pred_fun.__name__ == 'log_erf': <NEW_LINE> <INDENT> pred1 = np.exp(pred1) <NEW_LINE> pred2 = np.exp(pred2) <NEW_LINE> pred1_tmp = cumulative_derivative(pred1) <NEW_LINE> pred2_tm...
Average two models together in linear space. Args: pred1: (np.array) first set of predictions pred2: (np.array) second set of predictions w1: (float) weight for first predictions w2: (float) weight for second predictions pred_fun (function): Function that used to generate the prediction.
625941f1ab23a570cc25073a
def toDico(self): <NEW_LINE> <INDENT> dico = {} <NEW_LINE> for atom in self.atoms: <NEW_LINE> <INDENT> block = [i for i in range(len(self.dico.sizes)) if self.dico.sizes[i]==atom.length][0] <NEW_LINE> n = atom.timePosition +1 <NEW_LINE> frame = math.floor( float(n) / float(atom.length /2) ) +1 <NEW_LINE> key = int(bloc...
Returns the approximant as a sparse dictionary object , key is the index of the atom and values are atom objects
625941f1d268445f265b5421
def p_compilation(p): <NEW_LINE> <INDENT> pass
compilation : | compilation comp_unit | pragma pragma_s
625941f1507cdc57c630729b
def allow_relation(self, obj1, obj2, **hints): <NEW_LINE> <INDENT> if obj1._meta.app_label == 'stackGuruApi' and obj2._meta.app_label == 'stackGuruApi': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif 'stackGuruApi' not in [obj1._meta.app_label, obj2._meta.app_label]: <NEW_LINE> <INDENT> return None <NEW_LINE>...
Determine if relationship is allowed between two objects.
625941f1aad79263cf390ffc
def is_datetime_type(obj): <NEW_LINE> <INDENT> return isinstance(obj, _dt_tuple)
Whether an object is any date, datetime, or time delta type recognized by Bokeh. Arg: obj (object) : the object to test Returns: bool : True if ``obj`` is a datetime type
625941f1e5267d203edce248
def FindGameDef(name, skip=None): <NEW_LINE> <INDENT> toSearch = [None] <NEW_LINE> for folder in os.listdir('reggiedata/games'): toSearch.append(folder) <NEW_LINE> for folder in toSearch: <NEW_LINE> <INDENT> if folder == skip: continue <NEW_LINE> def_ = ReggieGameDefinition(folder) <NEW_LINE> if (not def_.custom) and (...
Helper function to find a game def with a specific name. Skip will be skipped
625941f1bde94217f368339e
def forward(self, input_): <NEW_LINE> <INDENT> batch_size = input_.size(0) <NEW_LINE> h0_encoder1 = Variable(torch.zeros( 2, batch_size, self.hidden_size)).to(self.device) <NEW_LINE> h0_encoder2 = Variable(torch.zeros( 2, batch_size, self.hidden_size)).to(self.device) <NEW_LINE> if self.rnn_network == 'lstm': <NEW_LINE...
get encoding
625941f1d6c5a10208144602
def get_eventartifacts(self, event_ids=None, limit=None, offset=None, order=None, search=None, sort_by=None, tags=None, headers=None, **request_parameters): <NEW_LINE> <INDENT> check_type(headers, dict) <NEW_LINE> check_type(event_ids, basestring) <NEW_LINE> check_type(tags, basestring) <NEW_LINE> check_type(offset, in...
Gets the list of artifacts based on provided offset and limit. Args: event_ids(basestring): eventIds query parameter. List of eventIds. tags(basestring): tags query parameter. Tags defined. offset(int): offset query parameter. Record start offset. limit(int): limit query parameter. # of records to retu...
625941f18e05c05ec3eea92c
def load_trained_model(trained_model_lists): <NEW_LINE> <INDENT> old_models = [] <NEW_LINE> if (len(trained_model_lists) > 0): <NEW_LINE> <INDENT> for m0 in trained_model_lists: <NEW_LINE> <INDENT> model0 = load_one_model(m0) <NEW_LINE> model0.summary() <NEW_LINE> old_models.append(model0) <NEW_LINE> <DEDENT> <DEDENT> ...
Load trained models
625941f17047854f462a19b5
def bounceOffOfPlayer(self): <NEW_LINE> <INDENT> imageKey = "move" <NEW_LINE> if self.playerState == c.PlayerStates.HITTING_PLAYER_SWINGING and not self.isTurningOrthogonally(): <NEW_LINE> <INDENT> imageKey = "turn" <NEW_LINE> <DEDENT> if any(self.rect.colliderect(levelRect) for levelRect in PlayerSprite.currentLevel.l...
Change the sprite's image, coordinates, and swinging angle as it bounces off of another player. As bouncing off of a wall takes priority over bouncing off of a player, it first runs a check to see if the sprite is also bouncing off of a wall. If so, it sets the sprite's state to HITTING_WALL, and the rest of the metho...
625941f1d164cc6175783301
def test_unknown_user(self): <NEW_LINE> <INDENT> num_users = User.objects.count() <NEW_LINE> response = self.client.get('/remote_user/', REMOTE_USER='newuser') <NEW_LINE> self.assertEqual(response.context['user'].username, 'newuser') <NEW_LINE> self.assertEqual(User.objects.count(), num_users + 1) <NEW_LINE> User.objec...
Tests the case where the username passed in the header does not exist as a User.
625941f12c8b7c6e89b35d6e
def __call__(self, anchors, objectness, box_regression, targets): <NEW_LINE> <INDENT> anchors = [cat_boxlist(anchors_per_image) for anchors_per_image in anchors] <NEW_LINE> labels, regression_targets = self.prepare_targets(anchors, targets) <NEW_LINE> sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels) <NEW...
Arguments: anchors (list[list[BoxList]]) objectness (list[Tensor]) box_regression (list[Tensor]) targets (list[BoxList]) Returns: objectness_loss (Tensor) box_loss (Tensor)
625941f1d53ae8145f87a816
def render_tag_posts(self, tag): <NEW_LINE> <INDENT> tag_posts = [] <NEW_LINE> for p in self._posts: <NEW_LINE> <INDENT> for t in tag: <NEW_LINE> <INDENT> if t in p.get('tag'): <NEW_LINE> <INDENT> tag_posts.append(p) <NEW_LINE> template = self.env.get_template('tag.html') <NEW_LINE> html = template.render( posts=tag_po...
渲染一个标签所有文章页 :return:
625941f14f88993c3716c613
def textFromValue(self, value): <NEW_LINE> <INDENT> if self._validator is None: <NEW_LINE> <INDENT> return super(DoubleSpinBox, self).textFromValue(value) <NEW_LINE> <DEDENT> val, si_prefix = number_to_si(value) <NEW_LINE> return '{value:.{decimals}f} {si_prefix}'.format(value=val, decimals=self.decimals(), si_prefix=s...
Overrides :meth:`QtWidgets.QDoubleSpinBox.textFromValue`.
625941f1a8370b7717052e50
def getId(self): <NEW_LINE> <INDENT> return str(self._id)
Return cat object id
625941f11d351010ab8560cd
def DatasetName(path: str) -> Dataset: <NEW_LINE> <INDENT> dataset = Dataset("<DATASET_NAME>") <NEW_LINE> ... <NEW_LINE> return dataset
The dataloader of <Dataset Name> dataset. Arguments: path: The root directory of the dataset. The file structure should be like:: <path> structure under the path Returns: The loaded 'Dataset' object.
625941f1d10714528d60029d
def save_user(form_instance, profile_callback=None): <NEW_LINE> <INDENT> username = form_instance.cleaned_data['username'] <NEW_LINE> email = form_instance.cleaned_data['email'] <NEW_LINE> password = form_instance.cleaned_data['password1'] <NEW_LINE> new_user = User.objects.create_user(username, email, password) <NEW_L...
Create a new **active** user from form data. This method is intended to replace the ``save`` of ``django-registration``s ``RegistrationForm``. Calls ``profile_callback`` if provided. Required form fields are ``username``, ``email`` and ``password1``.
625941f1cdde0d52a9e535eb
def test_get_media_map(self): <NEW_LINE> <INDENT> fi = NearSight() <NEW_LINE> form = {'elements': [{ "type": "TextField", "key": "3320", "label": "Name", "data_name": "name", }, { "type": "PhotoField", "key": "a1b0", "label": "Photos", "data_name": "pics", }, { "type": "VideoField", "key": "5834", "label": "Videos", "d...
Ensures that the media map is returned as expected, and provides implicit documentation.
625941f11f037a2d8b9467ae
def __init__(self, config=None): <NEW_LINE> <INDENT> super(Inspec, self).__init__(config) <NEW_LINE> self.default_linter = 'rubocop' <NEW_LINE> if config: <NEW_LINE> <INDENT> self._tests = self._get_tests()
Sets up the requirements to execute ``inspec`` and returns None. :param config: An instance of a Molecule config. :return: None
625941f160cbc95b062c6af6
def __floordiv__(self, other): <NEW_LINE> <INDENT> _set = Set() <NEW_LINE> for i in self: <NEW_LINE> <INDENT> if not other.search(i): <NEW_LINE> <INDENT> _set.append(i) <NEW_LINE> <DEDENT> <DEDENT> for i in other: <NEW_LINE> <INDENT> if not self.search(i): <NEW_LINE> <INDENT> _set.append(i) <NEW_LINE> <DEDENT> <DEDENT>...
Семмитричное пересечение множеств.
625941f1d268445f265b5422
def __read_user_clusters_text(user, path): <NEW_LINE> <INDENT> eacg.check_cluster_textfile(path) <NEW_LINE> cluster_file = open(path, "r") <NEW_LINE> clusters = {} <NEW_LINE> for l in cluster_file: <NEW_LINE> <INDENT> sl = l.strip() <NEW_LINE> if len(sl) == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if ':' in ...
Reads cleaned user clusters from a text file of the format. trip_name_1: section_id_1 section_id_2 section_id_n trip_name_2: ...
625941f15510c4643540f988
def save_cluster_info(clinfo): <NEW_LINE> <INDENT> clname = clinfo['name'] <NEW_LINE> def json_default(value): <NEW_LINE> <INDENT> if isinstance(value, datetime.date): <NEW_LINE> <INDENT> return value.strftime('%Y-%m-%d %H:%M:%S') <NEW_LINE> <DEDENT> raise TypeError('not JSON serializable') <NEW_LINE> <DEDENT> warning(...
클러스터 정보파일 쓰기.
625941f1cb5e8a47e48b8053
def linked(prefix, ignore_channels=False): <NEW_LINE> <INDENT> conda_package_types = PackageType.conda_package_types() <NEW_LINE> ld = iteritems(linked_data(prefix, ignore_channels=ignore_channels)) <NEW_LINE> return set(dist for dist, prefix_rec in ld if prefix_rec.package_type in conda_package_types)
Return the Dists of linked packages in prefix.
625941f116aa5153ce362a2c
def load_voc_summary(self): <NEW_LINE> <INDENT> voc_emb_size = dict() <NEW_LINE> for key, voc_size in self.VOC_SIZE.items(): <NEW_LINE> <INDENT> emb_size = self.flags.embed_dim <NEW_LINE> voc_emb_size[key] = [voc_size, emb_size] <NEW_LINE> <DEDENT> for k, v in voc_emb_size.items(): <NEW_LINE> <INDENT> if k == self.LABE...
model doesn't support categorical feature custom embedding size
625941f166656f66f7cbc760
def getValue(self): <NEW_LINE> <INDENT> return self.dateTime().toTime_t();
Return the timestamp from the date string
625941f199fddb7c1c9de940
def executeScript(self): <NEW_LINE> <INDENT> activeWin = self.mdiArea.activeSubWindow() <NEW_LINE> scriptTitle = activeWin.windowTitle() <NEW_LINE> if ".py" not in scriptTitle: <NEW_LINE> <INDENT> self.statusBar().showMessage('Cannot Execute From a Non-Script Window') <NEW_LINE> return <NEW_LINE> <DEDENT> subWin = self...
Executes the script in the active editor window and displays it.
625941f14428ac0f6e5badaa
def log(A): <NEW_LINE> <INDENT> return RPN._op("LOG", A)
log (A) (natural log)
625941f18da39b475bd6552e
def assign_from_checkpoint_fn(model_path, var_list, ignore_missing_vars=False, reshape_variables=False): <NEW_LINE> <INDENT> if not var_list: <NEW_LINE> <INDENT> raise ValueError('var_list cannot be empty') <NEW_LINE> <DEDENT> if ignore_missing_vars: <NEW_LINE> <INDENT> reader = pywrap_tensorflow.NewCheckpointReader(mo...
Returns a function that assigns specific variables from a checkpoint. If ignore_missing_vars is True and no variables are found in the checkpoint it returns None. Args: model_path: The full path to the model checkpoint. To get latest checkpoint use `model_path = tf.train.latest_checkpoint(checkpoint_dir)` v...
625941f1097d151d1a223409
def send_email(sender, recipients, subject, body): <NEW_LINE> <INDENT> msg = MIMEText(body) <NEW_LINE> msg['Subject'] = Header(subject) <NEW_LINE> msg['From'] = sender <NEW_LINE> if type(recipients) is list: <NEW_LINE> <INDENT> msg['To'] = ", ".join(recipients) <NEW_LINE> <DEDENT> if type(recipients) is str: <NEW_LINE>...
Function to send emails. sender and recipients can be a list or a string.
625941f14428ac0f6e5badab
def _extract_filters(self, queryparams=None): <NEW_LINE> <INDENT> if not queryparams: <NEW_LINE> <INDENT> queryparams = self.request.GET <NEW_LINE> <DEDENT> filters = [] <NEW_LINE> for param, paramvalue in queryparams.items(): <NEW_LINE> <INDENT> param = param.strip() <NEW_LINE> value = native_value(paramvalue) <NEW_LI...
Extracts filters from QueryString parameters.
625941f1f8510a7c17cf9cb4
def __init__(self, model, sess=K.get_session(), loss_fn=None, output_type='probs'): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.input_tensor = model.inputs[0] <NEW_LINE> if output_type == 'probs': <NEW_LINE> <INDENT> self.probs = model.outputs[0] <NEW_LINE> <DEDENT> elif output_type == 'logits': <NEW_LINE> <...
To generate the White-box Attack Agent. RNN is not supported now. :param model: the target model which should have the input tensor, the target tensor and the loss tensor. :param sess: the tensorflow session. :param loss_fn: None if using original loss of the model. You can also use your own loss function instea...
625941f10383005118ecfb93
def show_menu(): <NEW_LINE> <INDENT> print("*" * 50) <NEW_LINE> print("欢迎使用【名片管理系统】 V1.0") <NEW_LINE> print("") <NEW_LINE> print("1. 新增名片") <NEW_LINE> print("2. 显示全部") <NEW_LINE> print("3. 搜索名片") <NEW_LINE> print("") <NEW_LINE> print("0. 退出系统") <NEW_LINE> print("*" * 50)
显示菜单
625941f1f548e778e58cdb33
def create_identifier_payload(only_identifier=True): <NEW_LINE> <INDENT> if only_identifier: <NEW_LINE> <INDENT> return json.dumps(get_sys_info()) <NEW_LINE> <DEDENT> return get_sys_info()
Creates a json payload with client information
625941f115fb5d323cde10cb
def addMoveRating(self, level): <NEW_LINE> <INDENT> if not self.acheivedMoveAwardOnLevel(level): <NEW_LINE> <INDENT> self.moveRatings.append(level.getID()) <NEW_LINE> SaveProfile(self)
Add a move Rating
625941f1b830903b967e9eb7
def set_visibility(is_visible): <NEW_LINE> <INDENT> safe_call(backend.get().af_set_visibility(self._wnd, is_visible))
A flag that shows or hides the window as requested. Parameters ---------- is_visible: Flag specifying the visibility of the flag.
625941f126238365f5f0f429
def save_gif(self, ofn): <NEW_LINE> <INDENT> self.sprite_sheet.save(ofn, transparency=0)
Takes a full filename and saves the spritesheet
625941f14c3428357757c8d7
def find_title(soup): <NEW_LINE> <INDENT> return soup.title.get_text()
FIND TITLE USING BS4.
625941f1bf627c535bc13782
def collect_processes_metabolites_compartments(reactions=None): <NEW_LINE> <INDENT> collection = {} <NEW_LINE> for reaction in reactions.values(): <NEW_LINE> <INDENT> processes = reaction["processes"] <NEW_LINE> for process in processes: <NEW_LINE> <INDENT> if process not in collection: <NEW_LINE> <INDENT> collection[p...
Collects information about processes' metabolites and compartments arguments: reactions (dict<dict>): information about reactions returns: (dict<dict<list<str>>>): information about compartments in which each metabolite participates in each process raises:
625941f1e8904600ed9f24ea
def _recieve(self, source: int, cb_condition: int, view_dict: dict): <NEW_LINE> <INDENT> print("IN RECIEVE: ", view_dict.com_tup[0]) <NEW_LINE> print("CHILD_DICT: ", self._dict) <NEW_LINE> signal, data = view_dict.recv() <NEW_LINE> print('signal: {signal}, data: {data}'.format(**locals())) <NEW_LINE> if signal == 'clos...
Recieve signals from outside.
625941f1cc40096d61595f01
def get_user_context(): <NEW_LINE> <INDENT> cxt = {} <NEW_LINE> session = getattr(request, 'session', {}) <NEW_LINE> cxt.update({ 'session': { 'context': session.get('context', {}), 'db': session.get('db', None), 'login': session.get('login', None), 'password': session.get('uid', None), }, }) <NEW_LINE> return cxt
get the current user context, if possible
625941f1462c4b4f79d1dc82
def dist_between_points(a, b): <NEW_LINE> <INDENT> distance = sum(map(lambda a_b: (a_b[0] - a_b[1]) ** 2, zip(a, b))) <NEW_LINE> return math.sqrt(distance)
Return the Euclidean distance between two points
625941f150485f2cf553d34f
def test_malformed(self): <NEW_LINE> <INDENT> self.assertMalformed(self.lua, [ ('tag', 0), ('tag', 0, 'add'), ('tag', 0, 'remove'), ('tag', 0, 'get'), ('tag', 0, 'get', 'foo', 'bar'), ('tag', 0, 'get', 'foo', 0, 'bar'), ('tag', 0, 'top', 'bar'), ('tag', 0, 'top', 0, 'bar'), ('tag', 0, 'foo') ])
Enumerate all the ways it could be malformed
625941f1435de62698dfe200
def dict(_: Dict[T, U] = None) -> Dict[T, U]: <NEW_LINE> <INDENT> pass
Create a new dictionary. Make argument of type Mappable after implementing interfaces
625941f1aad79263cf390ffd
def __call__(self, a, y): <NEW_LINE> <INDENT> self.u = a - y <NEW_LINE> return np.einsum('ij,ij->', self.u, self.u, optimize=True) / self.u.size
a: 批量的样本输出 y: 批量的样本真值 return: 该批样本的平均损失 输出与真值的shape是一样的,并且都是批量的,单个输出与真值是一维向量 a.shape = y.shape = (N, C) N是该批样本的数量,C是单个样本最终输出向量的长度
625941f1566aa707497f4b13
@desktop.command() <NEW_LINE> @click.pass_context <NEW_LINE> def list(ctx): <NEW_LINE> <INDENT> click.echo("Your available EPIC Teams") <NEW_LINE> click.echo("ID | Status | Node Type | Launched by | Created") <NEW_LINE> click.echo("-----------------") <NEW_LINE> for desktop in ctx.obj[1].desktops.list(): <NEW_LINE> <IN...
List your EPIC Desktop instances
625941f13539df3088e2e8ff
def test_xml_hessian(xml_parser): <NEW_LINE> <INDENT> xml_data = xml_parser() <NEW_LINE> assert xml_data.get_hessian() == None
Check hessian matrix.
625941f1d6c5a10208144603
def test_parse_command_result_fail(self): <NEW_LINE> <INDENT> with patch.object(zfs, '_zfs_cmd', MagicMock(return_value='/sbin/zfs')): <NEW_LINE> <INDENT> with patch.object(zfs, '_zpool_cmd', MagicMock(return_value='/sbin/zpool')): <NEW_LINE> <INDENT> with patch.object(zfs, 'property_data_zfs', MagicMock(return_value=s...
Test if parse_command_result returns the expected result on failure
625941f1ad47b63b2c50a533
@task <NEW_LINE> def release(): <NEW_LINE> <INDENT> versiontag() <NEW_LINE> push_tags() <NEW_LINE> pypi_update()
Runs ``versiontag`` ``push_tags`` and ``pypi_update``.
625941f1711fe17d82542911
def color_interpolate(start_color, end_color, progress): <NEW_LINE> <INDENT> start_r = start_color[0] <NEW_LINE> start_g = start_color[1] <NEW_LINE> start_b = start_color[2] <NEW_LINE> end_r = end_color[0] <NEW_LINE> end_g = end_color[1] <NEW_LINE> end_b = end_color[2] <NEW_LINE> final_r = int(start_r + (end_r - start_...
Auxiliary color interpolation function What this really does is just calculate start_color + progress * (end_color - start_color) Parameters: start_color - tuple RGB color 0 - 255; the color at 0.0 progress end_color - tuple RGB color 0 - 255; the color at 1.0 progress progress - float 0.0 - 1.0; indicate...
625941f1460517430c394728
def process_info(f): <NEW_LINE> <INDENT> with open(f, "r") as r: <NEW_LINE> <INDENT> content = r.read() <NEW_LINE> <DEDENT> status_line = "HTTP/1.1 200 ok\r\n" <NEW_LINE> header = "Content-Type: text/html\r\n" <NEW_LINE> header += "Content-Length: {}\r\n".format(len(str.encode(content))) <NEW_LINE> response_msg = statu...
Process the info introduced by the client request. Parameters: f: file that should be open depending the request
625941f115baa723493c452d
def setup(self, is_training, n_classes, keep_prob): <NEW_LINE> <INDENT> raise NotImplementedError('Must be implemented by the subclass.')
Construct the network.
625941f1236d856c2ad44d96
def testQChem_QChem4_3_R_propylene_oxide_freq_ccsd_out(logfile): <NEW_LINE> <INDENT> assert hasattr(logfile.data, 'grads') <NEW_LINE> ngrads = 1 + 6*logfile.data.natom <NEW_LINE> assert logfile.data.grads.shape == (ngrads, logfile.data.natom, 3) <NEW_LINE> idx = (0, 8, 1) <NEW_LINE> assert logfile.data.grads[idx] == 0....
Check to see that the CCSD (numerical) Hessian is being parsed.
625941f11b99ca400220b067
def get_inode(arg): <NEW_LINE> <INDENT> volume_name, top, path, isdir = arg <NEW_LINE> db = settings.DB <NEW_LINE> inode = None <NEW_LINE> if isdir: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> inode = get_base_inode(volume_name, path) <NEW_LINE> cadfael.core.signals.inode(inode, path) <NEW_LINE> route = path[len(top)-...
extract the info for an inode
625941f196565a6dacc8fc7c
def set_attr(self, new_config): <NEW_LINE> <INDENT> merge_dict(self.data, new_config)
New config is a dictionary with the fields to be updated
625941f1099cdd3c635f120b
def Indices(self, *args): <NEW_LINE> <INDENT> return _stomp.IndexedTreeMap_Indices(self, *args)
Indices(self, Pixel pix, IndexVector indices)
625941f1e76e3b2f99f3adb5
def batch_dl(murl, nrequests, workers, file_path, url_generator): <NEW_LINE> <INDENT> with FuturesSession(session=requests.Session(), executor=ProcessPoolExecutor(max_workers=workers)) as session: <NEW_LINE> <INDENT> processed = 0 <NEW_LINE> temp = [] <NEW_LINE> for url in url_generator: <NEW_LINE> <INDENT> temp.append...
Batch download TimeMaps from Memgator :param str murl: URL to the running Memgator instance :param int nrequests: How many requests should be made at a time :param int workers: How many workers should be spawned :param file_path: Function returning the file path for the TimeMap from the URL :param url_generator: Genera...
625941f1b830903b967e9eb8
def entry_to_series(entry): <NEW_LINE> <INDENT> if not entry: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> series = Series(name=str(entry[SI.NAME]), volumes_owned=str(entry[SI.VOL_OWNED]), is_completed=entry[SI.IS_COMPLETED], next_volume=entry[SI.NEXT_VOLUME], publisher=str(entry[SI.PUBLISHER]), author=str(entry...
entry_to_series() Takes a single row from a database query and converts it into a series.
625941f1f9cc0f698b140ba9
def detachFrom(self, parent): <NEW_LINE> <INDENT> return _DataModel.EventParameters_detachFrom(self, parent)
detachFrom(EventParameters self, PublicObject parent) -> bool
625941f18a43f66fc4b54612
def doAnalysisLastDay(self, stockId=None, dataFrame=None, lParam=None, rParam=None): <NEW_LINE> <INDENT> return self.DoAnalysisLastNDay(stockId, dataFrame, 1, lParam, rParam)
分析最后一天
625941f16fece00bbac2dcf9
def pow(X, power, pm): <NEW_LINE> <INDENT> mgroup_size = len(pm) <NEW_LINE> def pow_el(x): <NEW_LINE> <INDENT> if x == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return get_dec((get_pow(x, pm=pm) * power) % mgroup_size, pm=pm) <NEW_LINE> <DEDENT> <DEDENT> if _np.isscalar(X): <NEW_LINE...
возведение матрицы X из элементов из поля Галуа, определяемого м-цей pm, в степень power
625941f196565a6dacc8fc7d
def exportConfig(self, config_export_path): <NEW_LINE> <INDENT> self._config_export_path = config_export_path <NEW_LINE> self._server.send_message("iou.export_config", {"id": self._iou_id}, self._exportConfigCallback)
Exports the initial-config :param config_export_path: export path for the initial-config
625941f1377c676e9127275a
def apply_shift(self, shift): <NEW_LINE> <INDENT> dictionary = Message.build_shift_dict(self,shift) <NEW_LINE> text = self.get_message_text() <NEW_LINE> result ="" <NEW_LINE> for char in text: <NEW_LINE> <INDENT> result += dictionary.get(char,char) <NEW_LINE> <DEDENT> return result
Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (stri...
625941f110dbd63aa1bd3155
def send_image(imagepath, channel, client) : <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = client.files_upload(channels=channel, file=imagepath) <NEW_LINE> assert response["file"] <NEW_LINE> <DEDENT> except SlackApiError as e: <NEW_LINE> <INDENT> assert e.response["ok"] is False <NEW_LINE> assert e.response["...
Send file as slack bot
625941f1c4546d3d9de72fed
def setIterR(self, iterR): <NEW_LINE> <INDENT> self.iterR = iterR
Number of iterations of updating r to do for each inner loop.
625941f144b2445a33932645
def test_dev_config(self): <NEW_LINE> <INDENT> app = create_app('sql_duplicater.settings.DevConfig') <NEW_LINE> assert app.config['DEBUG'] is True <NEW_LINE> assert app.config['SQLALCHEMY_DATABASE_URI'] == 'sqlite:///../database.db' <NEW_LINE> assert app.config['CACHE_TYPE'] == 'null'
Tests if the development config loads correctly
625941f101c39578d7e753ef
def set_image_palette(self, r, g, b): <NEW_LINE> <INDENT> print("draw_image_palette: {}".format(zip(r, g, b))) <NEW_LINE> self.palette = zip(r, g, b)
Given a set of RGB colors, create a list of 24bit numbers representing the pallet. I.e., RGB of (1,64,127) would be saved as 82047, or the number 00000001 01000000 011111111 :param r: red channel :param g: green channel :param b: blue channel :return:
625941f1442bda511e8be9c3
def get_available_moves(self, board, pos) : <NEW_LINE> <INDENT> moves = [] <NEW_LINE> for direction in ('left', 'right') : <NEW_LINE> <INDENT> piece_encountered = False <NEW_LINE> step = 1 <NEW_LINE> while True : <NEW_LINE> <INDENT> new_file = utils.get_file(pos[0], direction, step) <NEW_LINE> if new_file : <NEW_LINE> ...
Returns all available moves for piece in pos Format [(rank, file), ...]
625941f18a349b6b435e8726
def _fix_issue_227_parse_fetcher_opts(self): <NEW_LINE> <INDENT> easy_install_opts = {} <NEW_LINE> if not self.attrs or 'script_args' not in self.attrs: <NEW_LINE> <INDENT> return easy_install_opts <NEW_LINE> <DEDENT> script_args = self.attrs['script_args'] <NEW_LINE> supported_opts = (("index_url", "--index-url", "-i"...
When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well.
625941f11d351010ab8560ce
def write_to_file(filename: str, routes: List[Tuple[list, float]]) -> None: <NEW_LINE> <INDENT> with open(filename, "w") as file: <NEW_LINE> <INDENT> [file.write(output(x + 1, route)) for x, route in enumerate(routes)]
Write routes to the file as "Option <X>": <Route>
625941f16fb2d068a760f65b
def write_text(path, contents): <NEW_LINE> <INDENT> from pykern import pkcompat <NEW_LINE> fn = py_path(path) <NEW_LINE> with io.open(str(fn), 'wt', encoding=TEXT_ENCODING) as f: <NEW_LINE> <INDENT> f.write(pkcompat.from_bytes(contents)) <NEW_LINE> <DEDENT> return fn
Open file, write text with utf-8, and close. Args: path (str or py.path.Local): Path of file to write to contents (str or bytes): New contents Returns: py.path.local: `filename` as :class:`py.path.Local`
625941f1a934411ee3751c49