code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_errorReceived(self): <NEW_LINE> <INDENT> originalMessageData = Box(_command=SimpleCommand.commandName).serialize() <NEW_LINE> amr = MyAMPReceiver() <NEW_LINE> data = Box(_error="SIMPLE_ERROR").serialize() <NEW_LINE> amr.answerReceived(Value(AMP_ANSWER_TYPE, data), Value(None, originalMessageData), None, None) ... | L{AMPReceiver.answerReceived} should dispatch answers that indicate an
AMP error to methods decorated by the L{errorMethod} decorator, not to
the L{answerMethod} decorator. | 625941de2ae34c7f2600d478 |
def Equals(self,value): <NEW_LINE> <INDENT> pass | Equals(self: UnicodeEncoding,value: object) -> bool
Determines whether the specified System.Object is equal to the current
System.Text.UnicodeEncoding object.
value: The System.Object to compare with the current object.
Returns: true if value is an instance of System.Text.UnicodeEncoding and is equal to... | 625941de0383005118ecf929 |
def get_weights_con(h, Nbar, Y): <NEW_LINE> <INDENT> dim = np.size(Y) <NEW_LINE> meas_puc = np.prod(Y) <NEW_LINE> ZN2l = VecTri.get_ZNl(Nbar) <NEW_LINE> Wphi = np.ones(Nbar) / meas_puc <NEW_LINE> for ii in np.arange(dim): <NEW_LINE> <INDENT> Nshape = np.ones(dim, dtype=np.int) <NEW_LINE> Nshape[ii] = Nbar[ii] <NEW_LINE... | it evaluates integral weights,
which are used for upper-lower bounds calculation,
with constant rectangular inclusion
Parameters
----------
h - the parameter determining the size of inclusion
Nbar - no. of points of regular grid where the weights are evaluated
Y - the size of periodic unit cell
Returns
---... | 625941de67a9b606de4a81fe |
def generate_random_numbers(num, low = 1, high = 20): <NEW_LINE> <INDENT> np.random.seed(0) <NEW_LINE> return np.random.choice(range(low, high), num, replace=True) | Generates an array of num random numbers. | 625941de29b78933be1e59ee |
def complex_simpson(y, a, b, n=10): <NEW_LINE> <INDENT> f = lambdify(x, y) <NEW_LINE> h = (b - a) / n <NEW_LINE> s1 = 0 <NEW_LINE> for i in range(0, n): <NEW_LINE> <INDENT> tmp = a + h * i + 0.5 * h <NEW_LINE> s1 += f(tmp) <NEW_LINE> <DEDENT> s2 = 0 <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> tmp = a + h * i <... | :param y: expression
:param a: lower
:param b: upper
:param n: int
:return: integral | 625941dee76e3b2f99f3ab4e |
def accept_turn_from_player(self, pile_num, num_deleted): <NEW_LINE> <INDENT> if self.whose_turn != Turn.PLAYER: <NEW_LINE> <INDENT> raise GameException(config.NOT_PLAYERS_TURN_ERR) <NEW_LINE> <DEDENT> self.reduce_pile(pile_num, num_deleted) <NEW_LINE> self.remove_empty_piles() <NEW_LINE> self.whose_turn = Turn.AI <NEW... | :param pile_num:
:param num_deleted:
:return: game state after turn completion | 625941deadb09d7d5db6cad5 |
def display_accounts_details(): <NEW_LINE> <INDENT> return Credentials.display_credentials() | Function that returns all the saved credentials. | 625941decb5e8a47e48b7ded |
def sigmoid_rampup(current, rampup_length=15): <NEW_LINE> <INDENT> if rampup_length == 0: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current = np.clip(current, 0.0, rampup_length) <NEW_LINE> phase = 1.0 - current / rampup_length <NEW_LINE> return 0.9*float(np.exp(-5.0 * phase * phase)) | Exponential rampup from https://arxiv.org/abs/1610.02242 | 625941ded10714528d60002e |
def set_allow_register(self, allow): <NEW_LINE> <INDENT> raise NotImplementedError | Allow or disallow user registration
Parameters
----------
allow : bool | 625941dea8ecb033257d3413 |
def remove_edgelet(self, u, v, layer): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> multi_edge = self[u][v][self.cid] <NEW_LINE> multi_edge.pop(layer) <NEW_LINE> if len(multi_edge) == 0: <NEW_LINE> <INDENT> self.nx_base.remove_edge(self, u, v) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass | Remove a specific edge in a specific layer.
Parameters:
u, v: networkx node
The end nodes of the edgelet to be removed.
layer: str
The layer of the edgelet to be removed. | 625941de090684286d50f030 |
def refraction(angles, n_before, n_after): <NEW_LINE> <INDENT> snell = n_before / n_after * np.sin(angles) <NEW_LINE> snell[abs(snell) > 1] = np.nan <NEW_LINE> return np.arcsin(snell) | Returns angles after refracting through an interface
Parameters
----------
angles: float or array of floats
angles relative to normal before the interface
n_before: float
Refractive index of the medium light is coming from
n_after: float
Refractive index of the medium light is going to | 625941de0c0af96317bb852f |
def mark_range_detection(times, ranges): <NEW_LINE> <INDENT> artifacts = np.zeros(times.shape[0], dtype=bool) <NEW_LINE> for this_range in ranges: <NEW_LINE> <INDENT> idx = (times >= this_range[0]) & (times <= this_range[1]) <NEW_LINE> print(this_range, times[0], times[-1]) <NEW_LINE> print(idx.sum()) <NEW_LINE> artifa... | Ranges contains a list of 2-tuples. All timestamps within
such a 2-tuple are excluded. | 625941dea17c0f6771cbe397 |
def run_tweakshifts(asn_direct, verbose=False, clean=True): <NEW_LINE> <INDENT> from pyraf import iraf <NEW_LINE> from iraf import stsdas,dither <NEW_LINE> no = iraf.no <NEW_LINE> yes = iraf.yes <NEW_LINE> INDEF = iraf.INDEF <NEW_LINE> root = asn_direct.split('_asn.fits')[0] <NEW_LINE> try: <NEW_LINE> <INDENT> os.remov... | run_tweakshifts(asn_direct)
asn_direct - filename of ASN table of direct images [...]_asn.fits
This routine only uses dither.tweakshifts to compute the relative shifts of
the direct images
| 625941de090684286d50f031 |
def setInfo(msg): <NEW_LINE> <INDENT> logger.info(msg) | Função que grava informações de informação do processamento no log/YARN
Parâmetros de Entrada:
msg - String - Texto da mensagem a gravar na log | 625941deb545ff76a891415d |
def _get_hardcoded_users(): <NEW_LINE> <INDENT> users = [{'name': name} for (name) in user_data] <NEW_LINE> return users | Return a hardcoded list of users for testing purposes. | 625941de8c3a873295158705 |
def show(api: API) -> int: <NEW_LINE> <INDENT> downloads = api.get_downloads() <NEW_LINE> def print_line(*args): <NEW_LINE> <INDENT> print("{:<17} {:<9} {:>8} {:>12} {:>12} {:>8} {}".format(*args)) <NEW_LINE> <DEDENT> print_line("GID", "STATUS", "PROGRESS", "DOWN_SPEED", "UP_SPEED", "ETA", "NAME") <NEW_LINE> for downl... | Show subcommand.
Arguments:
api: The API instance to use.
Returns:
int: Always 0. | 625941decc0a2c11143dd1d8 |
def authenticate(self, key_id=None, secret=None, allow_agent=False): <NEW_LINE> <INDENT> if key_id and secret: <NEW_LINE> <INDENT> self.auth = HTTPSignatureAuth(key_id=key_id, secret=secret, allow_agent=allow_agent) | :param key_id: SmartDC identifier for the ssh key
:type key_id: :py:class:`basestring`
:param secret: path to private rsa key
:type secret: :py:class:`basestring`
:param allow_agent: whether or not to try ssh-agent
:type allow_agent: :py:class:`bool`
If no `key_id` or `secret` were entered on initialization, or ther... | 625941de6fece00bbac2da89 |
def allocate_tensors(self): <NEW_LINE> <INDENT> self.tensors = {} | (Optional) allocate torch tensors that could potentially be used in
in the train_step() or evaluation_step() functions. If the
load_to_gpu() function is called then those tensors will be moved to
the gpu device. | 625941de6fb2d068a760f3e9 |
def test_combine_empty_container(self): <NEW_LINE> <INDENT> a = Container() <NEW_LINE> b = Container() <NEW_LINE> c = a + b <NEW_LINE> self.assertEqual(c.nrow, a.nrow) <NEW_LINE> self.assertEqual(c.nrow, b.nrow) <NEW_LINE> self.assertEqual(c.nrow, 0) <NEW_LINE> np.testing.assert_array_equal(a(), c()) <NEW_LINE> np.test... | Test if combination of empty containers works | 625941de5510c4643540f724 |
def filter_files(self): <NEW_LINE> <INDENT> for path in self.finder.filter_files( "short_description.txt|full_description.txt|title.txt" ): <NEW_LINE> <INDENT> yield path.parent <NEW_LINE> <DEDENT> for path in self.finder.filter_files(r".*\.txt", ".*/changelogs"): <NEW_LINE> <INDENT> yield path.parent.parent | Filters possible file matches. | 625941de63d6d428bbe44837 |
def power_to_energy_K(x, radius, calibration_factor, frequency=1, velocity_mode=True, density=7600): <NEW_LINE> <INDENT> mass = density*4*np.pi/3 * radius**3*1e-18 <NEW_LINE> kB = 1.38e-23 <NEW_LINE> if velocity_mode: <NEW_LINE> <INDENT> return x*calibration_factor**2*1e-12*mass/kB <NEW_LINE> <DEDENT> else: <NEW_LINE> ... | scaled the input power to physical units
Args:
x: energy in px^2
radius: in um
frequency: in Hertz
calibration_factor: in um/px
density: in kg/m^3
velocity_mode: if true x was computed from the velocity psd if false x is the integral of the position psd
Returns: | 625941de5fdd1c0f98dc057c |
def make_move(self) -> None: <NEW_LINE> <INDENT> if self.is_legal(): <NEW_LINE> <INDENT> if self.square_to.row == 0 or self.square_to.row == 7: <NEW_LINE> <INDENT> if self.square_from.piece.piece_type.lower() == "p": <NEW_LINE> <INDENT> promotion_window(self, self.square_to.piece) <NEW_LINE> <DEDENT> <DEDENT> self.squa... | Method for executing a move with a given Move object on the board, given a legal Move. | 625941de38b623060ff0b135 |
def create(self, output_path, report_data): <NEW_LINE> <INDENT> for report in report_data['reports']: <NEW_LINE> <INDENT> checker = report['checkerName'] <NEW_LINE> report['severity'] = self._severity_map.get(checker, 'UNSPECIFIED') <NEW_LINE> <DEDENT> self.generated_html_reports[output_path] = report_data['reports'] <... | Create html file with the given report data to the output path. | 625941de656771135c3ebbba |
def __update_best_solution(self): <NEW_LINE> <INDENT> if self.__best_sum_similarities is None or self.__best_sum_similarities < self.sum_similarities_: <NEW_LINE> <INDENT> self.__best_labels = np.copy(self.labels_) <NEW_LINE> self.__best_cluster_centers = np.copy(self.cluster_centers_) <NEW_LINE> self.__best_similariti... | Updates the best solution if a new solution is better than previous ones. | 625941de3346ee7daa2b30b5 |
def test_best_location(): <NEW_LINE> <INDENT> s = Vendor.get("WhitePages", config={"api_key": "1234"}) <NEW_LINE> lookup_result = s._parse(JSON_BEST_LOCATION) <NEW_LINE> assert lookup_result.success == True <NEW_LINE> assert len(lookup_result.contacts) == 1 <NEW_LINE> log.debug(lookup_result.contacts) <NEW_LINE> assert... | Handle response of address but no name | 625941de925a0f43d254a1c1 |
def redges_false(train_E, test_E, output_path=None): <NEW_LINE> <INDENT> train_redges_false = set(tuple(reversed(edge_tuple)) for edge_tuple in train_E) <NEW_LINE> test_redges_false = set(tuple(reversed(edge_tuple)) for edge_tuple in test_E) <NEW_LINE> train_redges_false = train_redges_false - train_E <NEW_LINE> test_r... | For directed graphs computes all non-edges (a->b) such that the opposite edge (a<-b) exists in the graph.
It does this for both the train and test edge sets.
Parameters
----------
train_E : set
The set of train edges.
test_E : set
The set of test edges.
output_path : string, optional
A path or file where to ... | 625941de377c676e912724ef |
def handler(func): <NEW_LINE> <INDENT> class Handler(BaseHandler): <NEW_LINE> <INDENT> __doc__ = func.__doc__ <NEW_LINE> __name__ = func.__name__ <NEW_LINE> __module__ = func.__module__ <NEW_LINE> @property <NEW_LINE> @classmethod <NEW_LINE> def load_path(cls): <NEW_LINE> <INDENT> return f"{cls.__module__}.{cls.__name_... | Function decorator for creating Python handler classes. | 625941dea219f33f34628cad |
def get_wvlnt(self): <NEW_LINE> <INDENT> if self.wvlnt is None: <NEW_LINE> <INDENT> raise AttributeError('wvlnt value has not yet been defined') <NEW_LINE> <DEDENT> return self.wvlnt | Returns the wvlnt
:return: wavelength of q parameter
:rtype: float | 625941def8510a7c17cf9a46 |
def update_k_vars(k_vars): <NEW_LINE> <INDENT> for k, v in DEFAULT_K_VARS.items(): <NEW_LINE> <INDENT> if k not in k_vars: <NEW_LINE> <INDENT> k_vars[k] = v | Update unspeified keys in k_vars with the defaults | 625941debaa26c4b54cb1464 |
def train(self, sequences, labels, grid_search=True): <NEW_LINE> <INDENT> features = self.featurizer.convert_many(sequences) <NEW_LINE> if grid_search: <NEW_LINE> <INDENT> self.model = self.classifier_type.grid_search(features, labels) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.model = self.classifier_type.buil... | Trains the underlying classifier
:param sequences: The sequences to train on
:type sequences: list of list
:param labels: The labels for each sequence
:type labels: list of list
:param grid_search: Whether or not to use grid search to optimize the
model
:type grid_search: bool | 625941deff9c53063f47c53a |
def __str__(self): <NEW_LINE> <INDENT> result = "" <NEW_LINE> for s in self.__deck: <NEW_LINE> <INDENT> result = result + str(s) + '\n' <NEW_LINE> <DEDENT> return result | Represent the whole deck as a string for printing -- very useful during code development | 625941ded58c6744b4257fa6 |
def deletedRecord(self): <NEW_LINE> <INDENT> return u'no' | Way the repository handles deleted records.
Either 'no', 'transient' or 'persistent'. | 625941de8c0ade5d55d3ed05 |
def __init__( self, input_file: TextIO, autoload: bool = True, max_length: int = 76 ) -> None: <NEW_LINE> <INDENT> if not isinstance(max_length, int): <NEW_LINE> <INDENT> raise TypeError("The max_length must be int.") <NEW_LINE> <DEDENT> self.input_file = input_file <NEW_LINE> self.autoload = autoload <NEW_LINE> self.m... | Init method. | 625941de5166f23b2e1a54a1 |
def slice(self, index, step=None): <NEW_LINE> <INDENT> _index = 0 <NEW_LINE> result = [] <NEW_LINE> for uchar in self.value: <NEW_LINE> <INDENT> if (_index >= index) and ((step is None) or (step > _index)): <NEW_LINE> <INDENT> result.append(uchar) <NEW_LINE> <DEDENT> _index += 1 <NEW_LINE> <DEDENT> return "".join(resul... | Slice the unicode string
:param index: start index
:param step:
:return: a slice string | 625941de1d351010ab855e63 |
def addAnimationToFigure(self, colors=np.array([0.4, 0.4, 0.4, 1.0]), linkColors=np.array([0.0, 0.0, 1.0, 0.5]), indices=None, fileName=None): <NEW_LINE> <INDENT> elbowPositions = self.elbowPositions <NEW_LINE> fiberPositions = self.fiberPositions <NEW_LINE> cobraCenters = self.bench.cobras.centers <NEW_LINE> linkRadiu... | Animates the cobra trajectories on top of an existing figure.
Parameters
----------
colors: object, optional
The trajectory colors. Default is dark grey.
linkColors: object, optional
The cobra link colors. Default is light blue.
indices: object, optional
A numpy array with the cobra trajectory indices to a... | 625941de63f4b57ef0001459 |
def create_dataset(images,lables,buffer_size=100): <NEW_LINE> <INDENT> AUTOTUNE = tf.data.experimental.AUTOTUNE <NEW_LINE> images = [load_image(p) for p in images] <NEW_LINE> images_zip = zip(list(range(len(images))),images) <NEW_LINE> image_ds = tf.data.Dataset.from_generator( lambda: images_zip,(tf.int8,tf.float32)) ... | 直接先把所有图片读入内存 | 625941deec188e330fd5aae1 |
def __str__(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self.to_dict(), indent=2) | Return a `str` version of this NluEnrichmentSentiment object. | 625941dedc8b845886cb587e |
def lex_count(self, low, high): <NEW_LINE> <INDENT> return self.database.zlexcount(self.key, low, high) | Count the number of members in a sorted set between a given
lexicographical range. | 625941ded164cc6175783097 |
def rotatePixelCoords(sources, width, height, nQuarter): <NEW_LINE> <INDENT> if nQuarter < 1 or nQuarter > 3: <NEW_LINE> <INDENT> raise ValueError('nQuarter is %i. It should be 1 <= nQuarter <= 3 .' % int(nQuarter)) <NEW_LINE> <DEDENT> xKey = sources.schema.find("slot_Centroid_x").key <NEW_LINE> yKey = sources.schema.f... | !Rotate catalog (x, y) pixel coordinates such that LLC of detector in FP is (0, 0)
@param[in/out] sources SourceCatalog for which the x, y pixel values are to be rotated in place
@param[in] width image width from which the sources were measured
@param[in] height image height from which the sources wer... | 625941de71ff763f4b5499d9 |
def _sub_stage_teardown(self): <NEW_LINE> <INDENT> pass | **SUBCLASS HOOK**: Perform additional teardown actions in **teardown** stage.
Gets called from :py:func:`~BaseApp._stage_teardown` and it is a **TEARDOWN SUBSTAGE 01**. | 625941de32920d7e50b2851b |
def pack(self, assertstruct=True): <NEW_LINE> <INDENT> if(assertstruct): <NEW_LINE> <INDENT> if(not self.__assert()[0]): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> packed = "" <NEW_LINE> packed += struct.pack("!HHL", self.type, self.len, self.experimenter) <NEW_LINE> return packed | Pack message
Packs empty array used as placeholder | 625941dec4546d3d9de72d7e |
def is_normal(self): <NEW_LINE> <INDENT> N = self.index() <NEW_LINE> G = self.relabel(inplace=False) <NEW_LINE> s2 = G._S2 <NEW_LINE> s3 = G._S3 <NEW_LINE> ss2 = [None]*N <NEW_LINE> ss3 = [None]*N <NEW_LINE> for j in [s2[0],s3[0]]: <NEW_LINE> <INDENT> m = G._canonical_rooted_labels(j) <NEW_LINE> for i in range(N): <NEW... | Test whether the group is normal
EXAMPLES::
sage: G = Gamma(2).as_permutation_group()
sage: G.is_normal()
True
sage: G = Gamma1(2).as_permutation_group()
sage: G.is_normal()
False | 625941dee1aae11d1e74a002 |
def setComponentEnabledSetting(self, componentName, newState, flags): <NEW_LINE> <INDENT> pass | Set the enabled setting for a package component (activity, receiver,
service, provider). This setting will override any enabled state which
may have been set by the component in its manifest.
:param componentName: ComponentName: The component to enable
:param newState: int: The new enabled state for the component.Value... | 625941de76d4e153a657ee7a |
def get_api_perms(request): <NEW_LINE> <INDENT> perms = {} <NEW_LINE> ret = get_url_with_resource(request) <NEW_LINE> for obj in models.ResourcePermission.objects.all(): <NEW_LINE> <INDENT> name = URL_ARG_RE.sub(r'{\1}', obj.resource.name) <NEW_LINE> if name not in ret: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ... | Return all API perms for @groups and users.
Format: {resource: {create/read/update/delete: [users, @groups]}} | 625941de99cbb53fe6792f2e |
def remember(**kwargs): <NEW_LINE> <INDENT> for k, v in kwargs.items(): <NEW_LINE> <INDENT> d[k] = v | update the dict with the collected info pieces | 625941de3346ee7daa2b30b6 |
def test_get_info_no_tmdb_trailer(self): <NEW_LINE> <INDENT> request = {'imdb_id': 'tt0117509', 'tmdb_main': [{'title': 'Revolutionary Road', 'release_date': '2008-01-01'}], 'tmdb_trailer': []} <NEW_LINE> result = self.main.run(request) <NEW_LINE> expected = { 'trailer_main': [{ 'video_id': 'qADM67ZgYxM', 'imdb_id': 't... | Top level test checking that we pull back the bes trailer for a film | 625941dea05bb46b383ecb68 |
def create_asset(local_svgs_dir, target_dir): <NEW_LINE> <INDENT> target_dir = os.path.realpath(target_dir) <NEW_LINE> if not os.path.exists(target_dir): <NEW_LINE> <INDENT> os.makedirs(target_dir) <NEW_LINE> <DEDENT> download_svgs_cmd = [ 'python', os.path.join(SVG_TOOLS, 'svg_downloader.py'), '--output_dir', target_d... | Create the asset. | 625941de8e71fb1e9831daf0 |
def get_context_data(self, *args, **kwargs): <NEW_LINE> <INDENT> context = super(RelatedBillsList, self).get_context_data(*args, **kwargs) <NEW_LINE> metadata = context['metadata'] <NEW_LINE> FilterBillsForm = get_filter_bills_form(metadata) <NEW_LINE> if self.request.GET: <NEW_LINE> <INDENT> form = FilterBillsForm(sel... | Context:
If GET parameters are given:
- search_text
- form (FilterBillsForm)
- long_description
- description
- get_params
Otherwise, the only context item is an unbound FilterBillsForm.
Templates:
- Are specified in subclasses. | 625941def7d966606f6aa350 |
def json(self, dictionary): <NEW_LINE> <INDENT> self.set_header("Content-Type", "application/json") <NEW_LINE> return self.write(simplejson.dumps(dictionary)) | Writes a json response, and sets the json header. | 625941de6fece00bbac2da8a |
def assignment_mapping_from_key(context, manager_name, category, key, create=False): <NEW_LINE> <INDENT> manager = getUtility(IPortletManager, manager_name) <NEW_LINE> if category == CONTEXT_CATEGORY: <NEW_LINE> <INDENT> path = key <NEW_LINE> portal = getToolByName(context, "portal_url").getPortalObject() <NEW_LINE> po... | Given the name of a portlet manager, the name of a category, and a
key in that category, return the IPortletAssignmentMapping.
Raise a KeyError if it cannot be found. | 625941dee76e3b2f99f3ab4f |
def recreate_image(im_as_var): <NEW_LINE> <INDENT> reverse_mean = [-0.485, -0.456, -0.406] <NEW_LINE> reverse_std = [1/0.229, 1/0.224, 1/0.225] <NEW_LINE> recreated_im = copy.copy(im_as_var.data.numpy()[0]) <NEW_LINE> for c in range(3): <NEW_LINE> <INDENT> recreated_im[c] /= reverse_std[c] <NEW_LINE> recreated_im[c] -=... | Recreates images from a torch variable, sort of reverse preprocessing
Args:
im_as_var (torch variable): Image to recreate
returns:
recreated_im (numpy arr): Recreated image in array | 625941de3317a56b86939f99 |
def term_velocity_skydiver(): <NEW_LINE> <INDENT> tbf = TermBodyFluid(0.6, 0.79, 0.9, 0.08, 1003) <NEW_LINE> termvel = tbf.terminal_velocity_equation() <NEW_LINE> solver = ode.RungeKutta4(tbf) <NEW_LINE> solver.set_initial_condition(0.0) <NEW_LINE> n_list = range(10, 100, 5) <NEW_LINE> velocity_calcs = [] <NEW_LINE> t_... | plotting the terminal velocity of the skydiver with the exact velocity | 625941dee64d504609d74b88 |
def plot_layout( title="TDA KMapper", width=600, height=600, bgcolor="rgba(255, 255, 255, 1)", annotation_text=None, annotation_x=0, annotation_y=-0.01, top=100, left=60, right=60, bottom=60, ): <NEW_LINE> <INDENT> pl_layout = dict( title=title, font=dict(size=12), showlegend=False, autosize=False, width=width, height=... | Set the plotly layout
Parameters
----------
width, height: integers
setting width and height of plot window
bgcolor: string,
rgba or hex color code for the background color
annotation_text: string
meta data to be displayed
annotation_x & annotation_y:
The coordinates of the point where we insert the a... | 625941de796e427e537b0910 |
def normalize_data(data, data_mean, data_std, dim_to_use ): <NEW_LINE> <INDENT> data_out = {} <NEW_LINE> for key in data.keys(): <NEW_LINE> <INDENT> data[ key ] = data[ key ][ :, dim_to_use ] <NEW_LINE> mu = data_mean[dim_to_use] <NEW_LINE> stddev = data_std[dim_to_use] <NEW_LINE> data_out[ key ] = np.divide( (data[key... | Normalizes a dictionary of poses
Args
data: dictionary where values are
data_mean: np vector with the mean of the data
data_std: np vector with the standard deviation of the data
dim_to_use: list of dimensions to keep in the data
Returns
data_out: dictionary with same keys as data, but values have been norma... | 625941deaad79263cf390d8e |
def get_exchange_for_vhost(self, exchange, vhost): <NEW_LINE> <INDENT> return self._api_get('/api/exchanges/{0}/{1}'.format( urllib.parse.quote_plus(vhost), urllib.parse.quote_plus(exchange) )) | An individual exchange
:param exchange: The exchange name
:type exchange: str
:param vhost: The vhost name
:type vhost: str | 625941dea8ecb033257d3414 |
def test_process_roll_delete(self): <NEW_LINE> <INDENT> mock_parser = mock.Mock(name="delete_roll") <NEW_LINE> mock_parser.return_value = "Success" <NEW_LINE> evt = self.mock_event <NEW_LINE> arg = "delete something" <NEW_LINE> with mock.patch.object(RollPlugin, 'delete_roll', mock_parser): <NEW_LINE> <INDENT> handler ... | Assert that process roll handles delete command. | 625941de0a366e3fb873eb65 |
def simulation_step(self): <NEW_LINE> <INDENT> self.kernel_api.simulation_step() | See parent class. | 625941de23e79379d52ee8a8 |
def persist_header(self, header: BlockHeader) -> Tuple[BlockHeader, ...]: <NEW_LINE> <INDENT> is_genesis = header.parent_hash == GENESIS_PARENT_HASH <NEW_LINE> if not is_genesis and not self.header_exists(header.parent_hash): <NEW_LINE> <INDENT> raise ParentNotFound( "Cannot persist block header ({}) with unknown paren... | Returns iterable of headers newly on the canonical chain | 625941de4a966d76dd55135a |
def setup(self): <NEW_LINE> <INDENT> self.controller = App.get_running_app().controller <NEW_LINE> self.controller.bind( current_account=lambda _, value: self.on_current_account(value)) | Binds Controller.current_account property. | 625941de30dc7b7665901cac |
def trap(self, height): <NEW_LINE> <INDENT> left=0 <NEW_LINE> right=len(height)-1 <NEW_LINE> max_left=max_right=res=0 <NEW_LINE> while left<=right: <NEW_LINE> <INDENT> if height[left]<=height[right]: <NEW_LINE> <INDENT> if height[left]>=max_left: <NEW_LINE> <INDENT> max_left=height[left] <NEW_LINE> <DEDENT> else: <NEW_... | :type height: List[int]
:rtype: int | 625941de50812a4eaa59c667 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(PeopleColumn, self).__init__( label=_('People'), detailed_label=_('Target People'), sortable=False, shrink=False, *args, **kwargs) | Initialize the column. | 625941de293b9510aa2c35db |
def draw(self): <NEW_LINE> <INDENT> pass | Renders the object within the window.
Derived classes override this method to meet their specific
needs. | 625941de956e5f7376d711b4 |
def increment(self): <NEW_LINE> <INDENT> self._active = (self._active - 1) % len(self._labels) <NEW_LINE> self._activate() | Do things when the menu incremets. | 625941decc40096d61595c98 |
def test_lookup_succeeds_with_valid_params_lower_returns_a_capitalized_key(self): <NEW_LINE> <INDENT> result = lookup('paris') <NEW_LINE> self.assertEqual(result, ['The capital and largest city of France.']) | test lookup succeeds with valid params lower returns a capitalized key | 625941de91af0d3eaac9bd64 |
def add_entry(self, key, name=None, entry=None): <NEW_LINE> <INDENT> if not entry and not name: <NEW_LINE> <INDENT> raise ValueError("Should specify at least one of name or entry") <NEW_LINE> <DEDENT> if entry: <NEW_LINE> <INDENT> if not name: <NEW_LINE> <INDENT> name = entry.get_title() <NEW_LINE> <DEDENT> self._appen... | add an entry for the statistics file
- key: which category it belongs to (key returned by add_category)
You must specify at least one of the two following:
- name: a name for this entry
- entry: an instance of the Entry class.
Arguments: - name only: must already have an entry by that name.
- entry only: n... | 625941de7d847024c06be607 |
def data_for_rel(score_list): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for socres in score_list.values(): <NEW_LINE> <INDENT> data.append(list(socres.keys())) <NEW_LINE> <DEDENT> return data | 关联分析数据集
:param score_list:
:return: | 625941debf627c535bc13518 |
def depth(self): <NEW_LINE> <INDENT> url = "/".join([base_url, 'orderbook']) <NEW_LINE> resp = self._request('GET', url).json() <NEW_LINE> asks = [] <NEW_LINE> for p, a in resp['asks']: <NEW_LINE> <INDENT> asks.append(models.Order(price=self._create_decimal(p), amount=self._create_decimal(a))) <NEW_LINE> <DEDENT> bids ... | @todo: Docstring for depth
:returns: @todo | 625941ded99f1b3c44c678d2 |
def MST_pathfinder(G): <NEW_LINE> <INDENT> NG = nx.Graph() <NEW_LINE> NG.add_nodes_from(list(range(numnodes))) <NEW_LINE> edges = sorted( ((G[a][b]['weight'],a,b) for a,b in G.edges()), reverse=False) <NEW_LINE> clusters = {node:i for i,node in enumerate(G.nodes())} <NEW_LINE> while not edges == []: <NEW_LINE> <INDE... | The MST-pathfinder algorithm (Quirin et al. 2008) reduces the graph to the
unions of all minimal spanning trees. | 625941de462c4b4f79d1da19 |
def url(self): <NEW_LINE> <INDENT> return getNetworkUrl(self.protocol(), self.host(), self.port(), self.user(), self.settings()) | Returns current server url | 625941dee5267d203edcdfe1 |
def record(priority,message): <NEW_LINE> <INDENT> sys.stderr.write(time.asctime(time.localtime(time.time()))) <NEW_LINE> sys.stderr.write(' ') <NEW_LINE> if using_syslog: <NEW_LINE> <INDENT> syslog.syslog(priority,message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.stderr.write(priority + ' ') <NEW_LINE> <DEDENT... | record(priority,message)
priority should be one of the constants defined in this module | 625941de956e5f7376d711b5 |
def test_sorting(self): <NEW_LINE> <INDENT> sims = [Similarity(1), Similarity(0), 0.5] <NEW_LINE> sims.sort() <NEW_LINE> self.assertEqual([Similarity(0), 0.5, Similarity(1)], sims) | Verify similarities can be sorted. | 625941de8a43f66fc4b543aa |
def forward(self, graph, feat, efeat): <NEW_LINE> <INDENT> graph = graph.local_var() <NEW_LINE> graph.ndata['h'] = feat.expand_dims(-1) <NEW_LINE> graph.edata['w'] = self.edge_nn(efeat).reshape(-1, self._in_feats, self._out_feats) <NEW_LINE> graph.update_all(fn.u_mul_e('h', 'w', 'm'), self.reducer('m', 'neigh')) <NEW_L... | Compute MPNN Graph Convolution layer.
Parameters
----------
graph : DGLGraph
The graph.
feat : mxnet.NDArray
The input feature of shape :math:`(N, D_{in})` where :math:`N`
is the number of nodes of the graph and :math:`D_{in}` is the
input feature size.
efeat : mxnet.NDArray
The edge feature of sha... | 625941de3cc13d1c6d3c76c1 |
def __repr__(self): <NEW_LINE> <INDENT> return "<{} name:{!r}>".format(self.__class__.__name__, self.name) | Get a debugging representation of a field. | 625941def8510a7c17cf9a47 |
def run(self): <NEW_LINE> <INDENT> if not self.connection: <NEW_LINE> <INDENT> self.setup_connection() <NEW_LINE> <DEDENT> while self.is_running: <NEW_LINE> <INDENT> if self.connection.open: <NEW_LINE> <INDENT> self.reconnect_attempt = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.reconnect() <NEW_LINE> <DEDENT>... | Run forever | 625941de7d847024c06be608 |
def bubble_sort(array): <NEW_LINE> <INDENT> loop = len(array) - 1 <NEW_LINE> for i in range(loop): <NEW_LINE> <INDENT> for j in range(loop - i): <NEW_LINE> <INDENT> if array[j] > array[j + 1]: <NEW_LINE> <INDENT> array[j], array[j + 1] = array[j + 1], array[j] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return array | 传统冒泡排序 | 625941de63b5f9789fde742e |
def partition_bridge(self, node=None): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> node = self._random_interface()[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node = self._get_node(node) <NEW_LINE> <DEDENT> interfaces = self._interfaces() <NEW_LINE> disruptions = [] <NEW_LINE> for i in range(len(inter... | Partitions a node as a bridge to two sides of a cluster. | 625941de63b5f9789fde742f |
def test_fields_curly_braces(self): <NEW_LINE> <INDENT> ctr_format = u'{desc} {count:d} {unit}{fill}' <NEW_LINE> bar_format = u'{desc} {count:d} {unit}{bar}' <NEW_LINE> ctr = Counter(stream=self.tty.stdout, total=1, desc='open{', unit='dudes', counter_format=ctr_format, bar_format=bar_format) <NEW_LINE> self.assertEqua... | Ensure curly braces work in fields | 625941de287bf620b61d3daa |
def __len__(self) -> int: <NEW_LINE> <INDENT> raise NotImplementedError('`__len__` function in `datasets.py` needs to ' + 'be implemented') | Returns number of pairs of images in dataset. | 625941de2c8b7c6e89b35b07 |
def det(self): <NEW_LINE> <INDENT> if not self.is_endomorphism(): <NEW_LINE> <INDENT> raise ArithmeticError("Matrix morphism must be an endomorphism.") <NEW_LINE> <DEDENT> return self.matrix().determinant() | Return the determinant of this endomorphism.
EXAMPLES::
sage: V = ZZ^2; phi = V.hom([V.0+V.1, 2*V.1])
sage: phi.det()
2 | 625941de85dfad0860c3b1a5 |
def similarity(w1, w2): <NEW_LINE> <INDENT> vec = numpy.dot(w1, w2) <NEW_LINE> veclen=numpy.sqrt(numpy.sum(numpy.array(w1)**2))*numpy.sqrt(numpy.sum(numpy.array(w2)**2)) <NEW_LINE> if veclen>0.0: <NEW_LINE> <INDENT> return vec / veclen <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ('error vec') | 计算词向量的相似度,使用余弦 | 625941de711fe17d825426ad |
def update(self): <NEW_LINE> <INDENT> pass | override to add language-specific behavior | 625941de377c676e912724f0 |
def not_yet_valid(self) -> "CertificateQuerySet": <NEW_LINE> <INDENT> return self.filter(revoked=False, valid_from__gt=timezone.now()) | Return certificates that are not yet valid. | 625941decb5e8a47e48b7dee |
def get_success_url(self): <NEW_LINE> <INDENT> success_url = super(SuccessPreviousViewRedirectMixin, self).get_success_url() <NEW_LINE> ignore_success_mixin = self.kwargs.get('ignore_success_mixin', None) <NEW_LINE> if ignore_success_mixin is not True: <NEW_LINE> <INDENT> next = self.request.GET.get('next') <NEW_LINE> ... | Returns the relative path of the url provided in the 'next' param,
or the view's default success_url if 'next' is invalid or unavailable. | 625941de6e29344779a62958 |
def __str__(self): <NEW_LINE> <INDENT> return self.internalDictionary.__str__() | description:
this is the based dictionary class Star function to produce a string
representation of this object
parameters:
None
return:
a string representation of the internal dictionary structure. This is
achieved by simply calling the str function of the internal dictionary | 625941de0a50d4780f6671de |
def merge_unique_identities(db, from_uuid, to_uuid): <NEW_LINE> <INDENT> with db.connect() as session: <NEW_LINE> <INDENT> fuid = find_unique_identity(session, from_uuid) <NEW_LINE> tuid = find_unique_identity(session, to_uuid) <NEW_LINE> if not fuid: <NEW_LINE> <INDENT> raise NotFoundError(entity=from_uuid) <NEW_LINE>... | Merge one unique identity into another.
Use this function to join 'from_uuid' unique identity into
'to_uuid'. Identities and enrollments related to 'from_uuid' will be
assigned to 'to_uuid'. In addition, 'from_uuid' will be removed
from the registry. Duplicated enrollments will be also removed from
the registry while ... | 625941ded10714528d60002f |
def test__2d_encoding(self): <NEW_LINE> <INDENT> df = pd.read_csv(TEST_FILE, index_col='Date') <NEW_LINE> df["label"] = df["spy_Close"] > df["spy_Open"] <NEW_LINE> class ArrayEncoder(TargetLabelEncoder): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> @property <NEW_LI... | given | 625941dea934411ee37519dd |
def parse(path, source=None): <NEW_LINE> <INDENT> if source is None: <NEW_LINE> <INDENT> source = guess_source(path) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> handler = {"23andme": _23andme, "23andme-exome-vcf": _23andme_exome, "ftdna-illumina": ftdna, "decodeme": decodeme, "vcf": _23andme_exome, "ftdna": ftdna}[sou... | Returns a generator yielding :class:`SNP` from an openSNP file
at a given location.
:param str path: path to openSNP file, *all* formats are supported.
:param str source: should be one of ``"23andme"``, ``"vcf"``,
``"decodeme"`` or ``"ftdna"``; `source`` will be extracted from
the filename, if not provided exp... | 625941ded486a94d0b98e490 |
def svn_fs_node_prop(*args): <NEW_LINE> <INDENT> return _fs.svn_fs_node_prop(*args) | svn_fs_node_prop(svn_fs_root_t root, char path, char propname, apr_pool_t pool) -> svn_error_t | 625941dec432627299f04f91 |
def event_m10_25_x120(z28=851): <NEW_LINE> <INDENT> CompareChrHpValue(0, z28, 0, 5) <NEW_LINE> assert ConditionGroup(0) <NEW_LINE> return 0 | [Lib] [DC] [Condition] NPC White Spirit_Gesture Management
z28: Boss generator ID | 625941de76e4537e8c3519be |
def generate_new_readme(colourised: list,precol: list, readme: str): <NEW_LINE> <INDENT> l = len(colourised) <NEW_LINE> for i in range(l): <NEW_LINE> <INDENT> esc = re.escape(precol[i]) <NEW_LINE> readme = re.sub(esc,colourised[i],readme) <NEW_LINE> <DEDENT> return readme | Generate a new Readme.md | 625941dee1aae11d1e74a003 |
def _clear_cache(self): <NEW_LINE> <INDENT> if not self._is_mutable: <NEW_LINE> <INDENT> raise TypeError("cannot clear cache of immutable polyhedra") <NEW_LINE> <DEDENT> for ob in self._dependent_objects: <NEW_LINE> <INDENT> ob._polyhedron = None <NEW_LINE> <DEDENT> backend_object = self.__dict__["_" + self._backend_ob... | Clear the Vrepresentation and Hrepresentation data of ``self``.
TESTS::
sage: p = polytopes.permutahedron(4)
sage: P = p.parent()
sage: q = P._element_constructor_(p, mutable=True)
sage: TestSuite(q).run()
sage: q._clear_cache()
sage: TestSuite(q).run()
::
sage: q.set_immutable()
sag... | 625941ded18da76e23532822 |
def __init__(self, etree): <NEW_LINE> <INDENT> if isinstance(etree, compat.string_types): <NEW_LINE> <INDENT> etree = ElementTree.fromstring(etree) <NEW_LINE> <DEDENT> self.__dict__['_etree'] = etree | Initialize a new Element wrapper for ``etree``.
If ``etree`` is a string, then it will be converted to an
Element object using ``ElementTree.fromstring()`` first:
>>> ElementWrapper("<test></test>")
<Element "<?xml version='1.0' encoding='utf8'?>\n<test />"> | 625941ded58c6744b4257fa7 |
def build_attachment(self, attachment): <NEW_LINE> <INDENT> sendgridattachment = SendGridAttachment() <NEW_LINE> sendgridattachment.content = base64.b64encode( attachment.binarycontent).decode() <NEW_LINE> sendgridattachment.type = attachment.type <NEW_LINE> sendgridattachment.filename = attachment.originalfilename <NE... | Returns a valid sendgrid attachment from typical attachment object.
e.g
```
attachment = Attachment()
attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl"
"Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12")
attachment.type = "application/pdf"
attachment.filename = "balance_001.pdf"
att... | 625941de009cb60464c636f8 |
def pythagoreanTriplet(n): <NEW_LINE> <INDENT> triplet = tuple() <NEW_LINE> for a in range(1, n, 1): <NEW_LINE> <INDENT> for b in range(1, n - a, 1): <NEW_LINE> <INDENT> c = n - a - b <NEW_LINE> if (a * a) + (b * b) == (c * c): <NEW_LINE> <INDENT> triplet = triplet + (a, b, c) <NEW_LINE> return triplet <NEW_LINE> <DEDE... | Finds the Pythagorean triplet for n. | 625941de091ae356686672a2 |
def insertion_sort(lst): <NEW_LINE> <INDENT> for i in range(1, len(lst)): <NEW_LINE> <INDENT> idx = i - 1 <NEW_LINE> isrt_elmt = lst[i] <NEW_LINE> while idx >= 0 and isrt_elmt < lst[idx]: <NEW_LINE> <INDENT> lst[idx + 1] = lst[idx] <NEW_LINE> idx -= 1 <NEW_LINE> <DEDENT> lst[idx+1] = isrt_elmt <NEW_LINE> <DEDENT> retur... | 625941de596a897236089e06 | |
def test_create_index_variable_loop(): <NEW_LINE> <INDENT> create_index_variable_loop() | Test for creating a index variable loop | 625941de0383005118ecf92a |
def wait_until_report_finishes_being_generated(report_id): <NEW_LINE> <INDENT> while retrieve_report_status(report_id) in ['running', 'integrating', 'dispatched', 'started']: <NEW_LINE> <INDENT> sleep_seconds = 60 <NEW_LINE> print("[-] Report ID '{0}' is still being generated...sleeping {1} seconds.".format(report_id, ... | Given a report ID, sleep until the report finishes being generated.
| 625941de96565a6dacc8fa13 |
def __init__(self, redoTimeoutMin=None, redoTimeoutMax=None, **kwa): <NEW_LINE> <INDENT> kwa['kind'] = raeting.trnsKinds.message <NEW_LINE> if 'reid' not in kwa: <NEW_LINE> <INDENT> emsg = "Missing required keyword argumens: '{0}'".format('reid') <NEW_LINE> raise TypeError(emsg) <NEW_LINE> <DEDENT> super(Messengent, s... | Setup instance | 625941de283ffb24f3c55c47 |
def showtip(self): <NEW_LINE> <INDENT> self.active = True <NEW_LINE> if self.tipwindow or not self.text: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> x = self.widget.winfo_pointerx() + 16 <NEW_LINE> y = self.widget.winfo_pointery() + 16 <NEW_LINE> self.tipwindow = tw = Toplevel(self.widget) <NEW_LINE> tw.wm_overrider... | Displays the tooltip. | 625941ded268445f265b51b7 |
def __init__(self): <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> s.connect(('8.8.8.8', 0)) <NEW_LINE> self.ip_addr = s.getsockname()[0] <NEW_LINE> print('\nXiBot Router - xibrt') <NEW_LINE> print('\n******************************************') <NEW_LINE> print('Using router IP add... | This is the constructor for the XidecoRouter class.
:param: use_port_map: If true, use the ip address in the port map, if false, use discovered ip address
:return: None | 625941de236d856c2ad44b27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.