code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_get_protocol_version(self): <NEW_LINE> <INDENT> server, client = self._loopback() <NEW_LINE> client_protocol_version = client.get_protocol_version() <NEW_LINE> server_protocol_version = server.get_protocol_version() <NEW_LINE> self.assertIsInstance(server_protocol_version, int) <NEW_LINE> self.assertIsInstance...
:py:obj:`Connection.get_protocol_version()` returns an integer giving the protocol version of the current connection.
625941eb009cb60464c6388e
def withMagnitude(self, target_magnitude, bandpass): <NEW_LINE> <INDENT> current_magnitude = self.calculateMagnitude(bandpass) <NEW_LINE> norm = 10**(-0.4*(target_magnitude - current_magnitude)) <NEW_LINE> ret = self.copy() <NEW_LINE> ret._rest_photons = lambda w: self._rest_photons(w) * norm <NEW_LINE> return ret
Return a new SED with magnitude through `bandpass` set to `target_magnitude`. Note that this requires `bandpass` to have been assigned a zeropoint using `Bandpass.withZeropoint()`. When the returned SED is multiplied by a GSObject with flux=1, the resulting ChromaticObject will have magnitude `target_magnitude` when ...
625941ebb5575c28eb68e4e6
def do_query(self, line): <NEW_LINE> <INDENT> self.__controller.query(line)
Syntax: query [line] -> Returns basic data from the database. :param [line]: * Retrieves all data id Retrieves all empids age Retrieves all ages gender Retrieves all genders salary Retrieves all salaries bmi Retrieves all body mass indexes bi...
625941eb5fc7496912cc3e5e
def tokenizer(tweet: str) -> str: <NEW_LINE> <INDENT> social_tokenizer = SocialTokenizer(lowercase=False).tokenize <NEW_LINE> return " ".join(s for s in social_tokenizer(tweet))
Returns the tokenized sentence using a tokenizer specially designed for social network content, that can handle complex emoticons, emojis and other unstructured expressions like dates, times and more. Args: tweet (str) : the original tweet. Returns: tokenized_tweet (str) : the tokenized tweet.
625941ebe64d504609d74d21
def get_meta(key, default="Unknown"): <NEW_LINE> <INDENT> if not key in data: <NEW_LINE> <INDENT> msg = "key %s not found in the animation" % key <NEW_LINE> rospy.logdebug(msg) <NEW_LINE> return default <NEW_LINE> <DEDENT> return data[key] <NEW_LINE> self.current_state.name = get_meta('name', 'NONAME') <NEW_LINE> self....
Retrieve the meta-information for given key from data :param str key: :param default: returned if key does not exist :type default: any
625941eb7047854f462a18e5
def get_foreign_keys(self, connection, table_name, schema=None, **kw): <NEW_LINE> <INDENT> raise NotImplementedError()
Return information about foreign_keys in `table_name`. Given a :class:`_engine.Connection`, a string `table_name`, and an optional string `schema`, return foreign key information as a list of dicts with these keys: * ``name`` - the constraint's name * ``constrained_columns`` - a list of column names that make up...
625941eb5fc7496912cc3e5f
def sum(self, axis=None): <NEW_LINE> <INDENT> return self.__reduce(bn.nansum, axis=axis)
Sum of values along axis, ignoring NaNs. Parameters ---------- axis : {None, integer}, optional Axis to sum along or sum over all (None, default). Returns ------- d : {larry, scalar} When axis is an integer a larry is returned. When axis is None (default) a scalar is returned (assuming larry contains ...
625941ebdc8b845886cb5a18
def get_business_lines(): <NEW_LINE> <INDENT> business_line_type = CIType.objects.get(name='BusinessLine') <NEW_LINE> for business_line in CI.objects.filter(type=business_line_type): <NEW_LINE> <INDENT> yield { 'ci_id': business_line.id, 'ci_uid': business_line.uid, 'name': business_line.name, }
Returns Business Lines from CMDB (CIs with type Business Line)
625941ebec188e330fd5ac76
def get_time_string(self, time=None): <NEW_LINE> <INDENT> time = self.get_time_tuple(time) <NEW_LINE> if not time and self.time_from: <NEW_LINE> <INDENT> return self.get_time_string(datetime.now() - self.time_from) <NEW_LINE> <DEDENT> elif not time: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> hours = time[0] <NEW...
Returns time in string format
625941eb009cb60464c6388f
def __init__(self, proxy=None): <NEW_LINE> <INDENT> self.root = 'https://cdn.rawgit.com' <NEW_LINE> self.url = '/bangumi-data/bangumi-data/master/data/items/{}/{}.json' <NEW_LINE> ParserBase.__init__(self, self.root, proxy) <NEW_LINE> year = datetime.datetime.now().year <NEW_LINE> month = datetime.datetime.now().month ...
init :proxy: User proxy {'http': '127.0.0.1:1080'}
625941ebcad5886f8bd274ba
def calcPoints(UQID): <NEW_LINE> <INDENT> gradeDict = {1.0:10, 1.5:8, 2.0:6, 2.5:4, 3.0:2, 3.5:0, 4.0:-2, 4.5:-4, 5.0:-6, 5.5:-8, 6.0:-10} <NEW_LINE> goalDict = {'Torwart':6, 'Abwehr':5,'Mittelfeld':4,'Sturm':3} <NEW_LINE> Uq = c.execute("SELECT * FROM PlayerStats{}_{} WHERE UQID={}".format(league, season[2:], UQID)).f...
calculate the points a player gained by using his grade, score etc. UQID is the unique ID in PlayerStats composed of PlayerID+000+Gameday
625941eb099cdd3c635f113a
def cmd__set(self, from_lang, to_lang): <NEW_LINE> <INDENT> self.from_lang = from_lang <NEW_LINE> self.to_lang = to_lang <NEW_LINE> self.info(f'Translator set to {self.from_lang} -> {self.to_lang}') <NEW_LINE> self.open_monitor()
Set "from" and "to" language Usage: set <from_lang> <to_lang> <from_lang> and <to_lang> should always use two letters, like "en", "es" or "pt".
625941eb0fa83653e4657499
def test_phone_field_with_valid_value(self): <NEW_LINE> <INDENT> DescriptorMock.value = api.PhoneField(required=True) <NEW_LINE> try: <NEW_LINE> <INDENT> DescriptorMock("79030000000") <NEW_LINE> DescriptorMock(79030000000) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.error_msg = str(e) <NEW_LINE>...
Test `PhoneField` descriptor with valid dicts.
625941eb4428ac0f6e5bacd8
def icon(self, column, renderer, model, iter_, col_num): <NEW_LINE> <INDENT> stock_id = model.get_value(iter_, col_num) <NEW_LINE> if stock_id == '': <NEW_LINE> <INDENT> stock_id = None <NEW_LINE> <DEDENT> renderer.set_property('stock_id', stock_id)
Set the stock icon property of the cell renderer. We use a cell data function because there is a problem returning None from a model.
625941eb442bda511e8be8f2
def isfinite(self): <NEW_LINE> <INDENT> return np.all(np.isfinite(self.coefficients))
Test if a Function is bounded. returns False if f has any infinite coefficients
625941eb3eb6a72ae02ec9cc
@pytest.fixture() <NEW_LINE> def recharge(amount, investor_login): <NEW_LINE> <INDENT> request_url = MidHandler.conf_data["ENV"]["BASE_URL"] + MidHandler.conf_data["RECHARGE"]["URL"] <NEW_LINE> request_method = MidHandler.conf_data["RECHARGE"]["METHOD"] <NEW_LINE> request_header = MidHandler.conf_data["ENV"]["HEADER"] ...
充值接口 :return: response 响应数据
625941eb63f4b57ef00015ec
def _InitTextures(self): <NEW_LINE> <INDENT> BUFFER_LEVEL = self._bufferLevel <NEW_LINE> BUFFER_RESOLUTION = self._length <NEW_LINE> self._levels = list() <NEW_LINE> tex = (c_uint * (BUFFER_LEVEL + 1))(0) <NEW_LINE> glGenTextures(BUFFER_LEVEL + 1, tex) <NEW_LINE> tex[0] = self._inputID <NEW_LINE> for i in range(0,BUFFE...
Initialises all textures
625941eb0383005118ecfac2
def get_domain_random_screenshot(domain): <NEW_LINE> <INDENT> return Screenshot.get_randon_domain_screenshot(domain)
Retun last screenshot (core item). :param domain: crawled domain
625941eb4e4d5625662d48b2
def add_node(self, view: View): <NEW_LINE> <INDENT> super().add_node(view) <NEW_LINE> self.layedout = False <NEW_LINE> if isinstance(view, Button): <NEW_LINE> <INDENT> self.focusables.append(view) <NEW_LINE> if len(self.focusables) - 1 == self.focus: <NEW_LINE> <INDENT> view.on_focus() <NEW_LINE> <DEDENT> <DEDENT> else...
Adds nodes and invalidates current layout
625941eb2eb69b55b151cd98
def get_gained(self): <NEW_LINE> <INDENT> if self.GAIN is None: <NEW_LINE> <INDENT> gain = {} <NEW_LINE> for genome, hmap in self.maps.items(): <NEW_LINE> <INDENT> gain[genome] = hmap.GAIN <NEW_LINE> <DEDENT> self.GAIN = gain <NEW_LINE> <DEDENT> return self.GAIN
Lazy getter for gained genes. Returns: dictionary of Gn -> [Hn].
625941ebaad79263cf390f2a
def _process_image_files_batch(coder, output_file, filenames, synsets, labels): <NEW_LINE> <INDENT> writer = tf.python_io.TFRecordWriter(output_file) <NEW_LINE> for filename, synset in zip(filenames, synsets): <NEW_LINE> <INDENT> image_buffer, height, width = _process_image(filename, coder) <NEW_LINE> label = labels[sy...
Processes and saves list of images as TFRecords. Args: coder: instance of ImageCoder to provide TensorFlow image coding utils. output_file: string, unique identifier specifying the data set filenames: list of strings; each string is a path to an image file synsets: list of strings; each string is a unique Word...
625941ebcc40096d61595e30
def change(self, amount: int, coins: List[int]) -> int: <NEW_LINE> <INDENT> dp = [[0] * (amount+1) for _ in range(len(coins)+1)] <NEW_LINE> for i in range(1+len(coins)): <NEW_LINE> <INDENT> dp[i][0] = 1 <NEW_LINE> <DEDENT> for i in range(1, len(coins)+1): <NEW_LINE> <INDENT> for j in range(1, amount+1): <NEW_LINE> <IND...
dp[i][j] = 用前i個組成j 有幾種
625941eba17c0f6771cbe531
def calcHardMergeGap_SpecificPairs(self, SS, PairList): <NEW_LINE> <INDENT> Gaps = np.zeros(len(PairList)) <NEW_LINE> for ii, (kA, kB) in enumerate(PairList): <NEW_LINE> <INDENT> Gaps[ii] = self.calcHardMergeGap(SS, kA, kB) <NEW_LINE> <DEDENT> return Gaps
Calc change in ELBO for specific list of candidate hard merge pairs Returns --------- Gaps : 1D array, size L Gaps[j] = scalar change in ELBO after merge of PairList[j]
625941eb24f1403a92601043
def cmdLineParse(): <NEW_LINE> <INDENT> import sys <NEW_LINE> import argparse <NEW_LINE> parser = argparse.ArgumentParser(description='ionospheric correction') <NEW_LINE> parser.add_argument('-ion_dir', dest='ion_dir', type=str, required=True, help = 'directory of ionospheric phase for each date') <NEW_LINE> parser.add...
command line parser.
625941eb76e4537e8c351b58
def get_data(self, id): <NEW_LINE> <INDENT> token = self.data[id] <NEW_LINE> if token: <NEW_LINE> <INDENT> return token <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log().error('获取token失败') <NEW_LINE> return
根据关键字获取对应数据
625941eb460517430c394659
def check_ontology(): <NEW_LINE> <INDENT> if not os.path.exists(CSO_PICKLE_PATH) : <NEW_LINE> <INDENT> if not os.path.exists(CSO_JSON_PATH): <NEW_LINE> <INDENT> generate_cso_dict() <NEW_LINE> <DEDENT> with open(CSO_JSON_PATH, 'r') as jf: <NEW_LINE> <INDENT> cso = json.load(jf) <NEW_LINE> <DEDENT> with open(CSO_PICKLE_P...
Function that checks if the ontology file is available. Then it will create the pickle file.
625941eb91af0d3eaac9beff
def eval(self,x): <NEW_LINE> <INDENT> y = [] <NEW_LINE> for i in range(self.NUM_CLASSES): <NEW_LINE> <INDENT> y.append((x-self.u[i]) @ inv(self.sig[i]) @ (x-self.u[i]).T + np.log(det(self.sig[i]))) <NEW_LINE> <DEDENT> return np.argmin(y)
' Fill in code to evaluate model and return a prediction Prediction should be an integer specifying a class
625941ebde87d2750b860279
def __init__(self, path): <NEW_LINE> <INDENT> self.__path = os.path.abspath(path) <NEW_LINE> self.__name = os.path.basename(self.__path) <NEW_LINE> self.__bdlpath = os.path.join(self.__path, ".bdl") <NEW_LINE> self.__configpath = os.path.join(self.__bdlpath, "config.json") <NEW_LINE> self.__indexpath = os.path.join(sel...
Initializes object. Arguments: path (str): Repository path.
625941ebbe8e80087fb2111c
def __init__(self, bot): <NEW_LINE> <INDENT> super(Database, self).__init__(bot) <NEW_LINE> self.bot.dataset = dataset.connect(self.bot.config.database)
Initializes database plugin. Args: bot: The running IrcBot instance.
625941ebeab8aa0e5d26e03b
def _method_call(self, method, **kwargs): <NEW_LINE> <INDENT> session = requests.Session() <NEW_LINE> try: <NEW_LINE> <INDENT> response = session.get("http://" + self._api_address) <NEW_LINE> <DEDENT> except requests.exceptions.ConnectionError: <NEW_LINE> <INDENT> raise FantasyDataError('Error: Cannot connect to the Fa...
Call API method. Generate request. Parse response. Process errors `method` str API method url for request. Contains parameters `params` dict parameters for method url
625941ebdd821e528d63b687
def makeAveragePSFigure(averagePS, figureFileName): <NEW_LINE> <INDENT> pylab.imshow(np.log(averagePS), cmap="gray") <NEW_LINE> pylab.contour(np.log(averagePS)) <NEW_LINE> pylab.axis("off") <NEW_LINE> pylab.savefig(figureFileName)
Function that makes and save the figure with the power spectrum Args: averagePSLocal (numpy.array): the average power spectrum in an array of shape [sampleShape[0],sampleShape[1] figureFileName (str): absolute path where the figure will be saved
625941eba8370b7717052d7f
def copy_image(self, image_id, tenant_id_dst): <NEW_LINE> <INDENT> copy = _copy.ImageCopy() <NEW_LINE> return copy.copy_image(self.session, image_id, tenant_id_dst)
Copy image to a specified region. :param image_id: An identifier for the image. :param tenant_id_dst: An identifier for the image tenant for destination region. :return: :class:`~ecl.image.v2.image_copy.ImageCopy`
625941eba219f33f34628e44
def write_bulk_data(self, data, SPI_mode=CRYOMUX_MODE): <NEW_LINE> <INDENT> self.spi_rack.write_bulk_data(self.module, 7, SPI_mode, CRYOMUX_SPEED, data)
Write bulk data to the shift registers/cryo mux Allows the writing of an arbitrary amount of data. Args: data (int list): list of bytes to be written, values from 0-255 SPI_mode (int: 0-3): SPI mode to use. Defaults to CRYOMUX_MODE.
625941eb3617ad0b5ed683d8
@testing.requires_testing_data <NEW_LINE> def test_plot_projs_topomap(): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> with warnings.catch_warnings(record=True): <NEW_LINE> <INDENT> warnings.simplefilter('always') <NEW_LINE> projs = read_proj(ecg_fname) <NEW_LINE> <DEDENT> info = read_info(raw_fname) <...
Test plot_projs_topomap.
625941eb9f2886367277ad6b
def event_m50_36_x263(z39=50361130, z40=3700000): <NEW_LINE> <INDENT> DestroyObj(z39, z39, 0) <NEW_LINE> DeleteNavimeshAttribute(z40, 2) <NEW_LINE> return 0
[Execution] The image of the half-broken cocoon collapses z39: Half gangrene statue OBJ instance ID z40: Navigation change point ID
625941eb6fece00bbac2dc26
def sta(stim, stim_time, spikes, nsamples_before=30, nsamples_after=0): <NEW_LINE> <INDENT> nframe_stim, ysize, xsize = stim.shape <NEW_LINE> sta_array = np.zeros((nsamples_before+nsamples_after, ysize, xsize)) <NEW_LINE> ste_it = ste(stim, stim_time, spikes, nsamples_before, nsamples_after) <NEW_LINE> for kwindow_stim...
Compute a spike-triggered average. Parameters ---------- stim : array_like A spatiotemporal or temporal stimulus array, where time is the first dimension. stim_time : array_like The time array corresponding to the start of each frame in the stimulus. spikes : array_like A list or array of spike t...
625941eb6e29344779a62af2
def check_password(self, password): <NEW_LINE> <INDENT> return check_password_hash(self._password, password)
判断用户输入的密码和存储的 hash 密码是否相等
625941eb6aa9bd52df037289
def _GetOption(self, configType, section, option, default=None, type=None, warn_on_default=True, raw=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.userCfg[configType].has_option(section, option): <NEW_LINE> <INDENT> return self.userCfg[configType].Get(section, option, type=type, raw=raw) <NEW_LINE> <DEDE...
Return a value for configType section option, or default. If type is not None, return a value of that type. Also pass raw to the config parser. First try to return a valid value (including type) from a user configuration. If that fails, try the default configuration. If that fails, return default, with a default of ...
625941eb7d43ff24873a3186
def get_published_date(self, comment_header_string): <NEW_LINE> <INDENT> from BeautifulSoup import BeautifulSoup <NEW_LINE> from BeautifulSoup import Tag <NEW_LINE> soup = BeautifulSoup(comment_header_string) <NEW_LINE> _list = soup.findAll('div', {"class": " comment_header"}) <NEW_LINE> if len(_list) == 1: <NEW_LINE> ...
Because the published date is not contained by any tag. So we can't use xpath to select it.
625941eb24f1403a92601044
@require(iterid=int) <NEW_LINE> def codes_bufr_keys_iterator_get_name(iterid): <NEW_LINE> <INDENT> err, name = _internal.codes_c_bufr_keys_iterator_get_name(iterid, 1024) <NEW_LINE> GRIB_CHECK(err) <NEW_LINE> return name
@brief Get the name of a key from a BUFR keys iterator.  Examples: ef bufr_keys_iterator.py "bufr_keys_iterator.py" @param iterid keys iterator id created with @ref codes_bufr_keys_iterator_new @return key name to be retrieved @exception GribInternalError
625941ebc432627299f0512b
def check_fault(self): <NEW_LINE> <INDENT> self._send('RF') <NEW_LINE> response = self._receive() <NEW_LINE> return (response == '1')
Checks for faults with the bath Returns: True if faulty, else False
625941eb046cf37aa974d224
def __init__(self, tracking_id=None, status='Ok', payload=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._tracking_i...
OrderbookResponse - a model defined in OpenAPI
625941eb6fb2d068a760f587
def importFile(self, path, importFormat): <NEW_LINE> <INDENT> return self.__executor.execute(ImportCommand(self.__manager, path, importFormat))
@see: :class:`gui.app_interface.IApplication.importFile`.
625941eb07d97122c4178d79
def get_empty_inventory(self, reference_inv=None): <NEW_LINE> <INDENT> inv = inventory.Inventory() <NEW_LINE> if reference_inv is not None: <NEW_LINE> <INDENT> inv.root.revision = reference_inv.root.revision <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inv.root.revision = 'basis' <NEW_LINE> <DEDENT> return inv
Get an empty inventory. Note that tests should not depend on the revision of the root for setting up test conditions, as it has to be flexible to accomodate non rich root repositories. :param reference_inv: If not None, get the revision for the root from this inventory. This is useful for dealing with older repos...
625941eb82261d6c526ab989
def _solve_ode(t_arr: np.array, fun: Callable, fargs: Tuple, jfun: Callable, jargs: Tuple, initial_population: np.array, rtol: float = 1e-3, atol: float = 1e-15, nsteps: int = 1000, method: str = 'bdf', quiet: bool = True) -> np.array: <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> N_steps = len(t_...
Solve the ode for the times t_arr using rhs fun and jac jfun with their arguments as tuples.
625941ebd58c6744b4258140
def dfa_tv_estimator(appro, mask=None, wtype=0, j1=3, j2=7, lbda=1): <NEW_LINE> <INDENT> if mask is None: <NEW_LINE> <INDENT> mask = np.ones(appro.shape[:-1]) <NEW_LINE> <DEDENT> if appro.ndim > 2: <NEW_LINE> <INDENT> shape = (reduce(lambda a,b : a*b , (1,) + simulation.shape[:-1])) <NEW_LINE> appro = np.reshape(appro,...
This function estimate the Hurst exponent of a signal based on Daubechies' Wavelet coeffecients. It also allow l2 and tv regularisation. ----------------------------------------------------------- Input: appro: multidimensionnal signal as an np array (shape X Time) mask: if the data are taken from a masked imag...
625941eb55399d3f05588b99
def _filterQuery(self, blogId, typeId=None, creatorId=None, authorId=None, q=None): <NEW_LINE> <INDENT> sql = self.session().query(BlogPostMapped) <NEW_LINE> sql = sql.filter(BlogPostMapped.Blog == blogId) <NEW_LINE> if isinstance(q, QWithCId) and QWithCId.search in q: <NEW_LINE> <INDENT> all = self._processLike(q.sear...
Creates the general query filter for posts based on the provided parameters.
625941ebc432627299f0512c
def totext(self) ->str: <NEW_LINE> <INDENT> sreturn = '' <NEW_LINE> if self.properties.content_settings.content_encoding is None: <NEW_LINE> <INDENT> raise AzureStorageWrapException(self, 'can not convert blob {!s} to text because content_encoding is not given'.format(self.name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <I...
return blob content from StorageBlobModel instance to a string. Parameters are:
625941eb3c8af77a43ae3c88
def test_api_response_can_be_initialized_with_request_response(): <NEW_LINE> <INDENT> request_response = RequestResponseStub(payload={'test': 123}, status_code=200) <NEW_LINE> response = ApiResponse(request_response) <NEW_LINE> assert not response.error <NEW_LINE> assert response.response == request_response <NEW_LINE>...
An ApiResponse object can be initialized with a request response object.
625941ebd6c5a10208144531
def test_configmanager17(self): <NEW_LINE> <INDENT> log = logging.getLogger(__name__) <NEW_LINE> log.debug("BEGIN: unittest.TestCase.id=%r", unittest.TestCase.id(self)) <NEW_LINE> cfg = configuration.ConfigurationManager(version=1) <NEW_LINE> cfg.add_namespace("dlapp.alttree") <NEW_LINE> eok = False <NEW_LINE> try: <NE...
Call ConfigManager.get_namespace with non existent namespace.
625941eb21bff66bcd684e30
def test_failed_new(self): <NEW_LINE> <INDENT> self.assertRaises(RuntimeError, Webpage, url='http://255.255.255.255')
test_failed_new
625941eb046cf37aa974d225
def copy_plugin(self, target_placeholder, target_language, plugin_tree): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> plugin_instance, cls = self.get_plugin_instance() <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> new_plugin = CMSPlugin() <NEW_LINE> new_plugin.placeholder = target_...
Copy this plugin and return the new plugin.
625941ebbde94217f36832ce
def coord_array(self, dim): <NEW_LINE> <INDENT> from numpy import arange <NEW_LINE> return arange(self.shape[dim])*self.increments[dim]
Return an array of physical coordinates along the given dimension
625941eb4e4d5625662d48b3
def test_sees_error_message_if_username_doesnt_exist(self, user, testapp): <NEW_LINE> <INDENT> res = testapp.get('/login') <NEW_LINE> form = res.forms['login_user_form'] <NEW_LINE> form['email'] = 'unknown@unknown.com' <NEW_LINE> form['password'] = 'myprecious' <NEW_LINE> res = form.submit() <NEW_LINE> assert 'Specifie...
Show error if username doesn't exist.
625941eb1f5feb6acb0c502c
def time_slider_update(val): <NEW_LINE> <INDENT> global tims, tslider, ax_v, d_v, inps, img, fig_v, h5, k, dateList <NEW_LINE> timein = tslider.val <NEW_LINE> idx_nearest = np.argmin(np.abs(np.array(tims) - timein)) <NEW_LINE> ax_v.set_title('N = %d, Time = %s' % (idx_nearest, inps.dates[idx_nearest].strftime('%Y-%m-%d...
Update Displacement Map using Slider
625941eb2c8b7c6e89b35c9f
def has_add_permission(self, request): <NEW_LINE> <INDENT> return False
Did PaymentRequestAdmin has add permission enabled
625941ebd7e4931a7ee9e401
def user_exist(username): <NEW_LINE> <INDENT> return session.query(User).filter_by(username=username).first() is not None
Check user exist :param username: :return bool:
625941eb627d3e7fe0d69334
def try_commands(self, command_dict): <NEW_LINE> <INDENT> result = '' <NEW_LINE> x = self.x_raw <NEW_LINE> y = self.y_raw <NEW_LINE> e = self.error_raw <NEW_LINE> for key in self.extra_data_raw: <NEW_LINE> <INDENT> exec('%s = self.%s_raw' % (key, key)) <NEW_LINE> <DEDENT> xt = self.x <NEW_LINE> yt = self.y <NEW_LINE> e...
try_commands(self, command_dict) --> tuple of bool Evals the commands to locate any errors. Used to test the commands before doing the actual setting of x,y and z
625941eb3346ee7daa2b3252
def main(args=None, default_port=8000): <NEW_LINE> <INDENT> args = parser.parse_args(args) <NEW_LINE> port = args.port <NEW_LINE> if port is None: <NEW_LINE> <INDENT> port = default_port <NEW_LINE> bound = False <NEW_LINE> while not bound: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> httpd = BaseHTTPServer.HTTPServer( ...
Run the echo HTTP server.
625941eb63b5f9789fde75c8
def validate(self): <NEW_LINE> <INDENT> data = self.getData('in') <NEW_LINE> for i in range(self.ndim): <NEW_LINE> <INDENT> if i < len(data.shape): <NEW_LINE> <INDENT> shift = self.getVal(self.dim_base_name+str(-i-1)+']') <NEW_LINE> self.setAttr(self.dim_base_name+str(-i-1)+']', visible=True, val=shift) <NEW_LINE> <DED...
update the widgets based on the input arrays
625941eb293b9510aa2c3773
def move_all_to_games(self): <NEW_LINE> <INDENT> for donor in self.donor_titles: <NEW_LINE> <INDENT> print("Moving files from {0} to {1}".format(donor, self.get_donor_used_by(donor))) <NEW_LINE> if self.move_to_games(specific_donor=donor): <NEW_LINE> <INDENT> print("Success!")
Iterates through the donors and moves all games back to the games directory :return:
625941eb8e05c05ec3eea85b
def main(): <NEW_LINE> <INDENT> args = arg_parse() <NEW_LINE> angle = args.angle <NEW_LINE> N = args.N <NEW_LINE> triangleCoordinates = generateTriangles(angle, N, 'uniform') <NEW_LINE> drawTriangles(triangleCoordinates).show()
The main operation to see a random packing
625941ebd18da76e235329bf
def make_yx(fmap, h, w, n): <NEW_LINE> <INDENT> d = fmap.device() <NEW_LINE> y, x = torch.meshgrid( torch.arange(h))
We include the fmap in the inputs to be able to create the x and y tensors on the same device than the fmap.
625941eb63d6d428bbe449d3
def save_matching_basic(source_graph, target_graph, link_lists=[], colors=[], label_lists=[], name="matching", directory=None, tree=True): <NEW_LINE> <INDENT> bi_graph=nx.MultiDiGraph() <NEW_LINE> bi_graph.add_nodes_from(source_graph) <NEW_LINE> bi_graph.add_edges_from(source_graph.edges()) <NEW_LINE> bi_graph.add_node...
typically invokation (g1,g2,link_lists=[ [(a,b),(c,d)] , [(k,l),(u,v)] ],colors=["red","green"], name=...) :param source_graph: :param target_graph: :param links: new edges (e.g. modeling matching between graph nodes) :param colors: :param name: :param directory: :param tree: :return:
625941ebcb5e8a47e48b7f85
def test_default_go_install(self): <NEW_LINE> <INDENT> if not self.in_container: <NEW_LINE> <INDENT> self.example_prog_dir = tempfile.mkdtemp() <NEW_LINE> self.additional_dirs.append(self.example_prog_dir) <NEW_LINE> example_file = os.path.join(self.example_prog_dir, "hello.go") <NEW_LINE> open(example_file, "w").write...
Install eclipse from scratch test case
625941eb460517430c39465a
def get_simplified_groups_by_application(self, cr, uid, context=None): <NEW_LINE> <INDENT> model = self.pool.get('ir.model.data') <NEW_LINE> res = super(GroupsView, self).get_simplified_groups_by_application( cr, uid, context=context ) <NEW_LINE> try: <NEW_LINE> <INDENT> category = model.get_object( cr, uid, 'account_w...
return all groups classified by application (module category), as a list of pairs: [(app, kind, [group, ...]), ...], where app and group are browse records, and kind is either 'boolean' or 'selection'. Applications are given in sequence order. If kind is 'selection', the groups are given in reverse implication order.
625941eb8a349b6b435e8655
def setGridAxesThickness(self, thickness): <NEW_LINE> <INDENT> result = self.con.cmdTagList("setGridAxesThickness", imageView=self.getId(), thickness=thickness) <NEW_LINE> return result
Set grid axis thickness. Parameters ---------- thickness: integer A positive integer. Returns ------- list An error message if the thickness could not be set or an empty string if the thickness was successfully set.
625941eb21a7993f00bc81db
def get_predictions(model, ds): <NEW_LINE> <INDENT> preds = model.predict( lambda: ds.batch(1).make_one_shot_iterator().get_next()) <NEW_LINE> return np.hstack(pred['predictions'] for pred in preds)
Retrieve predictions from model.
625941eb63b5f9789fde75c9
def update_canned_message(self, canned_message_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.update_canned_message_with_http_info(canned_message_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.u...
Update canned message # noqa: E501 Update a canned message # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_canned_message(canned_message_id, async_req=True) >>> result = thread.get() :param async_req bool ...
625941ebd164cc6175783231
def createPath(self, alter_user=True): <NEW_LINE> <INDENT> self.path = os.path.abspath(self.path) <NEW_LINE> owner = self.user if self.user else User('root') <NEW_LINE> if not os.path.exists(self.path): <NEW_LINE> <INDENT> os.mkdir(self.path, 0o750) <NEW_LINE> <DEDENT> if alter_user: <NEW_LINE> <INDENT> owner_pw = pwd....
Create the directory of the partition, assign to the partition user and give it the 750 permission. In case if path exists just modifies it.
625941eb5fdd1c0f98dc0718
def test_success_fnif_nested(self): <NEW_LINE> <INDENT> template = cfnlint.decode.node.dict_node({ "Fn::If": [ "string", cfnlint.decode.node.dict_node({"Test": "True"}, (0, 1), (2, 3)), cfnlint.decode.node.dict_node({ "Fn::If": [ "nested", cfnlint.decode.node.dict_node({"NestedTest": "False,True"}, (0, 1), (2, 3)), Fal...
Test List Object
625941eb3eb6a72ae02ec9cd
def build(self) -> Optional[Bundle]: <NEW_LINE> <INDENT> bundle_objects = [self.author] <NEW_LINE> bundle_objects.extend(self.object_markings) <NEW_LINE> intrusion_sets = self._create_intrusion_sets() <NEW_LINE> bundle_objects.extend(intrusion_sets) <NEW_LINE> kill_chain_phases = self._create_kill_chain_phases() <NEW_L...
Build indicator bundle.
625941eb45492302aab5e7ab
def get_text(edus, movesedus): <NEW_LINE> <INDENT> txt = "" <NEW_LINE> for i in movesedus: <NEW_LINE> <INDENT> txt += edus[i] <NEW_LINE> <DEDENT> return txt.replace("<S>", "")
rebuilds text from edus
625941ebbaa26c4b54cb15fd
def threshold_labels(sample, threshold=.5, targets=None): <NEW_LINE> <INDENT> data, label = sample <NEW_LINE> assert targets is not None, 'Please specify targets for threshold_labels. Otherwise it will do nothing.' <NEW_LINE> assert type(label) is list or type(label) is pd.Series, 'Label from tup must be a numpy Series...
Maps continuous labels to binary labels.
625941ebfbf16365ca6f66b1
def generate(self): <NEW_LINE> <INDENT> self.update_progress('Loading Markdown...') <NEW_LINE> markdown_filename = self.markdown_path_input.text() <NEW_LINE> try: <NEW_LINE> <INDENT> with open(markdown_filename, 'r') as f: <NEW_LINE> <INDENT> input_text = f.read() <NEW_LINE> print(input_text) <NEW_LINE> <DEDENT> <DEDEN...
Generate the HTML file.
625941eb6fb2d068a760f588
def __str__(self): <NEW_LINE> <INDENT> return self.name
Ciąg do reprezentowania obiektu Modelu.
625941eb7d847024c06be7a3
def disable_save_reply_handlers(self): <NEW_LINE> <INDENT> self.reply_saver = None
Disable saving next step handlers (by default saving disable)
625941eb0a50d4780f667379
def dispatch_commit(self, domain, instance, field, value): <NEW_LINE> <INDENT> self._client.publish('{}/{}/{}/{}/{}'.format( self._prefix, self._unitname, domain, field, instance), value)
Dispatch a value commit.
625941eb3317a56b8693a12f
def prune_min_cost_comp(self): <NEW_LINE> <INDENT> def recurse_compute_cost(node, path_to_here): <NEW_LINE> <INDENT> node_weighted_impurity = node.impurity * node.num_samples / self.num_samples_total <NEW_LINE> if node.left != None: <NEW_LINE> <INDENT> left_leaves_weighted_impurity, left_num_leaves = recurse_compute_co...
Performs one iteration of pruning for the minimal cost complexity approach. See http://mlwiki.org/index.php/Cost-Complexity_Pruning for details.
625941eb66673b3332b92574
def _get_path_config(self, url: str) -> dict: <NEW_LINE> <INDENT> rel_path_parts = self.get_relative_path_parts(url) <NEW_LINE> for path_template, path_config in self.spec['paths'].items(): <NEW_LINE> <INDENT> path_template_bits = path_to_bits(path_template, transform=noop) <NEW_LINE> if len(path_template_bits) != len(...
Introspect the API spec to find the matching operation spec. :param url: The API endpoint to look up the resource for. Should be qualified as much as the spec['servers'] URLs.
625941ebd10714528d6001cc
def get_imap(mailbox='INBOX'): <NEW_LINE> <INDENT> imap = IMAP4_SSL(settings.EMAIL_HOST) <NEW_LINE> imap.login(settings.EMAIL_USER, settings.EMAIL_PASSWORD) <NEW_LINE> imap.select(mailbox) <NEW_LINE> return imap
Instantiate a new IMAP object, login, and connect to a mailbox.
625941eb851cf427c661a9ed
def __init__(self, state, top_left): <NEW_LINE> <INDENT> self._state = state <NEW_LINE> self.top_left = top_left <NEW_LINE> self.team = None
Do not touch this function. It initializes sectors before the game starts
625941eb94891a1f4081bf8e
def test_VT_MovesDoesNotScrollOutsideLeftRight(self): <NEW_LINE> <INDENT> esccmd.DECSTBM(2, 5) <NEW_LINE> esccmd.DECSET(esccmd.DECLRMM) <NEW_LINE> esccmd.DECSLRM(2, 5) <NEW_LINE> esccmd.CUP(Point(3, 5)) <NEW_LINE> escio.Write("x") <NEW_LINE> esccmd.CUP(Point(6, 5)) <NEW_LINE> escio.Write(VT) <NEW_LINE> AssertEQ(GetCurs...
Cursor moves down but won't scroll when outside left-right region.
625941ebcad5886f8bd274bb
def tell(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.stream.tell() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return super(NamedStream, self).tell()
Return the current stream position.
625941eb9f2886367277ad6c
def __init__(self, user_data: pd.DataFrame, list_items: ListItems, K=5): <NEW_LINE> <INDENT> self.K = K <NEW_LINE> self.list_items = list_items <NEW_LINE> self.user_ids = user_data.id.values <NEW_LINE> user_data.drop(columns=UserModel.COLUMNS_TO_DROP, inplace=True, errors='ignore') <NEW_LINE> user_data = self.__encode(...
:param user_data: User profiles to use on train :param K: number of neighbors to use
625941eb2c8b7c6e89b35ca0
def perform_create(self, serializer: PostSerializer): <NEW_LINE> <INDENT> serializer.save(creator=self.request.user)
link the user to the post that he made when the post is created. :param serializer: The post serializer.
625941eb21a7993f00bc81dc
def sort(self, col, order): <NEW_LINE> <INDENT> self.emit(SIGNAL("layoutAboutToBeChanged()")) <NEW_LINE> self.mylist = sorted(self.mylist, key=operator.itemgetter(col)) <NEW_LINE> if order == Qt.DescendingOrder: <NEW_LINE> <INDENT> self.mylist.reverse() <NEW_LINE> <DEDENT> self.current_sort_column = col <NEW_LINE> self...
sort table by given column number col
625941ebe64d504609d74d23
def findDurableSubscribersForDestination(self, destination): <NEW_LINE> <INDENT> query = jmx.QueryNested(destination.getObjectName(), 'DurableSubscribers') <NEW_LINE> nameAttr = self._attributeNameFor('Name') <NEW_LINE> query.addAttributes(nameAttr) <NEW_LINE> subscribers = [] <NEW_LINE> for item in self._getProvider()...
@types: jms.Destination -> list(jms.Subscriber) @raise jmx.AccessDeniedException: @raise jmx.ClientException:
625941eb9b70327d1c4e12bb
def increment_number_served(self): <NEW_LINE> <INDENT> add = int(input("请输入增加的就餐人数")) <NEW_LINE> self.number_served = self.number_served + add <NEW_LINE> print("该餐厅目前服务的人数为:" + str(self.number_served))
增加就餐人数并且打印
625941ebbf627c535bc136b2
def state_to_int(n): <NEW_LINE> <INDENT> n += np.ones(4) <NEW_LINE> return n[0]*4**3 + n[1]*4**2 + n[2]*4 + n[3]
Convert a state vector (a numpy array of size 4) to a unique STATENUMBER between 0 and 255. Example: In: state_to_int([1,1,0,1]) Out: 166 Args: n: np.array of shape (1,4) Returns: an integer between 0 and 255
625941eb23e79379d52eea40
def Product(*args): <NEW_LINE> <INDENT> args = _get_args(args) <NEW_LINE> if __debug__: <NEW_LINE> <INDENT> _z3_assert(len(args) > 0, "Non empty list of arguments expected") <NEW_LINE> <DEDENT> ctx = _ctx_from_ast_arg_list(args) <NEW_LINE> if __debug__: <NEW_LINE> <INDENT> _z3_assert(ctx != None, "At least one of th...
Create the product of the Z3 expressions. >>> a, b, c = Ints('a b c') >>> Product(a, b, c) a*b*c >>> Product([a, b, c]) a*b*c >>> A = IntVector('a', 5) >>> Product(A) a__0*a__1*a__2*a__3*a__4
625941ebdc8b845886cb5a1a
def duration_to_timedelta(duration): <NEW_LINE> <INDENT> num = int(duration[:-1]) <NEW_LINE> if duration.endswith('s'): <NEW_LINE> <INDENT> return datetime.timedelta(seconds=num) <NEW_LINE> <DEDENT> elif duration.endswith('m'): <NEW_LINE> <INDENT> return datetime.timedelta(minutes=num) <NEW_LINE> <DEDENT> elif duration...
Converts a `duration` into a timedelta object based on the following scheme. ========= ======= =================== Character Meaning Example ========= ======= =================== s Seconds '60s' -> 60 Seconds m Minutes '5m' -> 5 Minutes h Hours '24h' -> 24 Ho...
625941eb82261d6c526ab98a
def runCommands(cmds, localTempDir, inPipes=None, outPipes=None, errPipes=None): <NEW_LINE> <INDENT> if inPipes is None: <NEW_LINE> <INDENT> inPipes = [None] * len(cmds) <NEW_LINE> <DEDENT> if outPipes is None: <NEW_LINE> <INDENT> outPipes = [None] * len(cmds) <NEW_LINE> <DEDENT> if errPipes is None: <NEW_LINE> <INDENT...
Run commands from CMDS list
625941eb009cb60464c63891
def _fetch_from_gr(filename): <NEW_LINE> <INDENT> for i in range(0, len(GLOBAL_REQUIREMENTS_LOCATIONS)): <NEW_LINE> <INDENT> url = GLOBAL_REQUIREMENTS_LOCATIONS[i] + filename <NEW_LINE> LOG.debug("Try to obtain %s from %s" % (filename, url)) <NEW_LINE> try: <NEW_LINE> <INDENT> return requests.get(url).text <NEW_LINE> <...
Try to fetch data from OpenStack global-requirements repo
625941eb099cdd3c635f113c
@cronjobs.register <NEW_LINE> def escalate_questions(): <NEW_LINE> <INDENT> if settings.STAGE: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> qs = Question.objects.needs_attention().exclude( tags__slug__in=[config.ESCALATE_TAG_NAME]) <NEW_LINE> qs = qs.filter(locale=settings.WIKI_DEFAULT_LANGUAGE) <NEW_LINE> qs = qs.ex...
Escalate questions needing attention. Escalate questions where the status is "needs attention" and still have no replies after 24 hours, but not that are older than 25 hours (this runs every hour).
625941ebf9cc0f698b140ada
def grad(outputs, inputs, grad_outputs=None, retain_graph=None, create_graph=None, only_inputs=True): <NEW_LINE> <INDENT> outputs = (outputs,) if isinstance(outputs, Variable) else tuple(outputs) <NEW_LINE> inputs = (inputs,) if isinstance(inputs, Variable) else tuple(inputs) <NEW_LINE> if grad_outputs is None: <NEW_LI...
Computes and returns the sum of gradients of outputs w.r.t. the inputs. ``grad_outputs`` should be a sequence of length matching ``output`` containing the pre-computed gradients w.r.t. each of the outputs. If an output doesn't require_grad, then the gradient can be ``None``). Gradients can be given as Tensors when one...
625941ebd268445f265b5352
def read_content(self): <NEW_LINE> <INDENT> read = self.read() <NEW_LINE> if read != {}: <NEW_LINE> <INDENT> return read['Content'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return read
Funcion para leer el contenido de un archivo json (datos json)
625941eb3d592f4c4ed1d543
def GetParams(self): <NEW_LINE> <INDENT> input_names = ["input", "input2"] <NEW_LINE> input_dims = [[12, 5], [12, 5, 2, 2]] <NEW_LINE> output_name = "output" <NEW_LINE> g = ops.Graph() <NEW_LINE> with g.as_default(): <NEW_LINE> <INDENT> outputs = [] <NEW_LINE> for i in range(2): <NEW_LINE> <INDENT> x = array_ops.placeh...
Test for rank 2 input in TF-TRT.
625941eb07d97122c4178d7a
def rotateRight(self, head, k): <NEW_LINE> <INDENT> if not head or not k or not head.next: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> l = 0 <NEW_LINE> length = head <NEW_LINE> while length: <NEW_LINE> <INDENT> l += 1 <NEW_LINE> length = length.next <NEW_LINE> <DEDENT> k = k % l <NEW_LINE> if not k: <NEW_LINE> ...
:type head: ListNode :type k: int :rtype: ListNode
625941ebd6c5a10208144532
def step(t_init, T, A, time, offset=0, var=None): <NEW_LINE> <INDENT> if var is None: <NEW_LINE> <INDENT> step_input = np.ones_like(time) * float(offset) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if np.size(var) == np.size(time): <NEW_LINE> <INDENT> step_input = float(offset) + var <NEW_LINE> <DEDENT> else: <NEW_LI...
Step input. Parameters ---------- t_init : float Initial time (s). T : float Input signal length (s). A : float Peak to peak amplitude. time : array_like Time simulation vector (s). offset : float Signal offset. var : array_like, opt Array containing previous perturbations. Signal will be added...
625941ebcb5e8a47e48b7f86