code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _categorical_preprocess(self, df, cat_feature, how="ohe"): <NEW_LINE> <INDENT> assert how in ["ohe_encoder", "label_encoder", "target_encoder"] <NEW_LINE> if how == "ohe_encoder": <NEW_LINE> <INDENT> df.drop(cat_feature, 1, inplace=True) <NEW_LINE> df = df.join(pd.get_dummies(df[cat_feature], prefix=cat_feature)) <... | Categorical variables preprocess | 625941ecd6c5a1020814455a |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941ec5510c4643540f8e2 |
def write_to_file(self): <NEW_LINE> <INDENT> debug("Writing results out to: %s" % self.filename) <NEW_LINE> self.integrity_check() <NEW_LINE> to_write = { "config": self.config.text, "wallclock_times": self.wallclock_times, "core_cycle_counts": self.core_cycle_counts, "aperf_counts": self.aperf_counts, "mperf_counts": ... | Serialise object on disk. | 625941ecbe383301e01b5987 |
def get_machine_group_applied_configs(self, project_name, group_name): <NEW_LINE> <INDENT> headers = {} <NEW_LINE> params = {} <NEW_LINE> resource = "/machinegroups/" + group_name + "/configs" <NEW_LINE> (resp, header) = self._send("GET", project_name, None, resource, params, headers) <NEW_LINE> return GetMachineGroupA... | get the logtail config names applied in a machine group
Unsuccessful operation will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type group_name: string
:param group_name: the group name list
:return: GetMachineGroupAppliedConfigResponse
:raise: LogException | 625941ec3317a56b8693a157 |
@numba.jit(nopython=True, cache=True) <NEW_LINE> def get_max_ks_stat(full_data1, full_data2): <NEW_LINE> <INDENT> n1, p1 = full_data1.shape <NEW_LINE> n2, p2 = full_data2.shape <NEW_LINE> assert p1 == p2 <NEW_LINE> ks_stats = np.zeros(p1) <NEW_LINE> for ii in range(p1): <NEW_LINE> <INDENT> data1 = np.sort(full_data1[:,... | get_max_ks_stat
Parameters
----------
full_data1 : np.array
Of shape (n, d)
full_data2 : np.array
Of shape (n, d)
Returns
------- | 625941ec167d2b6e312190a0 |
def _player_loc(): <NEW_LINE> <INDENT> return _to_my_vec3(_get_mc().player.getTilePos()) | Return the player's location. | 625941ec96565a6dacc8fbd5 |
def determinant(self): <NEW_LINE> <INDENT> p = self._prime <NEW_LINE> return prod([ p**(s[0]*s[1]) for s in self._symbol ]) | Returns the (p-part of the) determinant (square-class) of the
Hessian matrix of the quadratic form (given by regarding the
integral symmetric matrix which generated this genus symbol as
the Gram matrix of Q) associated to this local genus symbol.
INPUT:
None
OUTPUT:
an integer
EXAMPLES::
sage: from sage.quadr... | 625941ecdc8b845886cb5a42 |
def pytest_funcarg__server_socket(request): <NEW_LINE> <INDENT> read_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> read_socket.bind(("localhost", 9562)) <NEW_LINE> request.addfinalizer(lambda: read_socket.close()) <NEW_LINE> return read_socket | Funcarg to create a UDP socket that can be communicated with. Why UDP
when the httpserver we'll be testing is tcp? So we don't have to set up an
entire socket server using listen and accept. We're testing iostream now,
not httpserver.
A better solution is probably to create a mock object. | 625941ecaad79263cf390f54 |
def shear(image, background, x, y): <NEW_LINE> <INDENT> if not isinstance(background, Color): <NEW_LINE> <INDENT> raise TypeError('background must be a wand.color.Color instance, ' 'not ' + repr(background)) <NEW_LINE> <DEDENT> elif not isinstance(x, numbers.Real): <NEW_LINE> <INDENT> raise TypeError('x has to be a num... | slides one edge of an image along the X or Y axis,
creating a parallelogram. An X direction shear slides an edge along the X
axis, while a Y direction shear slides an edge along the Y axis.
The amount of the shear is controlled by a shear angle.
For X direction shears, x_shear is measured relative to the Y axis,
and s... | 625941ecd486a94d0b98e652 |
def decrochage_arbre(self): <NEW_LINE> <INDENT> if (self.vehicule_precedent is None): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.simulateur.add_listener(self) <NEW_LINE> self.vehicule_precedent.supp_vehicule_suivant(self) <NEW_LINE> self.vehicule_precedent = None <NEW_LINE> self.propager_racine(self) | Se décroche de son arbre et donne l'information aux fils
# @author : Marcus | 625941ec66673b3332b9259c |
def _parse(self): <NEW_LINE> <INDENT> for child in self.xml_measure: <NEW_LINE> <INDENT> if child.tag == 'attributes': <NEW_LINE> <INDENT> self._parse_attributes(child) <NEW_LINE> <DEDENT> elif child.tag == 'backup': <NEW_LINE> <INDENT> self._parse_backup(child) <NEW_LINE> <DEDENT> elif child.tag == 'direction': <NEW_L... | Parse the <measure> element. | 625941ec5fcc89381b1e1bce |
def __iter__(self): <NEW_LINE> <INDENT> pass | Iterates on all components of a Maya api FloatPoint | 625941ece76e3b2f99f3ad0e |
def refresh_parset(project_id, parset_id, resetprevalence): <NEW_LINE> <INDENT> def update_project_fn(project): <NEW_LINE> <INDENT> parset = parse.get_parset_from_project(project, parset_id) <NEW_LINE> parset_name = parset.name <NEW_LINE> project.refreshparset(name=parset_name, resetprevalence=resetprevalence) <NEW_LIN... | Refresh parset from data | 625941ec4c3428357757c830 |
def _request_naws(self): <NEW_LINE> <INDENT> self._iac_do(NAWS) <NEW_LINE> self._note_reply_pending(NAWS, True) | Request to Negotiate About Window Size. See RFC 1073. | 625941ec16aa5153ce362984 |
def data_entry2dict(self, missing_val=''): <NEW_LINE> <INDENT> result = ['Identifier', 'Title', 'AppVersion', 'Arguments', 'ResultOf', 'Description', 'Scale', 'Proportion', 'DisplayFormat'] <NEW_LINE> res_ignore = set(['Arguments']) <NEW_LINE> data_entry = ['Identifier', 'Value', 'RawString', 'JSON'] <NEW_LINE> dat_ign... | For a given xml result file from pts/OpenBenchmarking.org, convert
the Result tags to a Pandas DataFrame. This means that the data
contained in the Result tag will now be replicated for each of the
Data/Entry tags for that given test result. | 625941ec26068e7796caf1f3 |
def getStats(self): <NEW_LINE> <INDENT> url = "%s://%s:%d/%s" % (self._proto, self._host, self._port, self._monpath) <NEW_LINE> response = util.get_url(url, self._user, self._password) <NEW_LINE> stats = {} <NEW_LINE> for line in response.splitlines(): <NEW_LINE> <INDENT> mobj = re.match('([\w\s]+):\s+(\w+)$', line) <N... | Query and parse Web Server Status Page.
| 625941ec0a50d4780f6673a2 |
def __del__(self): <NEW_LINE> <INDENT> self.__stop() | This desctuctor method will make sure the threads are alldone before finishing | 625941ec187af65679ca562b |
def enQueue(self, value: int) -> bool: <NEW_LINE> <INDENT> if self.isFull() : return False <NEW_LINE> self.queue[self.tail] = value <NEW_LINE> self.tail = (self.tail + 1) % self.l <NEW_LINE> self.size += 1 <NEW_LINE> return True | Insert an element into the circular queue. Return true if the operation is successful. | 625941ec0383005118ecfaec |
def MakeDict(self): <NEW_LINE> <INDENT> return {"header": self.__header.MakeDict(), "data": self.__data.MakeDict()} | Get dictionary representation of the overwatch histogram
:return: Dictionary representation of the histogram
:rtype: Dictionary | 625941ec5fcc89381b1e1bcf |
def cross_recurrence_matrix( xps, yps ): <NEW_LINE> <INDENT> return recurrence_matrix( xps, yps ) | Cross reccurence matrix.
Args:
xps (numpy.array):
yps (numpy.array):
Returns:
numpy.array : A 2D numpy array. | 625941ec76d4e153a657f03e |
def main(): <NEW_LINE> <INDENT> app = wx.App() <NEW_LINE> mainFrame = GenDisplayFrame(None, 410, 230) <NEW_LINE> app.MainLoop() | Main function used for local test. | 625941ec2ae34c7f2600d63c |
def set_enabled_units(units): <NEW_LINE> <INDENT> context = _UnitContext( equivalencies=get_current_unit_registry().equivalencies) <NEW_LINE> get_current_unit_registry().set_enabled_units(units) <NEW_LINE> return context | Sets the units enabled in the unit registry.
These units are searched when using
`UnitBase.find_equivalent_units`, for example.
This may be used either permanently, or as a context manager using
the ``with`` statement (see example below).
Parameters
----------
units : list of sequences, dicts, or modules containing ... | 625941ecfbf16365ca6f66da |
def create_user(username, email, password, is_superuser=False, is_staff=True, is_active=True): <NEW_LINE> <INDENT> if not password.startswith('pbkdf2_'): <NEW_LINE> <INDENT> password = make_password(password) <NEW_LINE> <DEDENT> add_user = User.objects.create(**{ 'password': password, 'last_login': None, 'is_superuser'... | 创建用户
例子:
from ilds.django.user import create_user
create_user(username='admin', email='admin@qq.com', password='123456', is_superuser=False, is_staff=True)
:param username: 用户名
:param email: 邮箱
:param password: 密码,支持直接设置秘钥,秘钥前缀是 pbkdf2_
:param is_superuser: 是否是超级用户
:param is_staff: 用户是否可以登录到管理站点
:param is_active: 用户是... | 625941ec24f1403a9260106d |
def simulate_strain_and_nutrient_condition(ns, pset={},mut={}): <NEW_LINE> <INDENT> model = sim.get_simulator(modelpath = MODELPATH, simulator="cpp", executable=SIMARGS['executable']) <NEW_LINE> tmax = 90 <NEW_LINE> if ns['name'] == 'LCLN': <NEW_LINE> <INDENT> preshift = {'Carbon':1.0,"Glutamine_ext":1.0,"ATP":1.0} <NE... | Simulates a single strain using a parameter set if specified.
Requires a nutrient condition specification | 625941ecfb3f5b602dac3ba4 |
def postCommand(self, headerData: dict, command: dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> thisEnd = self.base_url + "/v1.0/devices/[id]/commands".replace("[id]", self.id) <NEW_LINE> resp = r.post(url=thisEnd, headers=headerData, data=json.dumps(command)) <NEW_LINE> if resp.json()['success'] == False: <NEW_LI... | Sends a post request to Tuya API for this device affecting it with the given command
Args:
headerData (dict): The data needed for the header to be sent to Tuya API
command (dict): The command to affect the device with
Raises:
Exception: Raises an exception on a failed call to Tuya API | 625941ec23e79379d52eea69 |
def train_model(model, X_train, train_files, X_test, test_files): <NEW_LINE> <INDENT> model.fit(X_train.toarray(), train_files.target, batch_size = 20, nb_epoch = 4, validation_data=(X_test.toarray(), test_files.target)) <NEW_LINE> test_score, test_accuracy = model.evaluate(X_test.toarray(), test_files.target, batch_si... | train the compiled ann with the data | 625941ec30c21e258bdfa9af |
def set_draw_callback(self,callback): <NEW_LINE> <INDENT> self.__drawcallback=callback | Sets draw callback | 625941ec55399d3f05588bc3 |
def testGetMaximum(self): <NEW_LINE> <INDENT> theList = [2, 7, 26, 25, 19, 17, 1, 90, 3, 36] <NEW_LINE> MaxHeapPriorityQueue.buildMaxHeap(theList) <NEW_LINE> expected = 90 <NEW_LINE> maxValue = MaxHeapPriorityQueue.getMaximum(theList) <NEW_LINE> self.assertEqual(expected, maxValue) | This test will verify that it pulls the correct max value | 625941eca8370b7717052da9 |
def search(self, word): <NEW_LINE> <INDENT> return self.search_from(word, 0, self.root) | Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool | 625941ec236d856c2ad44ced |
def to_escaped(value): <NEW_LINE> <INDENT> if hasattr(value, '__html__'): <NEW_LINE> <INDENT> value = value.__html__() <NEW_LINE> <DEDENT> if is_escaped(value): <NEW_LINE> <INDENT> return as_escaped(_helpers.to_str(value)) <NEW_LINE> <DEDENT> return as_escaped(_helpers.escape(_helpers.to_str(value))) | convert any value into string and escape it.
if value is already marked as escaped, don't escape it. | 625941ecd486a94d0b98e653 |
def get_top_tags(tags): <NEW_LINE> <INDENT> return Counter(tags).most_common(TOP_NUMBER) | Get the TOP_NUMBER of most common tagsself.
Hint: use most_common method of Counter (already imported) | 625941ec92d797404e304698 |
def fibMatrix(n): <NEW_LINE> <INDENT> def prevPowTwo(n): <NEW_LINE> <INDENT> if ((n & -n) == n): <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n -= 1 <NEW_LINE> n |= n >> 1 <NEW_LINE> n |= n >> 2 <NEW_LINE> n |= n >> 4 <NEW_LINE> n |= n >> 8 <NEW_LINE> n |= n >> 16 <NEW_LINE> n += 1 <NEW_LI... | Matrix-based computation of the n fibonacci number.
f(0) = 1, f(1) = 1, f(2) = 2 | 625941ece1aae11d1e74a1c8 |
def mergeNpmDeps(base, module, modulename): <NEW_LINE> <INDENT> items = ['dependencies', 'devDependencies'] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> base_dep = base.get(item, None) <NEW_LINE> module_dep = module.get(item, None) <NEW_LINE> conflicts = None <NEW_LINE> if base_dep and module_dep: <NEW_LINE> <INDE... | Adds dependencies from module into base and reports any conflicts that happen. | 625941ec7cff6e4e81117e91 |
def _critic_objective(self, samples_data): <NEW_LINE> <INDENT> obs = samples_data["observation"] <NEW_LINE> actions = samples_data["action"] <NEW_LINE> rewards = samples_data["reward"].flatten() <NEW_LINE> terminals = samples_data["terminal"].flatten() <NEW_LINE> next_obs = samples_data["next_observation"] <NEW_LINE> w... | Compute the Q-function/critic loss.
Args:
samples_data (dict): Transitions(S,A,R,S') that are sampled from
the replay buffer. It should have the keys 'observation',
'action', 'reward', 'terminal', and 'next_observations'.
Note:
samples_data's entries should be torch.Tensor's with the following
... | 625941ec4e696a04525c9959 |
def custom_replace(s, to_replace): <NEW_LINE> <INDENT> ge = s[s.ge(0)] <NEW_LINE> if ge.isnull().all(): <NEW_LINE> <INDENT> new = {k: (np.nan if isinstance(v, str) else v) for k, v in to_replace.items()} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new = {} <NEW_LINE> for k, v in to_replace.items(): <NEW_LINE> <INDENT... | Replace with specified scalars or mapped aggregates. | 625941ecd7e4931a7ee9e42b |
def two_dose_immunity(birth_year: int) -> float: <NEW_LINE> <INDENT> years_after_age_six = (current_year - birth_year) - 6 <NEW_LINE> if years_after_age_six < 0: <NEW_LINE> <INDENT> years_after_age_six = 0 <NEW_LINE> <DEDENT> return two_dose_init_immunity * (e ** (two_dose_waning_imm_exp_coeff * years_after_age_six)) | Returns a probability of immunity given two doses of mumps vaccine.
:param birth_year: int
:return: float 0<=x<=1 | 625941ec0fa83653e46574c4 |
def logprob(preds, lbels): <NEW_LINE> <INDENT> preds[preds < 1e-10] = 1e-10 <NEW_LINE> return np.sum(np.multiply(lbels, -np.log(preds))) / lbels.shape[0] | Log-probability of the true labels in a predicted batch | 625941ec23849d37ff7b3597 |
def is_nested_stack(logger, stack_list, stack_name): <NEW_LINE> <INDENT> logger.debug("Checking if stack %s is a nested stack" % stack_name) <NEW_LINE> for stack in stack_list: <NEW_LINE> <INDENT> if stack_name.startswith(stack + '-'): <NEW_LINE> <INDENT> logger.debug("Stack %s is a nested stack" % stack_name) <NEW_LIN... | A deleted nested stack has no ParentId property, hence that cannot be used to identify a deleted stack as
a nested stack. Using the following method instead: if the stack name starts with the name of any other
stack (which would be the root stack) followed by a dash, it is a nested stack. | 625941ec442bda511e8be91d |
def get_name (self): <NEW_LINE> <INDENT> return self.__name | Function to get the name of the register | 625941ec956e5f7376d71378 |
def __init__(self): <NEW_LINE> <INDENT> self._read_fd, self._write_fd = os.pipe() | Opens the pipe. | 625941ecd53ae8145f87a772 |
def merge_by_1digitdiff(df1, df2, df1_dob = 'dob', df2_dob = 'dob'): <NEW_LINE> <INDENT> df1['year'] = df1[df1_dob].astype('datetime64[ns]').dt.year <NEW_LINE> df2['year'] = df2[df2_dob].astype('datetime64[ns]').dt.year <NEW_LINE> df1['df1_dob'] = df1[df1_dob].astype('str') <NEW_LINE> df2['df2_dob'] = df2[df2_dob].asty... | Merge the student and defendant records by exact matching these 2 fields:
"firstname_clean", "lastname_clean", "year" and
then any date entries that only differ by less than 2 digits.
:param DataFrame df1: The left dataframe
:param DataFrame df2: The right dataframe
:return: the matched dataframe, matching % betwee... | 625941ec462c4b4f79d1dbdb |
def _parse_example_proto(example_serialized): <NEW_LINE> <INDENT> keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='png'), 'image/class/label': tf.FixedLenFeature( [], tf.int64, default_value=tf.zeros([], dtype=tf.... | Parses an Example proto containing a training example of an image.
The output of the build_image_data.py image preprocessing script is a
dataset
containing serialized Example protocol buffers. Each Example proto
contains
the following fields (values are included as examples):
tf.train.Example(features=tf.trai... | 625941ec1f5feb6acb0c5055 |
def find_gdp(line, index): <NEW_LINE> <INDENT> begin = 76 +12*index <NEW_LINE> end = begin + 12 <NEW_LINE> gdp_num = float(line[begin:end]) <NEW_LINE> return gdp_num | Use the index to find the gdp value in the line | 625941ecbe8e80087fb21147 |
def initialize_data(): <NEW_LINE> <INDENT> apartment_expense_data = create_apartment_expense_data() <NEW_LINE> populate_apartment_expense_data(apartment_expense_data) <NEW_LINE> changes_stack = create_changes_stack() <NEW_LINE> return apartment_expense_data, changes_stack | Initializes the data instance and the changes stack
:return: tuple - A tuple containing the apartment data instance wit the default valuesand the changes stack | 625941ecfbf16365ca6f66db |
def __str__( self ): <NEW_LINE> <INDENT> if self.canonical: <NEW_LINE> <INDENT> octave_str = "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> octave_str = str(self.octave) <NEW_LINE> <DEDENT> return self.glyph + octave_str | return glyph + octave as string | 625941ecb7558d58953c5415 |
def even_or_odd(n): <NEW_LINE> <INDENT> if n % 2 == 0: <NEW_LINE> <INDENT> return 'Even' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Odd' | Return a string odd or even for odd or even values of n. | 625941ecb545ff76a8914322 |
def _on_browse_for_publishes(self, new_project_form): <NEW_LINE> <INDENT> loader_app = self._app.engine.apps.get("tk-multi-loader2") <NEW_LINE> if not loader_app: <NEW_LINE> <INDENT> raise TankError( "The tk-multi-loader2 app needs to be available to browse for publishes!" ) <NEW_LINE> <DEDENT> publish_types = self._ap... | Called when the user clicks the 'Add Publishes' button in the new
project form. Opens the loader so that the user can select a publish
to be loaded into the new project.
:param new_project_form: The new project form that the button was
clicked in | 625941ec7cff6e4e81117e92 |
def log_response(self, cmd, re, info=None): <NEW_LINE> <INDENT> cmd = replace_eol_func(cmd) <NEW_LINE> ncmd = prep_str(cmd) <NEW_LINE> if ncmd: <NEW_LINE> <INDENT> cmd = ncmd <NEW_LINE> <DEDENT> if re and len(re) > 100: <NEW_LINE> <INDENT> re = "{}...".format(re[:97]) <NEW_LINE> <DEDENT> if info and info != "": <NEW_LI... | Log command and response as an INFO message | 625941ece8904600ed9f2442 |
def randomly_generate_new_alien_ship(gamestate): <NEW_LINE> <INDENT> random_velocity_angle = random.randint(0, 359) <NEW_LINE> random_alien_x_velocity, random_alien_y_velocity = rotate_these_points_around_that_point(0, -5, 0, 0, random_velocity_angle) <NEW_LINE> random_alien_size = random.sample([20, 40], 1)[0] ... | Create a new AlienShip object with randomly
generated features at the edge of the map. | 625941ecd8ef3951e3243a4a |
def get_judgment(self, job, judgment_id): <NEW_LINE> <INDENT> return Judgment( job, client=self, **self.jobs[job.id].judgments[judgment_id]() ) | Get Judgment ``judgment_id`` for ``job``. | 625941ec44b2445a3393259e |
def nit(self): <NEW_LINE> <INDENT> return self._nit | returns number of computed iterations | 625941ec4e4d5625662d48dd |
def testCmsNamePatterntoSE(self): <NEW_LINE> <INDENT> target = [u'T2_XX_SiteA', u'T2_XX_SiteB', u'T2_XX_SiteC'] <NEW_LINE> results = self.mySiteDB.cmsNametoSE("%T2_XX") <NEW_LINE> self.failUnless(sorted(results) == sorted(target)) | Tests CmsNamePatterntoSE | 625941ec91af0d3eaac9bf2a |
def CreateUtcEventTimes(self, dates): <NEW_LINE> <INDENT> pass | CreateUtcEventTimes(self: ITimeRule, dates: IEnumerable[DateTime]) -> IEnumerable[DateTime] | 625941ec10dbd63aa1bd30ae |
def gray2rgb(img, cmap='gray'): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> import numpy as np <NEW_LINE> def standardize(x): return (x-x.min())/(x.max()-x.min()) <NEW_LINE> if np.abs(img).max() > 1: <NEW_LINE> <INDENT> img = standardize(img) <NEW_LINE> <DEDENT> cmap = plt.get_cmap(cmap) <NEW_LINE> i... | Given a grayscale image, returns rgb equivalent
Inputs:
cmap - Colormap; can be specified as 'gray', 'jet',
or as plt.cm.Accent, etc | 625941ecb830903b967e9e12 |
def calculate_group_sizes(self, input_shape): <NEW_LINE> <INDENT> self.included_weight_groups = [ all(dim != 0 for dim in group_shape[1:]) for group_shape in input_shape ] <NEW_LINE> num_groups = np.sum(self.included_weight_groups) <NEW_LINE> if num_groups < 1: <NEW_LINE> <INDENT> raise ValueError( "There must be at le... | Calculates the output size for each input group. The results are stored in two variables:
self.included_weight_groups: if the corresponding entry is True then the input group
is valid and should be used.
self.weight_sizes: the size of the output from this group.
Args:
input_shape (list of list of i... | 625941ec6e29344779a62b1d |
def get_organizations(self): <NEW_LINE> <INDENT> organizations = {} <NEW_LINE> for record in self.records: <NEW_LINE> <INDENT> if 'creators' in record['data']['metadata']: <NEW_LINE> <INDENT> creators_list = record['data']['metadata']['creators'] <NEW_LINE> for creator in creators_list: <NEW_LINE> <INDENT> if creator['... | extract organizations of creators and associated IDs of records | 625941ecbde94217f36832f9 |
def isna(df): <NEW_LINE> <INDENT> op = DataFrameCheckNA(positive=True, use_inf_as_na=options.dataframe.mode.use_inf_as_na) <NEW_LINE> return op(df) | Detect missing values.
Return a boolean same-sized object indicating if the values are NA.
NA values, such as None or :attr:`numpy.NaN`, gets mapped to True
values.
Everything else gets mapped to False values. Characters such as empty
strings ``''`` or :attr:`numpy.inf` are not considered NA values
(unless you set ``... | 625941ece64d504609d74d4c |
def getMinimumDifference(self, root): <NEW_LINE> <INDENT> inorder_list = inorder_traversal(root) <NEW_LINE> print(inorder_traversal) | :type root: TreeNode
:rtype: int | 625941ec82261d6c526ab9b4 |
def update_data(self) -> None: <NEW_LINE> <INDENT> slot = get_current_slot(self.store) <NEW_LINE> new_slot = self.data.slot != slot <NEW_LINE> current_epoch = compute_epoch_at_slot(slot) <NEW_LINE> self.update_attest_move() <NEW_LINE> self.update_propose_move() <NEW_LINE> received_block = len([block for block_root, blo... | The head may change if we recorded a new block/new attestation in the `store`.
Attester/proposer responsibilities may change if head changes *and*
canonical chain changes to further back from start current epoch.
.. code-block:: txt
---x------
\ x is fork point
-----
In the followi... | 625941ec435de62698dfe159 |
def test_add_to_table_with_bad_schema1(self): <NEW_LINE> <INDENT> self.assert_table_nonexistant(self.bad_schema_table) <NEW_LINE> self.create_table_with_bad_schema(self.bad_schema_table) <NEW_LINE> self.assert_table_exists(self.bad_schema_table) <NEW_LINE> manager = RecipientManager(self.bad_schema_table, self.db_conne... | Test adding a new recipient to a table with an incorrectly defined schema.
Adding a new recipient to a table with a bad schema should cause the method to return False.
What To Test:
1. Assert that the table initially does not exist.
2. Use external database connection to create database with 1 field that is c... | 625941ec0a50d4780f6673a3 |
def calc_vol(df, n=21): <NEW_LINE> <INDENT> df['Return'] = np.log(df.Close).diff() <NEW_LINE> df['Volatility'] = df['Return'].rolling(n).std() <NEW_LINE> df['Change'] = df['Close'].diff() <NEW_LINE> df['Exp_Change'] = (df['Volatility'] * df['Close']).shift(1) <NEW_LINE> df['Magnitude'] = df['Change'] / df['Exp_Change']... | calculate rolling window volatility
(STD), and add related columns. Default is 21 day. | 625941ecc4546d3d9de72f45 |
def is_heavily_occluded(self): <NEW_LINE> <INDENT> return self.occlusion == 2 | A face with occluded area over 30% is labeled as ‘heavily occluded’
:return: | 625941ec2eb69b55b151cdc4 |
def get_phot_exposure_time(name, flter): <NEW_LINE> <INDENT> path=REMOTE_FOLDER <NEW_LINE> name=name.lower() <NEW_LINE> wisp_path=path+'/wisps/archive.stsci.edu/missions/hlsp/wisp/v6.2//' <NEW_LINE> if name.lower().startswith('par'): <NEW_LINE> <INDENT> p= wisp_path+name+'/hlsp_wisp_hst_wfc3_*-80mas_f*w_v6.2_drz.fits'... | obtain pointing exposure time | 625941ec8a349b6b435e867f |
def _get_hierarchy_row(max_rows, projects): <NEW_LINE> <INDENT> project_count = projects.count() <NEW_LINE> if max_rows == project_count: <NEW_LINE> <INDENT> return [project for project in projects] <NEW_LINE> <DEDENT> empty_begin = (max_rows - project_count) / 2 <NEW_LINE> empty_end = (max_rows - project_count) / 2 + ... | Returns a column for the project hierarchy with a division.
E.g. with a max_rows of 4 and one project, it will return [False, <Project>, False, False]. | 625941eca79ad161976cc652 |
def restrict(xpath): <NEW_LINE> <INDENT> pass | Restrict imput lxml trees to the matching xpath.
| 625941eccc40096d61595e5b |
def adaptive_filter(self): <NEW_LINE> <INDENT> for peak in self.r_peaks: <NEW_LINE> <INDENT> window = self.filt_data[peak - int(self.median_rr / 2):peak + int(self.median_rr / 2)] <NEW_LINE> self.ecg_windowed.append(window) <NEW_LINE> <DEDENT> self.ecg_windowed = np.asarray(self.ecg_windowed)[1:] <NEW_LINE> correct_win... | Method that runs an adaptive filter that generates the "average" QRS template for the window of data.
- Calculates the median RR interval
- Generates a sub-window around each peak, +/- RR interval/2 in width
- Deletes the final beat sub-window if it is too close to end of data window
- Calculates the "average" QRS tem... | 625941ec099cdd3c635f1165 |
def downvote(self, sha256): <NEW_LINE> <INDENT> url = '%sapks/%s/votes' % (self.url, sha256) <NEW_LINE> res = requests.post(url, data={'kind': 'negative'}, headers=self.headers) <NEW_LINE> return res.json() | Downvote a sample | 625941ec7c178a314d6ef975 |
def normalize(self): <NEW_LINE> <INDENT> dispModulus= self.getCentroid().getPositionVector().getModulo() <NEW_LINE> if(dispModulus>1e-4): <NEW_LINE> <INDENT> normalizedPositions= self.getLoadRelativePositions() <NEW_LINE> if(self.vehicleBoundary): <NEW_LINE> <INDENT> normalizedVehicleBoundary= self.getVehicleBoundaryRe... | Sets the positions with respect to the loads centroid. | 625941ec8c0ade5d55d3eecc |
def __str__(self): <NEW_LINE> <INDENT> return "[{}] ({}) {}".format(str(type(self).__name__), self.id, str(self.__dict__)) | returns str representation | 625941ec090684286d50f1fb |
def simple_commit(repo, commit_dir, repo_path, commit_msg): <NEW_LINE> <INDENT> remove_all_except_git(repo_path) <NEW_LINE> copy_tree(commit_dir, repo_path) <NEW_LINE> repo.git.add("*") <NEW_LINE> repo.git.commit("-m {}".format(commit_msg)) <NEW_LINE> sha = repo.git.rev_parse("HEAD") <NEW_LINE> repo.git.tag(commit_msg)... | :param repo: a GitPython Repo object
:param commit_dir: the dir which contains snapshot of target commit
:param repo_path: path to target repo
:param commit_msg:
:return: the SHA of newly created commit | 625941ec7047854f462a1911 |
def compute_3d_loss(params_pred, params_gt, has_gt3d): <NEW_LINE> <INDENT> with tf.name_scope("3d_loss", values = [params_pred, params_gt, has_gt3d]): <NEW_LINE> <INDENT> weights = tf.expand_dims(tf.cast(has_gt3d, tf.float32), 1) <NEW_LINE> res = tf.losses.mean_squared_error( params_gt, params_pred, weights=weights) * ... | Computes the l2 loss between 3D params pred and gt for those data that has_gt3d is True.
Parameters to compute loss over:
3Djoints: 14*3 = 42
rotations:(24*9)= 216
shape: 10
total input: 226 (gt SMPL params) or 42 (just joints)
Inputs:
params_pred: N x {226, 42}
params_gt: N x {226, 42}
# has_gt3d: (N,) bool
h... | 625941ec30bbd722463cc2d6 |
def compute_depth_range(tracks_manager, reconstruction, shot, config): <NEW_LINE> <INDENT> depths = [] <NEW_LINE> for track in tracks_manager.get_shot_observations(shot.id): <NEW_LINE> <INDENT> if track in reconstruction.points: <NEW_LINE> <INDENT> p = reconstruction.points[track].coordinates <NEW_LINE> z = shot.pose.t... | Compute min and max depth based on reconstruction points. | 625941eca17c0f6771cbe55c |
def serialize_transaction(transaction): <NEW_LINE> <INDENT> if isinstance(transaction, model.Payment): <NEW_LINE> <INDENT> return serialize_payment(transaction) <NEW_LINE> <DEDENT> elif isinstance(transaction, model.InvestmentSecurityPurchase): <NEW_LINE> <INDENT> return serialize_investment_transaction( transaction, I... | Serializes a transaction to the QIF format.
@type transaction: model.Transaction
@param transaction: The transaction to serialize
@rtype: unicode
@return: The QIF serialization of the transaction.
@raise SerializationError: For unknown transaction types. | 625941ec23849d37ff7b3598 |
def on_tpu(): <NEW_LINE> <INDENT> return tpu_function.get_tpu_context().number_of_shards is not None | Returns True when building a TPU computation. | 625941ec94891a1f4081bfb9 |
def BFloat64(name): <NEW_LINE> <INDENT> return FormatField(name, ">", "d") | Big endian, 64-bit IEEE floating point number | 625941ec0a366e3fb873ed2c |
def validate(self): <NEW_LINE> <INDENT> dummy = self <NEW_LINE> return True | Simple function to make sure self is valid.
Should return True if valid or raise a ValueError otherwise.
This is useful as a check to make sure things are deserialized
correctly. | 625941ec50812a4eaa59c829 |
def addFileTypeMapping( self, fileTypeMapping ): <NEW_LINE> <INDENT> for fromStr, toStr in fileTypeMapping: <NEW_LINE> <INDENT> thisMapping = self.__addElt( "fileTypeMapping", self.fileTypeMap ) <NEW_LINE> self.__addElt( "from", thisMapping, fromStr ) <NEW_LINE> self.__addElt( "to", thisMapping, toStr ) | Add mapping of file patterns to file types. Sometimes e.g. a text file does not
end in .txt; this lets us add a pattern to say that files matching this pattern
should be viewed as .txt files. | 625941ec23e79379d52eea6a |
def __init__(self, parent=None): <NEW_LINE> <INDENT> super(SheetMapImporterDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self) | Constructor. | 625941ecaad79263cf390f56 |
def notifyUserUploadComplete(self): <NEW_LINE> <INDENT> message = ("Upload succeeded") <NEW_LINE> notify = QMessageBox.warning(self, 'QtMessageBox.warning()', message) | Dialog box triggered when data upload is complete
This method should be overwritten in a subclass if required
to provide a more detailed message to the user. Any
overwritten method should ensure that the close all method is
called. | 625941ecd486a94d0b98e654 |
def replace_dependencies(container, *dependencies, **dependency_map): <NEW_LINE> <INDENT> if set(dependencies).intersection(dependency_map): <NEW_LINE> <INDENT> raise RuntimeError( "Cannot replace the same dependency via both args and kwargs.") <NEW_LINE> <DEDENT> arg_replacements = OrderedDict((dep, MagicMock()) for d... | Replace the dependency providers on ``container`` with
instances of :class:`MockDependencyProvider`.
Dependencies named in *dependencies will be replaced with a
:class:`MockDependencyProvider`, which injects a MagicMock instead of the
dependency.
Alternatively, you may use keyword arguments to name a dependency and
p... | 625941ec5fcc89381b1e1bd0 |
def current_albumcheckout(self): <NEW_LINE> <INDENT> checkouts = self.albumcheckout_set.filter(return_at=None) <NEW_LINE> if len(checkouts) > 0: <NEW_LINE> <INDENT> return checkouts[0] <NEW_LINE> <DEDENT> return None | Returns first outstanding (return_at=None) checkout | 625941ecf9cc0f698b140b04 |
def begin_get_p2_s_vpn_connection_health( self, resource_group_name, gateway_name, **kwargs ): <NEW_LINE> <INDENT> polling = kwargs.pop('polling', True) <NEW_LINE> cls = kwargs.pop('cls', None) <NEW_LINE> lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) <NEW_LINE> cont_token = kwargs.pop('con... | Gets the connection health of P2S clients of the virtual wan P2SVpnGateway in the specified
resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param gateway_name: The name of the P2SVpnGateway.
:type gateway_name: str
:keyword callable cls: A custom type or func... | 625941ec71ff763f4b549ba2 |
def test_replace_namespaced_custom_object_status(self): <NEW_LINE> <INDENT> pass | Test case for replace_namespaced_custom_object_status
| 625941ec66673b3332b9259f |
def __init__(self): <NEW_LINE> <INDENT> self.max_button_chars = 3 <NEW_LINE> self.jpg_quality = 95 <NEW_LINE> self.png_quality = 7 <NEW_LINE> self.tif_compression = 'None' <NEW_LINE> self.export_status = False <NEW_LINE> self.file_format_in_use = None <NEW_LINE> self.names = { 1: 'Sample 1', 2: 'Sample 2', 3: 'Sample 3... | Holds names for the samples and qualifiers. | 625941ece76e3b2f99f3ad10 |
def test_can_update_address_valid_manual_entry_page(self): <NEW_LINE> <INDENT> with mock.patch.object( NannyGatewayActions, "read" ) as nanny_api_read, mock.patch.object( NannyGatewayActions, "list" ) as nanny_api_list, mock.patch.object( NannyGatewayActions, "put" ) as nanny_api_put, mock.patch.object( NannyGatewayAct... | Test to assert that the 'manual entry' page can be rendered. | 625941ec21bff66bcd684e5b |
def calculate(self, exp): <NEW_LINE> <INDENT> if len(self.result_field.get()) == 0: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = round(eval(exp), 10) <NEW_LINE> self.result_field.delete(0, "end") <NEW_LINE> self.result_field.insert(0, result) <NEW_LINE> <DEDEN... | calculates and returns result | 625941ecbe7bc26dc91cdb03 |
def __init__(self, zk_client): <NEW_LINE> <INDENT> self.solr_adapter = solr_adapter.SolrAdapter(zk_client) | Initialises an instance of APIMethods.
In particular it creates SoldAdapter.
Args:
zk_client: An instance of kazoo.client.KazooClient. | 625941eccad5886f8bd274e6 |
def valid_login(username, password): <NEW_LINE> <INDENT> user = User.user_by_name(username) <NEW_LINE> if user and valid_pw(username, password, user.pw_hash): <NEW_LINE> <INDENT> return user | checks for a valid user and password | 625941ec07d97122c4178da5 |
def test_kbhit_no_tty(): <NEW_LINE> <INDENT> @as_subprocess <NEW_LINE> def child(): <NEW_LINE> <INDENT> with mock.patch('blessed.terminal.HAS_TTY', False): <NEW_LINE> <INDENT> term = TestTerminal(stream=six.StringIO()) <NEW_LINE> stime = time.time() <NEW_LINE> assert term.kbhit(timeout=1.1) is False <NEW_LINE> assert m... | kbhit() returns False immediately if HAS_TTY is False | 625941ecd4950a0f3b08c855 |
def RUN(self, x): <NEW_LINE> <INDENT> shell_cmd, new_x = self.condense_multiline_cmds(x) <NEW_LINE> cmd = ' shell: '+self.get_work_dir_cmd() <NEW_LINE> cmd += shell_cmd <NEW_LINE> name = 'Shell Command (' + ' '.join(shell_cmd.split()[0:5]) + ')' <NEW_LINE> self.put_together('RUN', name=name, cmd=[cmd]) <NEW_LINE> retu... | Logic for a RUN command (Shell command) | 625941ec16aa5153ce362986 |
def ConvertTo(self,*__args): <NEW_LINE> <INDENT> pass | ConvertTo(self: SelectionRangeConverter,context: ITypeDescriptorContext,culture: CultureInfo,value: object,destinationType: Type) -> object
Converts the specified System.Windows.Forms.SelectionRangeConverter object to another type by
using the specified culture.
context: A System.ComponentModel.ITypeDescr... | 625941ec596a897236089fc7 |
def eigvals_banded(a_band, lower=False, overwrite_a_band=False, select='a', select_range=None): <NEW_LINE> <INDENT> return eig_banded(a_band, lower=lower, eigvals_only=1, overwrite_a_band=overwrite_a_band, select=select, select_range=select_range) | Solve real symmetric or complex hermitian band matrix eigenvalue problem.
Find eigenvalues w of a::
a v[:,i] = w[i] v[:,i]
v.H v = identity
The matrix a is stored in a_band either in lower diagonal or upper
diagonal ordered form:
a_band[u + i - j, j] == a[i,j] (if upper form; i <= j)
a_ban... | 625941ec07f4c71912b11992 |
def save_url_image_to_file(url, filename): <NEW_LINE> <INDENT> r = requests.get(url) <NEW_LINE> with open("myimage/" + filename, "wb") as f: <NEW_LINE> <INDENT> f.write(r.content) | 请求图片url,并保存至指定文件 | 625941ec15fb5d323cde1025 |
def test(): <NEW_LINE> <INDENT> sf = "6C 7C 8C 9C TC".split() <NEW_LINE> fk = "9D 9H 9S 9C 7D".split() <NEW_LINE> fh = "TD TC TH 7C 7D".split() <NEW_LINE> tp = "5S 5D 9H 9C 6S".split() <NEW_LINE> print(poker([sf, fk, fh])) <NEW_LINE> assert poker([sf, fk, fh]) == [sf] <NEW_LINE> assert poker([fk, fh]) == [fk] <NEW_LINE... | Test cases for the functions in poker program | 625941ec50485f2cf553d2a9 |
def reconstruct(self , X,n_gibbs): <NEW_LINE> <INDENT> v = X <NEW_LINE> for i in range(n_gibbs): <NEW_LINE> <INDENT> prob_h_,h = self.to_hidden(v) <NEW_LINE> prob_v_,v = self.to_visible(prob_h_) <NEW_LINE> <DEDENT> return prob_v_,v | This will reconstruct the sample with k steps of gibbs Sampling | 625941eca17c0f6771cbe55d |
def forwards(self, orm): <NEW_LINE> <INDENT> for parent_thing, tags in self.get_tags_by_thing(orm): <NEW_LINE> <INDENT> uncategorised = self.get_uncategorised_module_for_thing( orm, parent_thing) <NEW_LINE> for tag in tags: <NEW_LINE> <INDENT> tag.thing = uncategorised <NEW_LINE> tag.save() | Write your forwards methods here. | 625941ec2ae34c7f2600d63e |
def _get_mac_addresses(ssh): <NEW_LINE> <INDENT> stdin, stdout, stderr = ssh.exec_command( "/sbin/ip addr show | /bin/grep 'link/ether'", ) <NEW_LINE> return [line.split(None, 3)[1] for line in stdout] | Get the MAC addresses | 625941ec73bcbd0ca4b2c583 |
def test_ga(self): <NEW_LINE> <INDENT> self.tiny_opt_run(ev_opts.GA) | Performs a tiny run of the GA | 625941ec566aa707497f4a6f |
def list_tf_record_files(self, split_name: str) -> list: <NEW_LINE> <INDENT> import fnmatch <NEW_LINE> file_pattern = self.tf_record_file_pattern[:self.tf_record_file_pattern.find("%s")] + split_name + "*." + self.tf_record_file_pattern.split(".")[-1] <NEW_LINE> result_list = [os.path.join(self.tf... | :rtype: list of str | 625941ecdd821e528d63b6b2 |
def record_ticket(self, record, data, hash, app_id): <NEW_LINE> <INDENT> s = self.session <NEW_LINE> try: <NEW_LINE> <INDENT> q = self.tickets.select(self.tickets.c.record_hash == hash) <NEW_LINE> row = s.execute(q).fetchone() <NEW_LINE> if row is None: <NEW_LINE> <INDENT> row = s.execute(self.tickets.insert().values( ... | Records a log record as ticket. | 625941ecfbf16365ca6f66dc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.