code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def plotReacNet(ax, sunet, matr_shape, forcedZ=0, step=4, xoffset=1, cmap='Greens', aspect=1.0): <NEW_LINE> <INDENT> with open(matr_shape) as f: <NEW_LINE> <INDENT> for i, line in enumerate(f): <NEW_LINE> <INDENT> if len(line) != 22: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_... | plots a reaction network based on
default files at cdx/Network/netname
Args:
ax(mpl.axes): axes to draw on.
sunet(str): filename with species names.
matr_shape(str): filename with reaction tags.
forcedZ(int): offset for reaction values.
step(int): element name skip size.
xoffset(int): element n... | 625941ead164cc6175783228 |
def execute(self): <NEW_LINE> <INDENT> self.character.set_subcommand(self.command_name, self.args) <NEW_LINE> return self | Set a subcommand on a character's command list.
:return: `self`. | 625941eae1aae11d1e74a195 |
def match(self, pattern): <NEW_LINE> <INDENT> return pattern in self.memo or pattern in self.tags | Determine if this note matches the pattern text.
Return True if it matches, False otherwise.
Search is case sensitive and matches both text and
tags. | 625941ea3317a56b8693a125 |
def safe_json(f): <NEW_LINE> <INDENT> return json(safe(f)) | A combination of the safe and json decorators | 625941ea21a7993f00bc81d1 |
def create_connection(db, user, password): <NEW_LINE> <INDENT> db_connection = psycopg2.connect(database=db, user=user, password=password) <NEW_LINE> cursor = db_connection.cursor() <NEW_LINE> cursor.execute("PREPARE review_insert (varchar, timestamp with time zone, char, real, text, varchar, varchar, char) as insert i... | Create a database connection. Just specify None if you are not using a password | 625941eaa8ecb033257d35a4 |
def rank_n_accuracy(y_true, y_prob_mat, n=0.33): <NEW_LINE> <INDENT> n_classes = y_prob_mat.shape[1] <NEW_LINE> if n < 1: <NEW_LINE> <INDENT> n = int(round(n_classes * n)) <NEW_LINE> <DEDENT> rankings = np.argsort(-y_prob_mat) <NEW_LINE> rankings = rankings[:, :n] <NEW_LINE> num_samples = len(y_true) <NEW_LINE> correct... | Compute how often the true label is one of the top n predicted classes
for each training example.
If n is an integer, consider the top n predictions for each example.
If n is a float, it represents a proportion of the top predictions.
This metric is only really useful when the total number of classes is large. | 625941ea45492302aab5e7a1 |
def filter_subsets(word, score, possible_subsets): <NEW_LINE> <INDENT> new_list = [] <NEW_LINE> for items in possible_subsets: <NEW_LINE> <INDENT> if compatible(word, score, items) == True: <NEW_LINE> <INDENT> new_list += [items] <NEW_LINE> <DEDENT> <DEDENT> return new_list | Returns the subsets for which word would get the given score.
>>> word = make_word_from_string('steal')
>>> sub1 = ['a', 'b', 'e', 'l', 's']
>>> sub2 = ['b', 'e', 'l', 't', 'z']
>>> sub3 = ['s', 't', 'e', 'a', 'l']
>>> sub4 = ['b', 'l', 'e', 's', 't']
>>> filter_subsets(word, 4, [sub1, sub2, sub3, sub4])
[['a', 'b', '... | 625941ea38b623060ff0b2c6 |
def enable_service(self, service, host=None, binary=None): <NEW_LINE> <INDENT> if utils.supports_microversion(self, '2.53'): <NEW_LINE> <INDENT> return self.update_service( service, status='enabled') <NEW_LINE> <DEDENT> service = self._get_resource(_service.Service, service) <NEW_LINE> return service.enable(self, host,... | Enable a service
:param service: Either the ID of a service or a
:class:`~openstack.compute.v2.service.Service` instance.
:param str host: The host where service runs.
:param str binary: The name of service.
:returns: Updated service instance
:rtype: class: `~openstack.compute.v2.service.Service` | 625941ea796e427e537b0aa3 |
def _delete_blob(location): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove(app.config['UPLOAD_FOLDER'] + '/' + location) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> abort(404, 'Location could not be found') <NEW_LINE> <DEDENT> return '200' | Handle the deletion logic for a new blob.
:param location: The location we want to delete the blob at.
:return: The return code.
:rtype: int | 625941ea6fb2d068a760f57e |
def PrePredict(self, X, y, MinComb=1, MaxComb=None): <NEW_LINE> <INDENT> y_true = self.Label2Num.fit_transform(y) <NEW_LINE> self.BestCombResults = pd.DataFrame(columns=['Combination', 'Score', 'NumOfModels', 'Param']) <NEW_LINE> CombModelList = [] <NEW_LINE> AllModelsName = list(self.ModelsAfterFit.keys()) <NEW_LINE> ... | In case we want to see how combinations of models work, we will use this method.
It will take a training set and give us the best possible combinations for the best results.
It looks for combinations of predicted proba for each model.
Then it aggregates them into 3 types for EACH combination: Average prediction, maximu... | 625941ea85dfad0860c3b335 |
def sample(array, size, replace = False, prob = None): <NEW_LINE> <INDENT> return np.random.choice(array, size, replace = replace, p = prob) | it is np.random.choice but replace = False by default | 625941eaa8370b7717052d76 |
def __init__(self, head_length=.4, head_width=.2): <NEW_LINE> <INDENT> super(ArrowStyle.CurveFilledAB, self).__init__( beginarrow=True, endarrow=True, fillbegin=True, fillend=True, head_length=head_length, head_width=head_width) | Parameters
----------
head_length : float, optional, default : 0.4
Length of the arrow head
head_width : float, optional, default : 0.2
Width of the arrow head | 625941ea596a897236089f92 |
def unserialize(self, data, request): <NEW_LINE> <INDENT> if "inReplyTo" in data: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> media_id = int(extract_url_arguments( url=data["inReplyTo"]["id"], urlmap=request.app.url_map )["id"]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT... | Takes API objects and unserializes on existing comment | 625941ea956e5f7376d71344 |
def get_posterior_distribution_for_trg_token(trg_index, src_tokens, trg_tokens, prior_model, translation_model): <NEW_LINE> <INDENT> trg_token = trg_tokens[trg_index] <NEW_LINE> src_length, trg_length = len(src_tokens), len(trg_tokens) <NEW_LINE> posterior_probs_unnorm = np.array([ prior_model.get_prior_prob(src_index,... | Compute the posterior distribution over alignments for
trg_index: P(a_j = i|f_j, e). | 625941ea6e29344779a62ae9 |
def getNonInstallableProfiles(self): <NEW_LINE> <INDENT> return [ 'tdf.extensioncentertheme:uninstall', ] | Hide uninstall profile from site-creation and quickinstaller | 625941eaa4f1c619b28b0506 |
def __init__(self, pretrain_model): <NEW_LINE> <INDENT> super(TextBertEmbeddingModel, self).__init__() <NEW_LINE> self.pretrain_model = pretrain_model <NEW_LINE> self.embedder = BertModel.from_pretrained(pretrain_model) <NEW_LINE> self.text_embedding_dim = self.embedder.config.hidden_size | 构造函数
:param pretrain_model: | 625941ea9f2886367277ad62 |
def _element_constructor_(self, arg): <NEW_LINE> <INDENT> if hasattr(arg,"_universal_cyclotomic_field_"): <NEW_LINE> <INDENT> return arg._universal_cyclotomic_field_() <NEW_LINE> <DEDENT> elif isinstance(arg,(sage.interfaces.gap3.GAP3Element,sage.interfaces.gap.GapElement)): <NEW_LINE> <INDENT> return self.from_gap(arg... | The only way to get here is if there was no coercion found.
In this case, we give other parents the option to define a conversion
using the method ``_universal_cyclotomic_field_``, or raise a TypeError otherwise.
TESTS::
sage: UCF = UniversalCyclotomicField()
sage: UCF(CC(5)) # indirect doctest
Tracebac... | 625941ea96565a6dacc8fba3 |
def download(url): <NEW_LINE> <INDENT> data = urllib.request.urlopen(url).read() <NEW_LINE> return data | Download and return data from the given URL.
>>> data = download('https://de.wikipedia.org')
>>> type(data)
<class 'bytes'> | 625941ea091ae3566866742f |
def dump_links(self, all=True): <NEW_LINE> <INDENT> req_msg = lm_types.LinkMonitorRequest() <NEW_LINE> req_msg.cmd = lm_types.LinkMonitorCommand.DUMP_LINKS <NEW_LINE> links = self.send_and_recv_thrift_obj(req_msg, lm_types.DumpLinksReply) <NEW_LINE> if not all: <NEW_LINE> <INDENT> links.interfaceDetails = { k: v for k,... | @param all: If set to false then links with no addresses will be
filtered out. | 625941ea50812a4eaa59c7f5 |
def how_much_die(self, population_size): <NEW_LINE> <INDENT> return int(self.total_2019_death * population_size / self.total_2019_population) | return the number of dead should happen prorated to given
population_size | 625941ea7c178a314d6ef940 |
def testGetPointClass(self): <NEW_LINE> <INDENT> self.Point = Point([],'classA') <NEW_LINE> assert self.Point.get_point_class() == 'classA', "get point class method isn't work propertly" | method for checking method get_point_class(), which should return point class
:param TestKNearestNeighbors self: class instance | 625941ead486a94d0b98e620 |
def get_indexes(cursor, table_name): <NEW_LINE> <INDENT> indexes = {} <NEW_LINE> for info in _table_info(cursor, table_name): <NEW_LINE> <INDENT> indexes[info['name']] = {'primary_key': info['pk'] != 0, 'unique': False} <NEW_LINE> <DEDENT> cursor.execute('PRAGMA index_list(%s)' % quote_name(table_name)) <NEW_LINE> for ... | Returns a dictionary of fieldname -> infodict for the given table,
where each infodict is in the format:
{'primary_key': boolean representing whether it's the primary key,
'unique': boolean representing whether it's a unique index} | 625941eaec188e330fd5ac6e |
def assert_same(nest1, nest2): <NEW_LINE> <INDENT> tf.nest.assert_same_structure(nest1, nest2) <NEW_LINE> for t1, t2 in zip(tf.nest.flatten(nest1), tf.nest.flatten(nest2)): <NEW_LINE> <INDENT> assert t1.dtype == t2.dtype <NEW_LINE> if isinstance(t1, tf.Tensor) and isinstance(t2, tf.Tensor): <NEW_LINE> <INDENT> assert t... | Assert that both structures are equivalent.
This function is more strict than tf.nest.assert_same_structure since it also
requires that Tensors have the same dtype and shape.
Args:
nest1: A nested structure.
nest2: A nested structure. | 625941ea2c8b7c6e89b35c96 |
def __extract_cvis_fft(self, image, m2pix): <NEW_LINE> <INDENT> DZ = image.shape[0]//2 <NEW_LINE> uv_samp = self.kpi.UVC * m2pix + DZ <NEW_LINE> ac = shift(fft(shift(image))) <NEW_LINE> ac /= (np.abs(ac)).max() / self.kpi.nbap <NEW_LINE> xx = np.cast['int'](np.round(uv_samp[:, 1])) <NEW_LINE> yy = np.cast['int'](np.rou... | -------------------------------------------------------------------
extracts complex visibility from a square image (using old school FFT)
Assumes that you know what you do and have provided sufficient
zero-padding to avoid Fourier aliasing for the spatial frequencies the
model tries to get access to.
The alternative... | 625941eabe7bc26dc91cdad0 |
def _create_empty(self): <NEW_LINE> <INDENT> dbpath = self.dbpath <NEW_LINE> assert not os.path.exists(dbpath), "redefining dbpath" <NEW_LINE> pr.progress("Creating new database %s ..." % (dbpath,)) <NEW_LINE> temp_cx = None <NEW_LINE> try: <NEW_LINE> <INDENT> temp_cx = sqlite3.connect(dbpath) <NEW_LINE> SQL... | Create a new SQL database file and close it. | 625941ea0a366e3fb873ecf8 |
def update(self, uInt): <NEW_LINE> <INDENT> self._value = long(uInt) <NEW_LINE> for key, bit in self._bitFields.iteritems(): <NEW_LINE> <INDENT> setattr(self, key, self._value & 2**bit > 0) | Update attributes with new values. | 625941eaa79ad161976cc61f |
def interpreter(self, personnage, dic_masques): <NEW_LINE> <INDENT> titre = dic_masques["message"].message <NEW_LINE> rapport = importeur.rapport.creer_rapport(titre, personnage, ajouter=False) <NEW_LINE> rapport.type = "évolution" <NEW_LINE> editeur = importeur.interpreteur.construire_editeur( "bugedit", personnage, r... | Méthode d'interprétation de commande | 625941ea82261d6c526ab980 |
def incoming(ui, repo, other): <NEW_LINE> <INDENT> ui.status(_("searching for changed bookmarks\n")) <NEW_LINE> r = compare(repo, other.listkeys('bookmarks'), repo._bookmarks, dsthex=hex) <NEW_LINE> addsrc, adddst, advsrc, advdst, diverge, differ, invalid, same = r <NEW_LINE> incomings = [] <NEW_LINE> if ui.debugflag: ... | Show bookmarks incoming from other to repo
| 625941eacb5e8a47e48b7f7c |
def parse_structure(self, struct_list_dict): <NEW_LINE> <INDENT> for rep_num, item in enumerate(struct_list_dict): <NEW_LINE> <INDENT> sgmnt = segment.Segment() <NEW_LINE> sgmnt.fill_segment(item) <NEW_LINE> if not sgmnt.is_empty(): <NEW_LINE> <INDENT> sgmnt.repetition = rep_num <NEW_LINE> sgmnt.is_trail_running = self... | Parses structure with data in the list of dictionaries
Parses structure with data in the list of dictionaries.
Data from the single run is passed into the segment, such as trail,
feeling or date. | 625941ea435de62698dfe126 |
def artifact_list(sig): <NEW_LINE> <INDENT> artifactsList = [] <NEW_LINE> users = User.objects.get(signum = sig) <NEW_LINE> for artifact in Artifact.objects.filter(user_id=users): <NEW_LINE> <INDENT> artifactsList.append(artifact) <NEW_LINE> <DEDENT> return artifactsList | List of all artifact IDs for a user | 625941ea0383005118ecfaba |
def test_comma2(self): <NEW_LINE> <INDENT> self.assertEqual( ['N,N-Dimethylformamide', '(', 'DMF', ')', 'was', 'used', 'as', 'solvent', '.'], self.t.tokenize('N,N-Dimethylformamide (DMF) was used as solvent.') ) | Test the word tokenizer on sentence containing chemical name with commas. | 625941ea23e79379d52eea37 |
def change_lane_policy(self): <NEW_LINE> <INDENT> if self.lane_index != self.target_lane_index: <NEW_LINE> <INDENT> for v in self.road.vehicles: <NEW_LINE> <INDENT> if v is not self and v.lane_index != self.target_lane_index and isinstance(v, ControlledVehicle) ... | Decide when to change lane.
Based on:
- frequency;
- closeness of the target lane;
- MOBIL model. | 625941ea090684286d50f1c6 |
def write_temp(self, temp_dir=None): <NEW_LINE> <INDENT> if not hasattr(self, '_temp_filepath') or not self._temp_filepath: <NEW_LINE> <INDENT> if temp_dir: <NEW_LINE> <INDENT> safe_create_dir(temp_dir) <NEW_LINE> <DEDENT> fd, self._temp_filepath = tempfile.mkstemp( suffix=MIMETYPES.guess_extension(self.content_type())... | Write this data's bytes to a temporary file on disk, returning the path
to the written file, whose extension is guessed based on this data's
content type.
NOTE:
The file path returned should not be explicitly removed by the user.
Instead, the ``clean_temp()`` method should be called on this
object.
:param... | 625941ea3eb6a72ae02ec9c4 |
def GetYouTubeVideoCommentEntry(self, uri): <NEW_LINE> <INDENT> return self.Get( uri, converter = gdata.youtube.YouTubeVideoCommentEntryFromString) | Retrieve a YouTubeVideoCommentEntry.
Args:
uri: A string representing the URI of the comment entry that is to
be retrieved.
Returns:
A YouTubeCommentEntry if successfully retrieved. | 625941ead58c6744b4258137 |
def test_no_recent_documents(self): <NEW_LINE> <INDENT> self.assertEqual([], RecentDocuments().read_paths()) <NEW_LINE> w = self.window <NEW_LINE> w._sync_recent_documents_actions() <NEW_LINE> self.assertFalse(w.recent_doc_actions[0].isEnabled()) <NEW_LINE> self.assertTrue(w.recent_doc_actions[0].isVisible()) <NEW_LINE... | No recent documents | 625941ea45492302aab5e7a2 |
def registerPlayer(name): <NEW_LINE> <INDENT> DB = connect() <NEW_LINE> cursor = DB.cursor() <NEW_LINE> cursor.execute('insert into players (name) values (%s)', (name , ) ) <NEW_LINE> DB.commit() <NEW_LINE> DB.close() | Adds a player to the tournament database.
The database assigns a unique serial id number for the player. (This
should be handled by your SQL database schema, not in your Python code.)
Args:
name: the player's full name (need not be unique). | 625941eade87d2750b860271 |
def note_Note__hash__(self): <NEW_LINE> <INDENT> return hash(self.fullName) | Fix hashing of note.Note() objects so sets work. | 625941eaeab8aa0e5d26e033 |
def make_upload_path(instance, filename): <NEW_LINE> <INDENT> return generate_filename(instance.UPLOAD_DIR, filename) | Generates upload path for FileField | 625941ea97e22403b379d475 |
def install() -> None: <NEW_LINE> <INDENT> venv.create() <NEW_LINE> venv.activate() <NEW_LINE> sys_calls.run(["pip", "install", "--upgrade", 'pip', 'setuptools']) <NEW_LINE> sys_calls.run(["pip", "install", "-r", "requirements.txt"]) | Downloads & installs all dependencies for the backend. | 625941eabe8e80087fb21115 |
def test_read_device_data(self): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> hibike_message.send(self.dummy_device, hibike_message.make_subscription_request(self.dummy_dev_id, self.dummy_params, 40)) <NEW_LINE> for packet in hibike_message.blocking_read_generator(self.dummy_device): <NEW_LINE> <INDENT> if p... | Check that DeviceData packets are received and decoded. | 625941ead99f1b3c44c67a5f |
def encode(self, value, encoding=None): <NEW_LINE> <INDENT> raise NotImplementedError | Return str object containing encoded field value.
This is an abstract method and it must be overriden in child classes. | 625941eaa4f1c619b28b0507 |
def grayCode2(self, n): <NEW_LINE> <INDENT> results = [0] <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> results += [x + pow(2, i) for x in reversed(results)] <NEW_LINE> <DEDENT> return results | :type n: int
:rtype: List[int] | 625941ea5e10d32532c5f3ff |
def squares_2(L): <NEW_LINE> <INDENT> type_name = type(L) <NEW_LINE> return type_name([item ** 2 for item in L]) | Решение с использованием генератора списков. | 625941eab7558d58953c53e3 |
def text2conll2002(text,pos=True): <NEW_LINE> <INDENT> text=toolner_to_tag(text) <NEW_LINE> text=text.replace("''",'"') <NEW_LINE> text=text.replace("’",'"').replace("‘",'"') <NEW_LINE> tag=tokenizer.tokenize(text) <NEW_LINE> j=0 <NEW_LINE> conll2002="" <NEW_LINE> for tagopen,text,tagclose in tag: <NEW_LINE> <INDENT> w... | ใช้แปลงข้อความให้กลายเป็น conll2002 | 625941ea3d592f4c4ed1d53a |
def p_Definition(p): <NEW_LINE> <INDENT> p[0] = p[1] | Definition : CallbackOrInterface
| PartialInterface
| Dictionary
| Exception
| Enum
| Typedef
| ImplementsStatement | 625941ea6aa9bd52df037281 |
def proc_txt_lv73_word_1_9_17(lines,lv): <NEW_LINE> <INDENT> w_ret=list() <NEW_LINE> wcount=0 <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> line_info=line_to_number_body_pair(line) <NEW_LINE> if is_memory_line(line_info): <NEW_LINE> <INDENT> if FLAG_ANSWER: <NEW_LINE> <INDENT> w_ret.append(line.strip()) <NEW_LINE> ... | lv73 1,9,17 8n+1 の単語だけを残して単語をマスクする | 625941ea76d4e153a657f00c |
def getValue(self)->list: <NEW_LINE> <INDENT> return self.conf | Returns array of queens position
Returns:
list: config array | 625941ea92d797404e304666 |
def replace_wrep(t:str) -> str: <NEW_LINE> <INDENT> def _replace_wrep(m:Collection[str]) -> str: <NEW_LINE> <INDENT> c,cc = m.groups() <NEW_LINE> return f' {TK_WREP} {len(cc.split())+1} {c} ' <NEW_LINE> <DEDENT> re_wrep = re.compile(r'(\b\w+\W+)(\1{3,})') <NEW_LINE> return re_wrep.sub(_replace_wrep, t) | Replace word repetitions in `t`. | 625941eaf9cc0f698b140ad1 |
def add_blanks(text, stop_words_file): <NEW_LINE> <INDENT> with open(stop_words_file) as f: <NEW_LINE> <INDENT> stop_words = f.readlines() <NEW_LINE> stop_words = [x.strip() for x in stop_words] <NEW_LINE> <DEDENT> for stop_w in stop_words: <NEW_LINE> <INDENT> to_replace = "\n" + stop_w + "\n" <NEW_LINE> to_replace = t... | adds spaces and new lines to text from txt file
:param text:
:return: text with spaces and new lines | 625941eaa934411ee3751b6f |
def DivideCV(self): <NEW_LINE> <INDENT> unicodeVowels = u"[ae\N{LATIN SMALL LETTER E WITH GRAVE}iouy]+" <NEW_LINE> uniConsonants = u"[^ae\N{LATIN SMALL LETTER E WITH GRAVE}iouy]+" <NEW_LINE> firstvowel = re.search(unicodeVowels, self.wd).start() <NEW_LINE> for v in re.finditer(unicodeVowels, self.wd): <NEW_LINE> <INDEN... | Divide the word among C and V groups to fill the sylBounds list.
Here, and here alone, we need to catch e-with-grave-accent to count it
as not only a vowel but syllabic ('an aged man' vs. 'aged beef'). Other
special characters might be useful to recognize, but won't make the
same syllabic difference. | 625941ea9c8ee82313fbbc51 |
def between_markers(text: str, begin: str, end: str) -> str: <NEW_LINE> <INDENT> word = text[text.find(begin)+1:text.find(end)] <NEW_LINE> return word | returns substring between two given markers | 625941ea3cc13d1c6d3c7852 |
def _handle_content_frame(self, frame_value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self._content_assembler.process(frame_value) <NEW_LINE> <DEDENT> except exceptions.UnexpectedFrameError: <NEW_LINE> <INDENT> self._on_unexpected_frame(frame_value) <NEW_LINE> return <NEW_LINE> <DEDENT> if response: <NE... | This is invoked by the connection when frames that are not registered
with the CallbackManager have been found. This should only be the case
when the frames are related to content delivery.
The _content_assembler will be invoked which will return the fully
formed message in three parts when all of the body frames have... | 625941ea3539df3088e2e825 |
def addTwoNumbers(self, l1, l2): <NEW_LINE> <INDENT> s = self.link2list(l1, l2) <NEW_LINE> s = list(str(s)) <NEW_LINE> head = ListNode(s[0]) <NEW_LINE> node = head <NEW_LINE> for j in range(1, len(s)): <NEW_LINE> <INDENT> node.next = ListNode(s[j]) <NEW_LINE> node = node.next <NEW_LINE> <DEDENT> return head | :type l1: ListNode
:type l2: ListNode
:rtype: ListNode | 625941ead53ae8145f87a740 |
def areStrictlyCompatibleForDiv(self, *args): <NEW_LINE> <INDENT> return _ParaMEDMEM.MEDCouplingTimeDiscretization_areStrictlyCompatibleForDiv(self, *args) | areStrictlyCompatibleForDiv(self, MEDCouplingTimeDiscretization other) -> bool
1 | 625941ea046cf37aa974d21c |
def add_nodes(graph, ids): <NEW_LINE> <INDENT> for v in ids: <NEW_LINE> <INDENT> graph.add_vertex(str(v)) <NEW_LINE> <DEDENT> graph.vs['size'] = 30 <NEW_LINE> graph.vs['color'] = '#2b8cbe' <NEW_LINE> return graph | graph: igraph object
ids: list of node (vertex) IDs
returns: igraph object with nodes added in | 625941ead18da76e235329b6 |
def dailyTemperatures(self, T): <NEW_LINE> <INDENT> res = [0 for i in range(len(T))] <NEW_LINE> stack = [] <NEW_LINE> for j in range(len(T)): <NEW_LINE> <INDENT> while stack and T[j] > T[stack[-1]]: <NEW_LINE> <INDENT> i = stack.pop() <NEW_LINE> res[i] = j - i <NEW_LINE> <DEDENT> stack.append(j) <NEW_LINE> <DEDENT> ret... | :type T: List[int]
:rtype: List[int] | 625941ea1b99ca400220af8d |
def idade (numero): <NEW_LINE> <INDENT> return 'Adulto' | >>> idade(3)
'Crianca'
>>> idade(67)
'Idoso'
>>> idade(18)
'Adolescente'
>>> idade(28)
'Adulto' | 625941ea0a50d4780f667370 |
def get_collected_num(self, category, has_sub_key=False): <NEW_LINE> <INDENT> num = 0 <NEW_LINE> collection = self.collection <NEW_LINE> if collection.has_key(category): <NEW_LINE> <INDENT> if has_sub_key: <NEW_LINE> <INDENT> for k, v in collection[category].items(): <NEW_LINE> <INDENT> num += len(v) <NEW_LINE> <DEDENT... | 根据收集的物品的分类获取用户收集到的物品列表的数量
Args:
category:图鑑类型(如:卡片,怪物等)
return:
int | 625941ea01c39578d7e75315 |
def with_mulithread(): <NEW_LINE> <INDENT> processes = [] <NEW_LINE> for i in range(1000): <NEW_LINE> <INDENT> p1 = multiprocessing.Process(target=do_something, args=[1.5]) <NEW_LINE> p2 = multiprocessing.Process(target=do_something, args=[2.0]) <NEW_LINE> p1.start() <NEW_LINE> p2.start() <NEW_LINE> processes.append(p1... | with concurrent.futures.ProcessPoolExecutor() as executor:
secs = [1 for x in range(100)]
results = executor.map(do_something, secs)
print(results) | 625941ea1b99ca400220af8e |
def sync_run(host, dry_run=False): <NEW_LINE> <INDENT> with NERSCConnection(host) as nersc: <NEW_LINE> <INDENT> remote_dir = nersc.run("python -c 'from lsskit import rsdfit; print(rsdfit.RSDFIT)'") <NEW_LINE> <DEDENT> cmd = RSYNC <NEW_LINE> if dry_run: cmd += ' --dry-run' <NEW_LINE> cmd += " --exclude='.*' --exclude='o... | Sync the RSDFit ``run`` directory to NERSC
Parameters
----------
host : {'cori', 'edison'}
the name of the remote host
dry_run : bool, optional
whether to do a dry-run | 625941ea07d97122c4178d71 |
def toRunItem(stuff: str): <NEW_LINE> <INDENT> stuff = stuff.strip() <NEW_LINE> if stuff.lower() == "rest" or stuff == "-": <NEW_LINE> <INDENT> return REST <NEW_LINE> <DEDENT> stuff = stuff.replace("mi run", "miles") <NEW_LINE> stuff = stuff.replace("mi pace", "miles pace") <NEW_LINE> stuff = stuff.replace("-K Race", "... | Convert some of the random text to standard text | 625941ea7047854f462a18de |
def __call__(self, x): <NEW_LINE> <INDENT> from itertools import ifilter <NEW_LINE> try: <NEW_LINE> <INDENT> return next(ifilter(lambda x: x is not None, (f(x) for f in self.method_list))) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return self.default(x) | Call the methods in method_list until one of them returns something other than None
and return that as the result of the call. | 625941ea656771135c3ebd4f |
def predict_on_models(final_trait_dir, candidate_df): <NEW_LINE> <INDENT> predicted_value = 0 <NEW_LINE> for file in os.listdir(final_trait_dir): <NEW_LINE> <INDENT> if 'model' in file: <NEW_LINE> <INDENT> model = joblib.load(os.path.join(final_trait_dir, file)) <NEW_LINE> predicted_value += model.predict(candidate_df)... | :param final_trait_dir: the dit of the trait final results
:param candidate_df: the data frame scaled data of the candidate
:return: the avg predicted value | 625941ea2c8b7c6e89b35c97 |
def register_generator(generator_desc_or_language, target=None, description='', generator=None): <NEW_LINE> <INDENT> global generators <NEW_LINE> if generators is None: <NEW_LINE> <INDENT> generator_descriptions() <NEW_LINE> <DEDENT> if not isinstance(generator_desc_or_language, GeneratorDesc): <NEW_LINE> <INDENT> gene... | Programmatically register a generator.
Args:
generator_desc_or_language (GeneratorDesc or str): If GeneratorDesc is
given other parameters are not used.
For other parameters see `GeneratorDesc`. | 625941eae64d504609d74d1a |
def __init__( self, driver: str = None, fs_type: str = None, options: dict = None, read_only: bool = None, secret_ref: "SecretReference" = None, ): <NEW_LINE> <INDENT> super(FlexPersistentVolumeSource, self).__init__( api_version="core/v1", kind="FlexPersistentVolumeSource" ) <NEW_LINE> self._properties = { "driver": d... | Create FlexPersistentVolumeSource instance. | 625941ea38b623060ff0b2c7 |
def dropout_backward(dout, cache): <NEW_LINE> <INDENT> dropout_param, mask = cache <NEW_LINE> mode = dropout_param['mode'] <NEW_LINE> dx = None <NEW_LINE> if mode == 'train': <NEW_LINE> <INDENT> dx = dout* cache[1] <NEW_LINE> <DEDENT> elif mode == 'test': <NEW_LINE> <INDENT> dx = dout <NEW_LINE> <DEDENT> return dx | Perform the backward pass for (inverted) dropout.
Inputs:
- dout: Upstream derivatives, of any shape
- cache: (dropout_param, mask) from dropout_forward. | 625941ead99f1b3c44c67a60 |
def draw_roi(self, box, theta): <NEW_LINE> <INDENT> b_l = box[0] <NEW_LINE> t_l = box[1] <NEW_LINE> t_r = box[2] <NEW_LINE> b_r = box[3] <NEW_LINE> all_y = [box[0][1], box[1][1], box[2][1], box[3][1]] <NEW_LINE> all_x = [box[0][0], box[1][0], box[2][0], box[3][0]] <NEW_LINE> index_1, _max = min(enumerate(all_y), key=op... | Draws a region of interest (ROI) above the pillar if no 'gap' is detected.
Essentially detects the top edge of the pillar.
Parameters
----------
box:
The external contour box coordinates
theta:
The angle of rotation of the box through the y-axis.
Returns
-------
[t_l_, t_r_, p_l, p_r, t_l,... | 625941ea435de62698dfe127 |
def _etag_tail(head, tail, etag): <NEW_LINE> <INDENT> for chunk in head: <NEW_LINE> <INDENT> yield encodeUnicodeToBytes(chunk) <NEW_LINE> <DEDENT> for chunk in tail: <NEW_LINE> <INDENT> yield encodeUnicodeToBytes(chunk) <NEW_LINE> <DEDENT> etagval = (etag and etag.value()) <NEW_LINE> if etagval: <NEW_LINE> <INDENT> che... | Generator which first returns anything in `head`, then `tail`.
Sets ETag header at the end to value of `etag` if it's defined and
yields a value. | 625941ea29b78933be1e5b80 |
def __init__(self, db, storage): <NEW_LINE> <INDENT> self._db = db <NEW_LINE> self._storage = storage <NEW_LINE> _root = utils.read_one( self._db, _t.Groups, _t.Groups.c.id == _t.Groups.c.parent_id) <NEW_LINE> if _root is None: <NEW_LINE> <INDENT> self._create_root() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._... | :type storage: tensorlab.local_storage.api.facade.LocalStorage | 625941ea8e7ae83300e4b4a9 |
def forward(self, inp): <NEW_LINE> <INDENT> return nn.ReLU()(self.lin(inp)) | transforms env observation to hidden | 625941ea627d3e7fe0d6932c |
def write_warning(self, warning_dict): <NEW_LINE> <INDENT> _info = 'epoch: %d, lr: %f, loss: %f'%(warning_dict['epoch'],warning_dict['lr'], warning_dict['loss']) <NEW_LINE> self.log_writer.warning(_info) <NEW_LINE> sys.stdout.flush() | warninginfo writing
:return: | 625941eab57a9660fec33d65 |
@celery.task() <NEW_LINE> def query_subscription_plans(subscription_id, billing_cycle_id): <NEW_LINE> <INDENT> from src.models.plans_versioning import SubscriptionsPlanVersion <NEW_LINE> current_plan = SubscriptionsPlanVersion.get_current_plan(subscription_id=subscription_id) <NEW_LINE> return [(current_plan.plan.mb_av... | Add google style doc string here
(https://www.sphinx-doc.org/en/1.7/ext/example_google.html) | 625941ea63d6d428bbe449cb |
def is_factor(possible_factor, number): <NEW_LINE> <INDENT> return number % possible_factor == 0 | Is possible_factor a factor number? | 625941ea283ffb24f3c55dd7 |
def createPartialChainObject(self, startRes, endRes, addFlankingAtoms = False): <NEW_LINE> <INDENT> startIndex = self.resIndex(startRes) <NEW_LINE> endIndex = self.resIndex(endRes) <NEW_LINE> return self.createPartialChainObjectFromIndex(startIndex, endIndex, addFlankingAtoms) | Create a chain object containing coordinates for some nucleotides
ARGUMENTS:
startRes - the starting residue
endRes - the ending residue
OPTIONAL ARGUMENTS:
addFlankingAtoms - if True, add the 5' and 3' atoms that will move during minimization
Note that these atoms are only added i... | 625941ea71ff763f4b549b6f |
def post_process_urls(self, urlpatterns): <NEW_LINE> <INDENT> for pattern in urlpatterns: <NEW_LINE> <INDENT> if not hasattr(pattern, '_callback'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> decorator = self.get_url_decorator(pattern) <NEW_LINE> if decorator: <NEW_LINE> <INDENT> pattern._callback = decorator(patt... | Customise URL patterns.
By default, this only allows custom decorators to be specified, but you
could override this method to do anything you want. | 625941ea07f4c71912b1195f |
def replace(value, id): <NEW_LINE> <INDENT> return value.replace(id,"") | custom django filter, wraps around str.replace
removes id from a string | 625941eabd1bec0571d90b09 |
def fixids(self): <NEW_LINE> <INDENT> badchars = "[^a-zA-Z0-9\._-]" <NEW_LINE> for id in self.results['test_results']: <NEW_LINE> <INDENT> if id.has_key('test_case_id'): <NEW_LINE> <INDENT> id['test_case_id'] = id['test_case_id'].replace(" ", "_") <NEW_LINE> id['test_case_id'] = re.sub(badchars, "", id['test_case_id']) | Convert spaces to _ in test_case_id and remove illegal characters | 625941ea4527f215b584c92c |
def loadImage(self, filename): <NEW_LINE> <INDENT> image = fabio.open(filename) <NEW_LINE> return image | Use the fabio API instead of using the image format | 625941ea30dc7b7665901e3b |
def getPositionAndDerivative(self, t): <NEW_LINE> <INDENT> res = self.trajfunction(t) <NEW_LINE> if isinstance(res[0], float): <NEW_LINE> <INDENT> if 'trajprec' in self.__dict__ and 'dt' in self.__dict__: <NEW_LINE> <INDENT> deriv = (res - self.trajprec) / ((t - self.tprec) * self.dt) <NEW_LINE> <DEDENT> else: <NEW_LIN... | Call the traj function, and if needed compute the numerical derivative. | 625941ea4c3428357757c7ff |
def user(self, username): <NEW_LINE> <INDENT> if not self.user_exists(username.lower()): <NEW_LINE> <INDENT> raise AuthKitNoSuchUserError("No such user %r"%username.lower()) <NEW_LINE> <DEDENT> user = self.meta.Session.query(self.model.User).filter_by( username=username.lower()).first() <NEW_LINE> roles = [r.name for r... | Returns a dictionary in the following format:
.. code-block :: Python
{
'username': username,
'group': group,
'password': password,
'roles': [role1,role2,role3... etc]
}
The role names are ordered alphabetically
Raises an exception if the user doesn't exist. | 625941ea57b8e32f52483979 |
def gen_random(n): <NEW_LINE> <INDENT> ret = '' <NEW_LINE> data = os.urandom(n) <NEW_LINE> for i in data: <NEW_LINE> <INDENT> ret += '%02X' % i <NEW_LINE> <DEDENT> return ret | 产生n字节的随机数,然后输出为16进制字符串
:param n: int
:return : str | 625941ea5fdd1c0f98dc0710 |
def test_no_detect_tags(self): <NEW_LINE> <INDENT> content = 'mmmm an@email.com xxxx@ @--- no@tag' <NEW_LINE> matches = re.findall(TAG_REGEX, content) <NEW_LINE> self.assertEqual([], matches) | Check that things that aren't tags aren't being detected. | 625941ead164cc617578322a |
def fuzzy_search(query, elements, key=lambda x: x, rank=True, seq=3): <NEW_LINE> <INDENT> R = match_rank(query, [key(el) for el in elements], seq=seq) <NEW_LINE> out = [(el, R[i]) for i, el in enumerate(elements) if R[i] is not None] <NEW_LINE> return [el[0] for el in sorted(out, key=lambda el: el[1])] | Fuzzy search for query in list of strings, dictionaries, tulpes, or lists
Args:
query: search string
elements: list of strings, dictionaries, tulpes, or lists
key: function to access string element in dictionaries, tulpes, or lists
rank: rank the elements in the return list by quality of match (current... | 625941ea1f037a2d8b9466d7 |
def _process_body_line(self, line): <NEW_LINE> <INDENT> if '=' in line: <NEW_LINE> <INDENT> words = [x.strip() for x in line.split('=')] <NEW_LINE> if words[1].startswith('declare'): <NEW_LINE> <INDENT> name = words[0] <NEW_LINE> declare = words[1] <NEW_LINE> defn = self._handle_declare_statement(name, declare) <NEW_LI... | Returns the name defined and the processed line itself.
This hack primarily lets us declare variables from Python and inject
them into Cython code. | 625941eacdde0d52a9e53512 |
def get_lenenc_str(self): <NEW_LINE> <INDENT> value = '' <NEW_LINE> size = self.get_lenenc_int() <NEW_LINE> for i in xrange(self.offset, self.offset + size): <NEW_LINE> <INDENT> value += chr(self.packet[i]) <NEW_LINE> self.offset += 1 <NEW_LINE> <DEDENT> return value | Extract a length encoded string from the current packet position
>>> target = "The brown dog did stuff"
>>> pckt = Proto.build_lenenc_str(target)
>>> packet = Proto(pckt)
>>> packet.get_lenenc_str()
'The brown dog did stuff' | 625941ead10714528d6001c3 |
def items(self): <NEW_LINE> <INDENT> for item in self.table: <NEW_LINE> <INDENT> if item: <NEW_LINE> <INDENT> yield item.key, item.value | Returns a generator object that contains
all of the items in the table
:return: type generator | 625941ea45492302aab5e7a3 |
def pm_uhmm_array(self): <NEW_LINE> <INDENT> uhmms = np.zeros((self.nInitial, self.nNodes, self.nSymbols)) <NEW_LINE> for i, initial_node in enumerate(self.valid_initial_nodes): <NEW_LINE> <INDENT> uhmms[i] = self.pm_uhmm(initial_node) <NEW_LINE> <DEDENT> return uhmms | Returns an array of the posterior mean uHMMs. | 625941ea4c3428357757c800 |
def delete(self, _target, **kwargs): <NEW_LINE> <INDENT> return self.delete('GET', _target, kwargs) | 'DELETE' :py:func:`Client.call` wrapper. | 625941eaad47b63b2c50a45a |
def msvc9_query_vcvarsall(ver, arch='x86', *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> orig = get_unpatched(msvc9_query_vcvarsall) <NEW_LINE> return orig(ver, arch, *args, **kwargs) <NEW_LINE> <DEDENT> except distutils.errors.DistutilsPlatformError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except... | Patched "distutils.msvc9compiler.query_vcvarsall" for support extra
compilers.
Set environment without use of "vcvarsall.bat".
Known supported compilers
-------------------------
Microsoft Visual C++ 9.0:
Microsoft Visual C++ Compiler for Python 2.7 (x86, amd64)
Microsoft Windows SDK 6.1 (x86, x64, ia64)
... | 625941ea85dfad0860c3b337 |
def waitDI(self, io_var, io_value, timeout_ms=-1): <NEW_LINE> <INDENT> if type(io_var) != str: <NEW_LINE> <INDENT> io_var = '$DI[%s]' % str(io_var) <NEW_LINE> <DEDENT> if type(io_value) != str: <NEW_LINE> <INDENT> if io_value > 0: <NEW_LINE> <INDENT> io_value = 'TRUE' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> io_va... | Waits for an input io_var to attain a given value io_value. Optionally, a timeout can be provided. | 625941eaf548e778e58cda5b |
def draw(self): <NEW_LINE> <INDENT> self.drawRect() <NEW_LINE> self.drawText() | Draw all CommandBox elements. | 625941ea30bbd722463cc2a4 |
def testInitialize(self): <NEW_LINE> <INDENT> enumeration_value = data_types.EnumerationValue('enum_value', 5) <NEW_LINE> self.assertIsNotNone(enumeration_value) | Tests the __init__ function. | 625941eaa219f33f34628e3d |
def getMemberships(self, principalUID): <NEW_LINE> <INDENT> def gotCachedMemberships(memberships): <NEW_LINE> <INDENT> if memberships is not None: <NEW_LINE> <INDENT> return memberships <NEW_LINE> <DEDENT> def gotMembershipsFromDB(dbmemberships): <NEW_LINE> <INDENT> memberships = set([row[0].encode("utf-8") for row in ... | Return the list of group principal UIDs the specified principal is a member of.
@return: a deferred returning a C{set} of memberships. | 625941eabd1bec0571d90b0a |
def get_recomended_features(self): <NEW_LINE> <INDENT> shape=self.X_train.shape <NEW_LINE> reomended_number_features=int(shape[0]/10) <NEW_LINE> return reomended_number_features | Use empirical rule of 10 times number
rows per feature to asses the curse of
dimensionality.
Returns:
reomended_number_features(int): minimum number of features | 625941ea5fc7496912cc3e58 |
def _compute_faulting_mechanism(C, rake, dip): <NEW_LINE> <INDENT> frv = float((dip > 45) and (22.5 <= rake <= 157.5)) <NEW_LINE> fth = float((dip <= 45) and (22.5 <= rake <= 157.5)) <NEW_LINE> return C['c10'] * frv + C['c11'] * fth | Compute faulting mechanism term (see eq. 5, page 319).
Reverse faulting is defined as occurring on steep faults (dip > 45)
and rake in (22.5, 157.5).
Thrust faulting is defined as occurring on shallow dipping faults
(dip <=45) and rake in (22.5, 157.5) | 625941ea4a966d76dd5514ef |
def isAccountResourceCountEqualToExpectedCount(apiclient, domainid, account, expectedcount, resourcetype): <NEW_LINE> <INDENT> isResourceCountEqual = False <NEW_LINE> isExceptionOccured = False <NEW_LINE> reasonForException = None <NEW_LINE> try: <NEW_LINE> <INDENT> response = Resources.updateCount(apiclient, domainid=... | Get the resource count of specific account and match
it with the expected count
Return list [isExceptionOccured, reasonForException, isResourceCountEqual] | 625941ea8a43f66fc4b5453b |
def test_add_writer_should_disable_qsocket_notifier_on_callback(loop, sock_pair): <NEW_LINE> <INDENT> def can_write(): <NEW_LINE> <INDENT> nonlocal num_calls <NEW_LINE> num_calls += 1 <NEW_LINE> if num_calls == 2: <NEW_LINE> <INDENT> assert not notifier.isEnabled() <NEW_LINE> fut.set_result(None) <NEW_LINE> client_sock... | Verify that add_writer disables QSocketNotifier during callback. | 625941eacad5886f8bd274b4 |
def change_aliases(self, change_map): <NEW_LINE> <INDENT> assert set(change_map.keys()).intersection(set(change_map.values())) == set() <NEW_LINE> def relabel_column(col): <NEW_LINE> <INDENT> if isinstance(col, (list, tuple)): <NEW_LINE> <INDENT> old_alias = col[0] <NEW_LINE> return (change_map.get(old_alias, old_alias... | Changes the aliases in change_map (which maps old-alias -> new-alias),
relabelling any references to them in select columns and the where
clause. | 625941eab830903b967e9de1 |
def sum_bags(rules, col, num=1): <NEW_LINE> <INDENT> val = rules.get(col, []) <NEW_LINE> s = 0 <NEW_LINE> for color, number in val: <NEW_LINE> <INDENT> print(color, number) <NEW_LINE> s += number * sum_bags(rules, color, number*num) <NEW_LINE> <DEDENT> print(col, s) <NEW_LINE> return s + 1 | returns the number of bags contained | 625941eaab23a570cc250662 |
def getFeatureShaps(self, vector): <NEW_LINE> <INDENT> if isinstance(vector, DenseVector): <NEW_LINE> <INDENT> dense_values = [float(v) for v in vector] <NEW_LINE> return list(self._java_obj.getDenseFeatureShaps(dense_values)) <NEW_LINE> <DEDENT> elif isinstance(vector, SparseVector): <NEW_LINE> <INDENT> sparse_indices... | Get the local shap feature importances. | 625941eacb5e8a47e48b7f7e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.