code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@contextlib.contextmanager <NEW_LINE> def tempdir(): <NEW_LINE> <INDENT> d = tempfile.mkdtemp() <NEW_LINE> yield d <NEW_LINE> shutil.rmtree(d) | Create a temporary directory.
Use as a context manager so the directory is automatically cleaned up.
>>> with tempdir() as tmpdir:
... print(tmpdir) # prints a folder like /tmp/randomname | 625941b68e05c05ec3eea18b |
def detectCycle(head): <NEW_LINE> <INDENT> if (head == None): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if (head.next == head): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if (head.next == None): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> point1 = head <NEW_LINE> point2 = head <NEW_LINE> inde... | :type head: ListNode
:rtype: ListNode | 625941b65fdd1c0f98dc004c |
def build_strings(self): <NEW_LINE> <INDENT> self.window_title = "Voice Emotion Recognizer" <NEW_LINE> self.main_label = "How are you Feeling today?" <NEW_LINE> self.quit_label = "Quit" <NEW_LINE> self.record_label = StringVar() <NEW_LINE> self.analyze_label = StringVar() <NEW_LINE> self.record_label.set("Record") <NEW... | Declares the String labels for many of the prompts and buttons used in this GUI.
:return: None | 625941b6be383301e01b52a7 |
def test_patch_request_remapped(self): <NEW_LINE> <INDENT> client = self._create_client('basic.json') <NEW_LINE> res = client.patch('/user/1') <NEW_LINE> expected = self._read_json('basic/user/userid_patch.json') <NEW_LINE> self.assertEqual(to_unicode(res.data), expected) | PATCH /user/<userid> should serve userid_patch.json. | 625941b6dd821e528d63afc5 |
def ugettext(message, **variables): <NEW_LINE> <INDENT> return _translate('ugettext', message, **variables) | Translates `message`. | 625941b69c8ee82313fbb58f |
def add_external_recurrence(self, incoming): <NEW_LINE> <INDENT> self.external_rec, _ = get_input(incoming) | Use this Layer as recurrent connections for the conLSTM instead of convLSTM hidden activations
Don't forget to make sure that the bias and weight shapes fit to new shape!
Parameters
-------
incoming : layer class, tensorflow tensor or placeholder
Incoming external recurrence for convLSTM layer as layer class or t... | 625941b6b57a9660fec3369a |
def __contains__(self, value): <NEW_LINE> <INDENT> return value in self._values | Checks whether value is contained within stored time points
Parameters
----------
value: value point to check for whether it is contained
Returns
-------
true if value point is contained else false | 625941b630bbd722463cbbdd |
def read(self, node): <NEW_LINE> <INDENT> if node == nullid: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> raw = self._read(hex(node)) <NEW_LINE> index, size = self._parsesize(raw) <NEW_LINE> return raw[(index + 1):(index + 1 + size)] | returns the file contents at this node | 625941b692d797404e303fa5 |
def SVGMatrixFromNode(node, context): <NEW_LINE> <INDENT> tagName = node.tagName.lower() <NEW_LINE> tags = ['svg:use', 'svg:symbol'] <NEW_LINE> if tagName not in tags and 'svg:' + tagName not in tags: <NEW_LINE> <INDENT> return Matrix() <NEW_LINE> <DEDENT> rect = context['rect'] <NEW_LINE> m = Matrix() <NEW_LINE> x = S... | Get transformation matrix from given node | 625941b61f5feb6acb0c496f |
def test_init(): <NEW_LINE> <INDENT> app = Flask('testapp') <NEW_LINE> ext = InvenioCommunities(app) <NEW_LINE> assert 'invenio-communities' in app.extensions <NEW_LINE> app = Flask('testapp') <NEW_LINE> ext = InvenioCommunities() <NEW_LINE> assert 'invenio-communities' not in app.extensions <NEW_LINE> ext.init_app(app... | Test extension initialization. | 625941b691af0d3eaac9b82e |
def _to_dict(self): <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'voices') and self.voices is not None: <NEW_LINE> <INDENT> _dict['voices'] = [x._to_dict() for x in self.voices] <NEW_LINE> <DEDENT> return _dict | Return a json dictionary representing this model. | 625941b601c39578d7e74c5e |
def serialize( self, required=None, label=None, initial=None, help_text=None, **kwargs ): <NEW_LINE> <INDENT> serialize_function = getattr(self, f"serialize_{self.data_type}") <NEW_LINE> serialized = serialize_function(initial, **kwargs) <NEW_LINE> serialized["data_type"] = self.data_type <NEW_LINE> serialized["name"] ... | Execute the serialize function appropriate for the current data type | 625941b6d99f1b3c44c673b2 |
def p_Ident_DOT(p): <NEW_LINE> <INDENT> p[0] = p[1] | Ident_DOT : Identifier_DOT
| 625941b6be8e80087fb20a69 |
def test_rus_fit_transform_half(): <NEW_LINE> <INDENT> ratio = 0.5 <NEW_LINE> rus = RandomUnderSampler(ratio=ratio, random_state=RND_SEED) <NEW_LINE> X_resampled, y_resampled = rus.fit_transform(X, Y) <NEW_LINE> currdir = os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> X_gt = np.load(os.path.join(currdir, 'data',... | Test the fit transform routine with a 0.5 ratio | 625941b65f7d997b871748b5 |
def save_params(self): <NEW_LINE> <INDENT> if not self.dynamic_env.has_key('PARAMETERS_FILE'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> file_path = preprocess(self.dynamic_env['PARAMETERS_FILE'], self.dynamic_env) <NEW_LINE> with open(file_path, "w") as f_param: <NEW_LINE> <INDENT> for k in self.dynamic_env.keys(... | Converts the input to a string and dumps it to provided file.
The file is only generated if local environment contains
a key called `PARAMETERS_FILE`. Otherwise we assume that the
user does not want a separate file.
TODO:generate a runnable yaml file. | 625941b6d4950a0f3b08c175 |
def evaluatePressure(self, t, c): <NEW_LINE> <INDENT> u_shape = c[('u', 0)].shape <NEW_LINE> grad_shape = c[('grad(u)', 0)].shape <NEW_LINE> if self.pressureIncrementModelIndex is None: <NEW_LINE> <INDENT> phi = np.zeros(c[('r', 0)][:].shape, 'd') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if u_shape == self.pressur... | Evaluate the coefficients after getting the specified velocity and density | 625941b66e29344779a62430 |
def _update_sprite_heading(self): <NEW_LINE> <INDENT> i = (int(self._heading + 5) % 360) / (360 / SHAPES) <NEW_LINE> if not self._hidden and self.spr is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.spr.set_shape(self._shapes[i]) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> self.spr.set_shap... | Update the sprite to reflect the current heading | 625941b6ab23a570cc24ff9a |
def __init__(self,house=None, api_type=None, api_name=None, schema=None, entry_columns=None): <NEW_LINE> <INDENT> self.house = house <NEW_LINE> self.api_type = api_type <NEW_LINE> self.api_name = api_name <NEW_LINE> self.schema = schema <NEW_LINE> self.table = ('_').join([self.house, self.api_type, self.api_name]) <NEW... | Parent class for data capture.
:param house: str
:param api_type: str
:param api_name: str
:param schema: str
:param entry_columns: list | 625941b68a43f66fc4b53e84 |
def warning(self, message): <NEW_LINE> <INDENT> c_warning_color = '\033[93m' <NEW_LINE> c_endc = '\033[0m' <NEW_LINE> print(c_warning_color + message + c_endc) <NEW_LINE> if self.out_widget: <NEW_LINE> <INDENT> w_warning_color = "<font color=\"Yellow\">" <NEW_LINE> w_endc = "</font>" <NEW_LINE> self.out_widget.append(w... | @brief Error messaging | 625941b69b70327d1c4e0bee |
def error(self): <NEW_LINE> <INDENT> error_array = [] <NEW_LINE> if self._response_error: <NEW_LINE> <INDENT> error_array.append(self._response_error) <NEW_LINE> <DEDENT> error_array.extend(self._get_resp_body_errors()) <NEW_LINE> if len(error_array) > 0: <NEW_LINE> <INDENT> error_string = "%s: %s" % (self.verb, ", ".j... | Builds and returns the api error message. | 625941b624f1403a92600984 |
def get_distance_from_point(self, p_end): <NEW_LINE> <INDENT> a = numpy.array((self.base_position.x, self.base_position.y, self.base_position.z)) <NEW_LINE> b = numpy.array((p_end.x, p_end.y, p_end.z)) <NEW_LINE> distance = numpy.linalg.norm(a - b) <NEW_LINE> return distance | Given a Vector3 Object, get distance from current position
:param p_end:
:return: | 625941b616aa5153ce362293 |
def _observedFromPupilCoords(xPupil, yPupil, obs_metadata=None, includeRefraction=True, epoch=2000.0): <NEW_LINE> <INDENT> are_arrays = _validate_inputs([xPupil, yPupil], ['xPupil', 'yPupil'], "observedFromPupilCoords") <NEW_LINE> if obs_metadata is None: <NEW_LINE> <INDENT> raise RuntimeError("Cannot call observedFrom... | Convert pupil coordinates into observed (RA, Dec)
@param [in] xPupil -- pupil coordinates in radians.
Can be a numpy array or a number.
@param [in] yPupil -- pupil coordinates in radians.
Can be a numpy array or a number.
@param [in] obs_metadata -- an instantiation of ObservationMetaData characterizing
the state of... | 625941b6e8904600ed9f1d43 |
def to_jd(year, dayofyear): <NEW_LINE> <INDENT> return gregorian.to_jd(year, 1, 1) + dayofyear - 1 | Return Julian day count of given ordinal date. | 625941b699cbb53fe6792a02 |
def save_object(self): <NEW_LINE> <INDENT> signals.crud_pre_save.send(self, current=self.current, object=self.object) <NEW_LINE> obj_is_new = not self.object.exist <NEW_LINE> self.object.blocking_save() <NEW_LINE> signals.crud_post_save.send(self, current=self.current, object=self.object) | Saves object into DB.
Triggers pre_save and post_save signals.
Sets task_data['``added_obj``'] if object is new. | 625941b6293b9510aa2c30b4 |
def quartiles(self) -> t.Tuple[float, float, float]: <NEW_LINE> <INDENT> return self.percentile(25), self.percentile(50), self.percentile(75) | Calculates the 3 quartiles (1, 2 and 3) | 625941b624f1403a92600985 |
def plot_slice(self, data, idx): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> plt.imshow(data[idx, :, :], cmap='gray') <NEW_LINE> plt.axis('off') <NEW_LINE> plt.show() <NEW_LINE> return | PLOT_SLICE
Show one slice according to the given index. | 625941b6099cdd3c635f0a77 |
def throttling_all(*validators): <NEW_LINE> <INDENT> def decorator(klass): <NEW_LINE> <INDENT> dispatch = getattr(klass, 'dispatch') <NEW_LINE> setattr(klass, 'dispatch', throttling(*validators)(dispatch)) <NEW_LINE> return klass <NEW_LINE> <DEDENT> return decorator | Adds throttling validators to a class. | 625941b6442bda511e8be241 |
def replace(interval=Unchanged, count=Unchanged, until=Unchanged, exceptions=Unchanged, monthly=Unchanged): <NEW_LINE> <INDENT> pass | Return a copy of this recurrence rule with new specified fields. | 625941b663b5f9789fde6f00 |
def GetAccountInfo(self, sessionID, liveTradeID, key): <NEW_LINE> <INDENT> pass | Parameters:
- sessionID
- liveTradeID
- key | 625941b66aa9bd52df036bbd |
def __init__(self, s): <NEW_LINE> <INDENT> self.s = s <NEW_LINE> self.pw = pw = [1] * (len(s) + 1) <NEW_LINE> l = len(s) <NEW_LINE> self.h = h = [0] * (l + 1) <NEW_LINE> v = 0 <NEW_LINE> for i in range(l): <NEW_LINE> <INDENT> h[i + 1] = v = (v * self.base + ord(s[i])) % self.mod <NEW_LINE> <DEDENT> v = 1 <NEW_LINE> for... | sに関するローリングハッシュを構築する O(|s|)
cf. |s|<=5000 の構築で最大200ms程度 | 625941b615fb5d323cde0924 |
def get_courses(self, branch='published', qualifiers=None): <NEW_LINE> <INDENT> if qualifiers is None: <NEW_LINE> <INDENT> qualifiers = {} <NEW_LINE> <DEDENT> qualifiers.update({"versions.{}".format(branch): {"$exists": True}}) <NEW_LINE> matching = self.db_connection.find_matching_course_indexes(qualifiers) <NEW_LINE>... | Returns a list of course descriptors matching any given qualifiers.
qualifiers should be a dict of keywords matching the db fields or any
legal query for mongo to use against the active_versions collection.
Note, this is to find the current head of the named branch type
(e.g., 'draft'). To get specific versions via g... | 625941b6a4f1c619b28afe5d |
def bfs_traverse(lista): <NEW_LINE> <INDENT> nodes = [lista[1], lista[2]] <NEW_LINE> yield lista[0] <NEW_LINE> for q in nodes: <NEW_LINE> <INDENT> yield q[0] if q[0] is not None else () <NEW_LINE> nodes.append(q[1]) if q[1] is not None else () <NEW_LINE> nodes.append(q[2]) if q[2] is not None else () | Przejscie bfs | 625941b699fddb7c1c9de1ae |
def CheckForHeaderGuard(filename, lines, error): <NEW_LINE> <INDENT> cppvar = GetHeaderGuardCPPVariable(filename) <NEW_LINE> ifndef = None <NEW_LINE> ifndef_linenum = 0 <NEW_LINE> define = None <NEW_LINE> endif = None <NEW_LINE> endif_linenum = 0 <NEW_LINE> for linenum, line in enumerate(lines): <NEW_LINE> <INDENT> lin... | Checks that the file contains a header guard.
Logs an error if no #ifndef header guard is present. For other
headers, checks that the full pathname is used.
Args:
filename: The name of the C++ header file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any er... | 625941b65fcc89381b1e14df |
def on_intent(intent_request, session): <NEW_LINE> <INDENT> print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) <NEW_LINE> intent = intent_request['intent'] <NEW_LINE> intent_name = intent_request['intent']['name'] <NEW_LINE> if intent_name == "FeedIntent": <NEW_LINE> <IN... | Called when the user specifies an intent for this skill | 625941b6e5267d203edcdabc |
def poll(self, message, timeout=None): <NEW_LINE> <INDENT> if not timeout: <NEW_LINE> <INDENT> timeout = self.poll_timeout.duration <NEW_LINE> <DEDENT> msg_len = len(message) <NEW_LINE> if msg_len > 0xFFFE: <NEW_LINE> <INDENT> raise JobError("Message was too long to send!") <NEW_LINE> <DEDENT> c_iter = 0 <NEW_LINE> res... | Blocking, synchronous polling of the Coordinator on the configured port.
Single send operations greater than 0xFFFF are rejected to prevent truncation.
:param msg_str: The message to send to the Coordinator, as a JSON string.
:return: a JSON string of the response to the poll | 625941b6be7bc26dc91cd421 |
def _splitSeries(self, aoSeries): <NEW_LINE> <INDENT> if len(aoSeries) <= 1: <NEW_LINE> <INDENT> if len(aoSeries) < 1: <NEW_LINE> <INDENT> return []; <NEW_LINE> <DEDENT> return [aoSeries,]; <NEW_LINE> <DEDENT> dUnitSeries = dict(); <NEW_LINE> for oSeries in aoSeries: <NEW_LINE> <INDENT> if oSeries.iUnit not in dUnitSer... | Splits the data series (ReportGraphModel.DataSeries) into one or more graphs.
Returns an array of data series arrays. | 625941b6a17c0f6771cbde6f |
def clean_up(): <NEW_LINE> <INDENT> catalog_dir = os.path.join(prefs.pref('ManagedInstallDir'), 'catalogs') <NEW_LINE> for item in os.listdir(catalog_dir): <NEW_LINE> <INDENT> if item not in _CATALOG: <NEW_LINE> <INDENT> os.unlink(os.path.join(catalog_dir, item)) | Removes any catalog files that are no longer in use by this client | 625941b6507cdc57c6306aed |
def setXr(self, Xr): <NEW_LINE> <INDENT> return _core.CKroneckerCF_setXr(self, Xr) | setXr(CKroneckerCF self, limix::CovarInput const & Xr)
Parameters
----------
Xr: limix::CovarInput const & | 625941b631939e2706e4cc8c |
def __init__(self, include_related_objects=None): <NEW_LINE> <INDENT> self.swagger_types = { 'include_related_objects': 'bool' } <NEW_LINE> self.attribute_map = { 'include_related_objects': 'include_related_objects' } <NEW_LINE> self._include_related_objects = include_related_objects | RetrieveCatalogObjectRequest - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941b6a05bb46b383ec648 |
def energy_step(inputs, states): <NEW_LINE> <INDENT> assert_msg = "States must be a list. However states {} is of type {}".format(states, type(states)) <NEW_LINE> assert isinstance(states, list) or isinstance(states, tuple), assert_msg <NEW_LINE> """ Some parameters required for shaping tensors""" <NEW_LINE> batch_size... | Step function for computing energy for a single decoder state | 625941b660cbc95b062c6364 |
def get_nearest_room(rooms, list_of_rooms): <NEW_LINE> <INDENT> starting_room = None <NEW_LINE> nearest_room = None <NEW_LINE> center_point = midpoint(rooms) <NEW_LINE> for room in list_of_rooms: <NEW_LINE> <INDENT> new_center = midpoint(rooms) <NEW_LINE> dist = ((new_center[0] - center_point[0]) ** 2 + (new_center[1] ... | Helper function for finding the nearest room on builting bridges
Args:
rooms(int)
list_of_rooms(list): | 625941b6fff4ab517eb2f254 |
def test_corr_actual_video(self): <NEW_LINE> <INDENT> eval = VideoEvaluator(vid_metric='ME profile correlation') <NEW_LINE> val = eval(recon_vid_list,true_vid_list) <NEW_LINE> print(np.mean(val)) <NEW_LINE> self.assertEqual(val.flatten(), 721050) | Test profile correlation evaluation for true and reconstructed image
| 625941b6099cdd3c635f0a78 |
def _pmtkAck(self, sentence): <NEW_LINE> <INDENT> keywords = ['PMTK', 'command', 'flag'] <NEW_LINE> return self._mixhash(keywords, sentence) | convert the ack message | 625941b6c4546d3d9de7284c |
def handlers_for_address(self, path): <NEW_LINE> <INDENT> def callback(path, *args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> log('Calling {} for {}'.format(actions[path].__name__, path)) <NEW_LINE> actions[path](*args) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> log('No callback for {}'.format(path)) ... | yields Handler namedtuples matching the given OSC pattern. | 625941b6ac7a0e7691ed3ef5 |
def can_bid(self, member): <NEW_LINE> <INDENT> if self.get_last_bidder() == member: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return member.auction_bids_left(self) | Returns True if the member has commited bids left to use on the
auction, and its not the last bidder. | 625941b68e71fb1e9831d5c9 |
def OnEraseBackground(self, event): <NEW_LINE> <INDENT> if not self._backgroundImage: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self._imageStretchStyle == _StyleTile: <NEW_LINE> <INDENT> dc = event.GetDC() <NEW_LINE> if not dc: <NEW_LINE> <INDENT> dc = wx.ClientDC(self) <NEW_LINE> rect = self.GetUpdateRegion().... | Handles the wx.EVT_ERASE_BACKGROUND event. | 625941b6283ffb24f3c55728 |
def _paje_clca(self, agem_holder, af_nbenf, paje_base, inactif, partiel1, partiel2, P = law.fam): <NEW_LINE> <INDENT> agem = self.split_by_roles(agem_holder, roles = ENFS) <NEW_LINE> paje = paje_base >= 0 <NEW_LINE> age_m_benjamin = age_en_mois_benjamin(agem) <NEW_LINE> condition1 = (af_nbenf == 1) * (age_m_benjamin >=... | Prestation d'accueil du jeune enfant - Complément de libre choix d'activité
'fam'
Parameters:
-----------
age : âge en mois
af_nbenf : nombre d'enfants aus sens des allocations familiales
paje_base : allocation de base de la PAJE
inactif : indicatrice d'inactivité
partiel1 : Salarié: Temps de travail ne dépassant pa... | 625941b6796e427e537b03dd |
def testTruncateTCEDNS(self): <NEW_LINE> <INDENT> name = 'atruncatetc.tests.powerdns.com.' <NEW_LINE> query = dns.message.make_query(name, 'A', 'IN', use_edns=True, payload=4096, want_dnssec=True) <NEW_LINE> response = dns.message.make_response(query, our_payload=4242) <NEW_LINE> rrset = dns.rrset.from_text(name, 3600,... | Basics: Truncate TC with EDNS
dnsdist is configured to truncate TC (default),
we make the backend send responses
with TC set and additional content,
and check that the received response has been fixed.
Note that the query and initial response had EDNS,
so the final response should have it too. | 625941b6d10714528d5ffafa |
def __init__(self, int=stats.DUMB): <NEW_LINE> <INDENT> self.int = int <NEW_LINE> self.wantToMove = False <NEW_LINE> logic.ALLTHINGS.add(self) <NEW_LINE> logic.AIs.append(self) | judges when to fire and when to move | 625941b67c178a314d6ef273 |
def start_citationref(self, attrs): <NEW_LINE> <INDENT> handle = self.inaugurate(attrs['hlink'], "citation", Citation) <NEW_LINE> self.__add_citation(handle) | Add a citation reference to the object currently processed. | 625941b6e64d504609d7465c |
def winning_minimal_coalitions(players, quota): <NEW_LINE> <INDENT> min_to_max_weight = [i[0] for i in sorted(players.items(), key=itemgetter(1))] <NEW_LINE> max_to_min_weight = [i[0] for i in sorted(players.items(), key=itemgetter(1), reverse=True)] <NEW_LINE> min_players = number_players_search(max_to_min_weight, pl... | List the minimal coalitions that win the game.
Parameters
players : dictionary
Name of the the players and their weights.
quota : int
Necesary weight to win the game.
Yields
-------
list
A minimal coalition. | 625941b6090684286d50eafb |
def encode_image(image_file): <NEW_LINE> <INDENT> encoded = base64.b64encode(open(image_file, 'rb').read()) <NEW_LINE> return 'data:image/png;base64,{}'.format(encoded.decode()) | Function: encodes a png image | 625941b60fa83653e4656dd9 |
def __init__(self, bot, db_runner, logger): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> self.db_runner = db_runner <NEW_LINE> self.logger = logger | initialization View | 625941b6097d151d1a222c78 |
def ground_fd(fd, objective, tbox, abox): <NEW_LINE> <INDENT> fg = tbox.FunctionGrounding("fg_"+fd.name.replace('fd_', ''), namespace=abox, typeFD=fd, solvesO=objective) <NEW_LINE> return fg | Given a FunctionDesign fd and an Objective objective,
creates an individual FunctionGrounds with typeF fd and solve) objective
returns the fg | 625941b6091ae35668666d81 |
@permission_required('shadowsocks') <NEW_LINE> def donateData(request): <NEW_LINE> <INDENT> data = [Donate.totalDonateNums(), int(Donate.totalDonateMoney())] <NEW_LINE> result = json.dumps(data, ensure_ascii=False) <NEW_LINE> return HttpResponse(result, content_type='application/json') | 返回捐赠信息
捐赠笔数
捐赠总金额 | 625941b6d10714528d5ffafb |
def emphasize(s): <NEW_LINE> <INDENT> print('\n\033[1m{}\033[0m'.format(s)) | Like print(), but emphasizes the line using ANSI escape sequences. | 625941b6d6c5a10208143e63 |
def load_key(self): <NEW_LINE> <INDENT> file = open(self.key) <NEW_LINE> for line in file: <NEW_LINE> <INDENT> x = line.strip().split(";") <NEW_LINE> key =x[0] <NEW_LINE> value = list(eval(x[1])) <NEW_LINE> self.dic_list[key] = value <NEW_LINE> <DEDENT> file.close() | loads a text file containing the names and numeric values and saves it to a dict | 625941b62eb69b55b151c6c6 |
def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> super(SearchInputSet, self)._set_input('ResponseFormat', value) | Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Can be set to xml or json. Defaults to json.) | 625941b621a7993f00bc7b05 |
def _destructively_unify(feature1, feature2, bindings1, bindings2, memo, fail, depth=0): <NEW_LINE> <INDENT> if depth > 50: <NEW_LINE> <INDENT> print("Infinite recursion in this unification:") <NEW_LINE> print(show(dict(feature1=feature1, feature2=feature2, bindings1=bindings1, bindings2=bindings2, memo=memo))) <NEW_LI... | Attempt to unify C{self} and C{other} by modifying them
in-place. If the unification succeeds, then C{self} will
contain the unified value, and the value of C{other} is
undefined. If the unification fails, then a
UnificationFailure is raised, and the values of C{self}
and C{other} are undefined. | 625941b697e22403b379cdb4 |
def to_json(result_dict, filename): <NEW_LINE> <INDENT> with open(filename, 'w') as f: <NEW_LINE> <INDENT> content = json.dumps(result_dict) <NEW_LINE> f.write(content) | Save test results to status.json | 625941b623849d37ff7b2eae |
def start_ipykernel(self, client, wdir=None, give_focus=True): <NEW_LINE> <INDENT> if not self.get_option('monitor/enabled'): <NEW_LINE> <INDENT> QMessageBox.warning(self, _('Open an IPython console'), _("The console monitor was disabled: the IPython kernel will " "be started as expected, but an IPython console will ha... | Start new IPython kernel | 625941b6b57a9660fec3369b |
def onDisconnected(self, reason): <NEW_LINE> <INDENT> self.connectionStatus = False <NEW_LINE> self.loginStatus = False <NEW_LINE> self.gateway.mdConnected = False <NEW_LINE> content = (u'行情服务器连接断开,原因:%s' %reason) <NEW_LINE> self.writeLog(content) | 连接断开 | 625941b6a17c0f6771cbde70 |
def getAllAlignments(self): <NEW_LINE> <INDENT> lAlignments = [] <NEW_LINE> with open(self.inputBlastXMLFile, 'r') as input : <NEW_LINE> <INDENT> blast_records = NCBIXML.parse(input) <NEW_LINE> index = 0 <NEW_LINE> for blast_record in blast_records: <NEW_LINE> <INDENT> logging.debug('QUERY: {}'.format(blast_record.que... | Return list of all Alignments | 625941b6187af65679ca4f39 |
def roi_pooling(input, rois, size=(7, 7), spatial_scale=1.0): <NEW_LINE> <INDENT> assert (rois.dim() == 2) <NEW_LINE> assert (rois.size(1) == 4) <NEW_LINE> output = [] <NEW_LINE> rois = rois.data.float() <NEW_LINE> num_rois = rois.size(0) <NEW_LINE> rois.mul_(spatial_scale) <NEW_LINE> rois = rois.long() <NEW_LINE> for ... | :param input: input feature or images (batch_size,channel,height,width)
:param rois: cropped bboxing (batch_size,bbox), bbox=[x1,y1,x2,y2]
:param size: output size (height,width)
:param spatial_scale: down scale bboxes
:return: (batch_size,channel,cropped_height,cropped_width) | 625941b6796e427e537b03de |
def get_resource_parts(self): <NEW_LINE> <INDENT> if not self.is_api_request(): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> parts_list = list(filter(lambda x: x.replace(' ', '') != '', self.path.split(API_PATH))) <NEW_LINE> if len(parts_list) <= 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return list(fil... | Returns a list of resource parts: if URL is 'API_PATH/foo/bar' it returns ['foo', 'bar']
If not is a valid API_REQUEST, returns an empty list | 625941b650812a4eaa59c142 |
def read(self, params, file_name): <NEW_LINE> <INDENT> self.geometry = read_polydata(file_name) | Read centerlines from a .vtp file. | 625941b63617ad0b5ed67d1b |
def prefix_notation(node): <NEW_LINE> <INDENT> pass | Fill this in! | 625941b6be7bc26dc91cd422 |
def Score(self, Ranges, pose, sigma=1.0): <NEW_LINE> <INDENT> dis = 0.0 <NEW_LINE> score = 1.0 <NEW_LINE> for i in range(self.BeaconSet.shape[0]): <NEW_LINE> <INDENT> dis = np.linalg.norm(self.BeaconSet[i, :] - pose) <NEW_LINE> if Ranges[i] > 0.0: <NEW_LINE> <INDENT> score *= (self.NormPdf(Ranges[i], dis, sigma) + 1e-5... | METHOnd 2 | 625941b6e5267d203edcdabd |
def math_from_doc(fitfunc, maxlen=np.inf): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = fitfunc.__doc__ <NEW_LINE> res = res.replace(':math:', '') <NEW_LINE> res = res.replace('`', '$') <NEW_LINE> if len(res) > maxlen: <NEW_LINE> <INDENT> term = res.find(" + ", 0, len(res)) <NEW_LINE> res = res[:term+2]+' ...$' <... | convert sphinx compatible math to matplotlib/tex | 625941b6596a8972360898e6 |
def testAllOfUserGroupPermissionSet(self): <NEW_LINE> <INDENT> pass | Test AllOfUserGroupPermissionSet | 625941b68e05c05ec3eea18d |
def _assign_to_grid(self): <NEW_LINE> <INDENT> grid_locals = sys._getframe(2).f_locals <NEW_LINE> grid_cls_cols = grid_locals.setdefault('__cls_cols__', []) <NEW_LINE> grid_cls_cols.append(self) | Columns being set up in declarative fashion need to be attached to the class
somewhere. In WebGrid, we have a class attribute `__cls_cols__` that columns
append themselves to. Subclasses, use of mixins, etc. will combine these column
lists elsewhere. | 625941b663b5f9789fde6f01 |
def hdfs_delete(server, username, path, **args): <NEW_LINE> <INDENT> response = _namenode_request(server, username, 'DELETE', path, 'DELETE', args) <NEW_LINE> content = response.read() <NEW_LINE> _check_code(response.status, content) <NEW_LINE> boolean_json = json.loads(content) <NEW_LINE> return boolean_json['boolean'... | Make a directory. | 625941b6cad5886f8bd26dfe |
def run(): <NEW_LINE> <INDENT> DataDirBase = "./DataByVoltage/" <NEW_LINE> Voltages = GetImageJData(DataDirBase,ext=".xls") <NEW_LINE> OverhangObjsByVoltage = ConvertToOverhangObjects(Voltages) <NEW_LINE> Distributions = OrderedDict() <NEW_LINE> for Volt,AllLanes in OverhangObjsByVoltage.items(): <NEW_LINE> <INDENT> Al... | Shows how the concatemeters etc change with voltage | 625941b67b25080760e39277 |
def __init__(self, visualizer, gc): <NEW_LINE> <INDENT> self.agent_dict = {} <NEW_LINE> self.agent_list = [] <NEW_LINE> self.new_agents = [] <NEW_LINE> self.visualizer = visualizer <NEW_LINE> self.gc = gc | Initializes an abm with the given number of agents and returns it
:return: An initialized ABM. | 625941b6167d2b6e312189ba |
def test_diff_output_bad_path(builddir): <NEW_LINE> <INDENT> runner = CliRunner() <NEW_LINE> result = runner.invoke( main.cli, ["--debug", "--path", builddir, "diff", "src/baz.py"], catch_exceptions=False, ) <NEW_LINE> assert result.exit_code == 0, result.stdout <NEW_LINE> assert "test.py" not in result.stdout | Test the diff feature with no changes | 625941b650485f2cf553cbb5 |
def predictive_entropy(x): <NEW_LINE> <INDENT> return entropy(np.mean(x, axis=1)) | Take a tensor of MC predictions [#images x #MC x #classes] and return the
entropy of the mean predictive distribution across the MC samples. | 625941b64527f215b584c277 |
def pna_csv_2_ntwks3(filename): <NEW_LINE> <INDENT> header, comments, d = read_pna_csv(filename) <NEW_LINE> col_headers = pna_csv_header_split(filename) <NEW_LINE> z0 = npy.ones((npy.shape(d)[0]))*50 <NEW_LINE> f = d[:,0]/1e9 <NEW_LINE> name = os.path.splitext(os.path.basename(filename))[0] <NEW_LINE> if 'db' in header... | Read a CSV file exported from an Agilent PNA in dB/deg format
Parameters
--------------
filename : str
full path or filename
Returns
---------
out : n
2-Port Network
Examples
---------- | 625941b692d797404e303fa7 |
def add_item(self, mol_name=None, mol_cont=None): <NEW_LINE> <INDENT> if len(self) and self.is_empty(): <NEW_LINE> <INDENT> self[0].mol_name = mol_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(len(self)): <NEW_LINE> <INDENT> if self[i].mol_name == mol_name: <NEW_LINE> <INDENT> raise RelaxError("The ... | Append the given MolContainer instance to the MolList.
@keyword mol_name: The molecule number.
@type mol_name: int
@keyword mol_cont: The data structure for the molecule.
@type mol_cont: MolContainer instance
@return: The new molecule container.
@rtype: MolConta... | 625941b64e4d5625662d41fa |
def z(self, zw): <NEW_LINE> <INDENT> return zw * (np.cos(self.beta-self.omega))/(np.cos(self.beta) * np.cos(self.omega)) | Depth below the sloping ground surface | 625941b691af0d3eaac9b830 |
def list_keys( self, resource_group_name, namespace_name, topic_name, authorization_rule_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/a... | Gets the primary and secondary connection strings for the topic.
:param resource_group_name: Name of the Resource group within the
Azure subscription.
:type resource_group_name: str
:param namespace_name: The namespace name
:type namespace_name: str
:param topic_name: The topic name.
:type topic_name: str
:param auth... | 625941b655399d3f055884d0 |
def ZeroEvecs(n): <NEW_LINE> <INDENT> matrix = allJ(n) <NEW_LINE> evals, evecs = linalg.eig(matrix) <NEW_LINE> evecst = np.transpose(evecs) <NEW_LINE> sevecs = [np.zeros(2**n)] <NEW_LINE> for i in range(len(evals)): <NEW_LINE> <INDENT> if np.round(evals[i], 5)==0: <NEW_LINE> <INDENT> sevecs = np.append(sevecs, [evecst[... | Gives the eigenvectors of total S_y operator with zero eigenvalue | 625941b6d58c6744b4257a7d |
def strip_actions(self, model_path, folder): <NEW_LINE> <INDENT> path, model_file = os.path.split(model_path) <NEW_LINE> with open(model_path, 'r') as mf: <NEW_LINE> <INDENT> mlines = mf.readlines() <NEW_LINE> stripped_lines = filter(lambda x: self._not_action(x), mlines) <NEW_LINE> <DEDENT> stripped_model = os.path.jo... | Strips actions from a BNGL folder and makes a copy
into the given folder | 625941b6925a0f43d2549c90 |
def nav(items=[],delimiter="|",extra=[]): <NEW_LINE> <INDENT> ... <NEW_LINE> nav = """<nav {0}>\n""".format(" ".join(extra)) <NEW_LINE> for i in range(len(items)): <NEW_LINE> <INDENT> if i != len(items)-1: <NEW_LINE> <INDENT> nav += """{0} {1}\n""".format(items[i],delimiter) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | writes the the itmes inside the nav seperated by delimiter
-----
>>link1 = link("home","/home")
>>link2 = link("contact","/contact")
>>link3 = link("about us","/about us")
>>print(nav([link1,link2,link3]))
<nav>
<a href="/home" target="_blank" title="">home</a> |
<a href="/contact" target="_blank" title="">contact</a>... | 625941b61b99ca400220a8cd |
def scheduled_plans_for_space(self, space_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.scheduled_plans_for_space_with_http_info(space_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.scheduled_pl... | Scheduled Plans for Space
### Get scheduled plans by using a space id for the requesting user.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprin... | 625941b6cb5e8a47e48b78cc |
def notify_restart(self, name, **kw): <NEW_LINE> <INDENT> print(u"SSD1306 plugin: received restart signal; turning off LCD...") <NEW_LINE> try: <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> print(u"SSD1306 plugin: Exception caught while trying to stop") <NEW_LINE> trace... | Restart handler | 625941b6236d856c2ad445fb |
def get_query_executions(ids): <NEW_LINE> <INDENT> response = athena_client.batch_get_query_execution( QueryExecutionIds=ids ) <NEW_LINE> return response['QueryExecutions'] | Retrieve details on the provided query execuution IDs | 625941b60383005118ecf401 |
def can_run_in_direction(vDict): <NEW_LINE> <INDENT> if not vDict['runInDirection']: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> player_coords = vDict['gameLevel'].player.co <NEW_LINE> level = vDict['gameLevel'] <NEW_LINE> player = level.player <NEW_LINE> player_coords = player.co <NEW_LINE> new_coords = playe... | Runs a serise of checks to see if the player can "run" in a direction. First it checks to see if the grid tile
in front of the player can be moved through.
there are any
other enties in the player's sight. Then it checks to see if FInaly, it checks if any the 9 * 9 grid of tiles ajacent to the player is different then... | 625941b6435de62698dfda71 |
def _init_observation_spec(self): <NEW_LINE> <INDENT> if self._to_float: <NEW_LINE> <INDENT> pixels_dtype = np.float <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pixels_dtype = np.uint8 <NEW_LINE> <DEDENT> if self._grayscaling: <NEW_LINE> <INDENT> pixels_spec_shape = (self._height, self._width) <NEW_LINE> pixels_spec_... | Computes the observation spec for the pixel observations.
Returns:
An `Array` specification for the pixel observations. | 625941b61f037a2d8b94601b |
def __init__(self, filepath, report, date_list): <NEW_LINE> <INDENT> self.report = report <NEW_LINE> self.date_list = date_list <NEW_LINE> self.workbook = xlsxwriter.Workbook(filepath) <NEW_LINE> self.worksheet = self.workbook.add_worksheet() <NEW_LINE> self.worksheet.set_column('A:B', 20) <NEW_LINE> self.finalized = F... | Initialize an ExcelSheetHelper by creating an XLSX Workbook | 625941b63539df3088e2e168 |
def get_compatiblility(spacecraft_ch): <NEW_LINE> <INDENT> gs_chs = compatibility_models.ChannelCompatibility.objects.filter( spacecraft_channel=spacecraft_ch ) <NEW_LINE> for g in gs_chs: <NEW_LINE> <INDENT> print(g) <NEW_LINE> <DEDENT> compatible_tuples = [ ( c.groundstation_channel.groundstation, c.groundstation_cha... | Common method
Returns the tuples (GS, GS_CH) with the compatible Ground Station
channels with the given spacecraft channel.
:param spacecraft_ch: The channel for which the tuples are compatible with
:return: List with the (GS, GS_CH) tuples | 625941b64a966d76dd550e28 |
def reprojShapefile(sourcepath, outpath=None, newprojdictionary={'proj': 'longlat', 'ellps': 'WGS84', 'datum': 'WGS84'}): <NEW_LINE> <INDENT> if isinstance(outpath, type(None)): <NEW_LINE> <INDENT> outpath = sourcepath <NEW_LINE> <DEDENT> shpfile = gpd.GeoDataFrame.from_file(sourcepath) <NEW_LINE> shpfile = shpfile.to_... | Convert a shapefile into a new projection
sourcepath: (dir) the path to the .shp file
newprojdictionary: (dict) the new projection definitions (default is longlat projection with WGS84 datum)
outpath: (dir) the output path for the new shapefile | 625941b6b545ff76a8913c3c |
def __init__(self, *args): <NEW_LINE> <INDENT> this = _ArNetworkingPy.new_ArServerSimpleServerCommands(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this | __init__(self, ArServerHandlerCommands commands, ArServerBase server,
bool addLogConnections = True) -> ArServerSimpleServerCommands
__init__(self, ArServerHandlerCommands commands, ArServerBase server) -> ArServerSimpleServerCommands | 625941b61f037a2d8b94601c |
def first_nonrepeating (s): <NEW_LINE> <INDENT> if isinstance(s,str): <NEW_LINE> <INDENT> if (len(s)==0 or (s[0]=='\t') or (s[0]==' ')): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> order = [] <NEW_LINE> counts = {} <NEW_LINE> for x in s: <NEW_LINE> <INDENT> if x in counts: <NEW_LINE> <INDENT> counts[x] += 1 <NE... | :returns first unique letter | 625941b630dc7b7665901787 |
def _initialize_chain(self, test_dir, num_nodes, cachedir): <NEW_LINE> <INDENT> assert num_nodes <= MAX_NODES <NEW_LINE> create_cache = False <NEW_LINE> for i in range(MAX_NODES): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join(cachedir, 'node' + str(i))): <NEW_LINE> <INDENT> create_cache = True <NEW_LINE> break ... | Initialize a pre-mined blockchain for use by the test.
Create a cache of a 200-block-long chain (with wallet) for MAX_NODES
Afterward, create num_nodes copies from the cache. | 625941b6462c4b4f79d1d4ed |
def save_file(self, filename, encoding='utf8', headers=None, convertors=None, display=True, **kwargs): <NEW_LINE> <INDENT> global save_file <NEW_LINE> convertors = convertors or {} <NEW_LINE> headers = headers or [] <NEW_LINE> fields = self.get_fields() <NEW_LINE> _header = [] <NEW_LINE> for i, column in enumerate(fiel... | save result to a csv file.
display = True will convert value according choices value | 625941b663b5f9789fde6f02 |
def solvr_nonlinear_osc(Y, t, bound = 0.01): <NEW_LINE> <INDENT> Q = 100.0 <NEW_LINE> gain = 10.0 <NEW_LINE> beta = 1 <NEW_LINE> return [ Y[1], -(Y[0] + Y[1]/Q + beta*Y[0]**3) + np.clip(gain*Y[1], -1.0*bound, 1.0*bound), ] | Now let me move on to the self-sustaining oscillator, nonlinear case
x'' + (1+x^2)x'/Q + x + beta * x**3== clip(gain*x)
omega will set to be resonance, i.e. 1# define the ODE for linear oscillator
the clipping function np.clip(input, lower_bound, upper_bound)
will prevent the divergence | 625941b66aa9bd52df036bbf |
def retrieve(self, request, pk=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> breath_sounds = BreathSounds.objects.get(pk=pk) <NEW_LINE> serializer = BreathSoundsDropdownSerializer(breath_sounds, context={'request': request}) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> except Exception as ex: <... | Handle GET requests for BreathSounds
Returns:
Response -- JSON serialized patient instance | 625941b656ac1b37e6263ffd |
def make_bams(paired,fasta,in_file, out_file, length = 35, std = 1, index_file = "temp.index", sam_file = "temp.sam"): <NEW_LINE> <INDENT> cmd = make_kallisto_index_command(fasta, index_file) <NEW_LINE> output = run_commandline(cmd) <NEW_LINE> write_log("KALLISTO INDEX",output) <NEW_LINE> if paired == "": <NEW_LINE> <I... | mapps the reads in a fastq file to the genome in a fasta file, makes a log of the steps taken
keyword arguments:
fasta: str, name of the fasta file containing the genome (or transcriptome)
in_file: str, the name of the (first) fastq file with the reads to be mapped
paired: str, the name of the second fastq ... | 625941b65e10d32532c5ed4c |
def test_schedule_cron_style_policy_with_invalid_cron_month(self): <NEW_LINE> <INDENT> schedule_value_list = ['* * * -30 *', '* * * 13 *', '* * * 2- *', '* * * 6-0 *', '* * * -9 *', '* * * $ *'] <NEW_LINE> for each_schedule_value in schedule_value_list: <NEW_LINE> <INDENT> schedule_policy_cron_style = self.autoscale_be... | Creating a scaling policy of type schedule via cron style with invalid month value in
cron results in a 400. | 625941b638b623060ff0ac0c |
def set_VideoDuration(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'VideoDuration', value) | Set the value of the VideoDuration input for this Choreo. ((optional, string) Filters search results based on the video duration. Valid values are: any, long, medium, and short.) | 625941b6a17c0f6771cbde71 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.