code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_selected_spectra(self): <NEW_LINE> <INDENT> treemodelsort, pathlist = self._selection.get_selected_rows() <NEW_LINE> iters = [treemodelsort.get_iter(path) for path in pathlist] <NEW_LINE> spectrumIDs = [int(treemodelsort.get(iter_, 0)[0]) for iter_ in iters] <NEW_LINE> return spectrumIDs | Returns list of currently selected Spectrum IDs. | 625941e70a50d4780f6672ef |
def parse_relation(string): <NEW_LINE> <INDENT> word = Word(alphanums) <NEW_LINE> csv = OneOrMore(Word(alphanums) + Suppress(ZeroOrMore(','))) <NEW_LINE> csv.setParseAction(set) <NEW_LINE> relation = word('name') + Suppress('(') + csv('attributes') + Suppress(')') <NEW_LINE> result = relation.parseString(string) <NEW_L... | Parse relation
>>> s = 'Courses(courseCode, courseName, credits, teacherID, teacherName)'
>>> parse_relation(s)
Relation(name='Courses', attributes={'courseCode', 'courseName', 'credits',
'teacherName', 'teacherID'}) | 625941e7ec188e330fd5abef |
def _help_float_testing(self, np_dt, dataset_name='vlen'): <NEW_LINE> <INDENT> dt = h5py.special_dtype(vlen=np_dt) <NEW_LINE> ds = self.f.create_dataset(dataset_name, (5,), dtype=dt) <NEW_LINE> array_0 = np.array([1., 2., 30.], dtype=np_dt) <NEW_LINE> array_1 = np.array([100.3, 200.4, 98.1, -10.5, -300.0], dtype=np_dt)... | Helper for testing various vlen numpy data types.
:param np_dt: Numpy datatype to test
:param dataset_name: String name of the dataset to create for testing. | 625941e75510c4643540f832 |
def addDigits(num): <NEW_LINE> <INDENT> while num >= 10: <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> while num > 0: <NEW_LINE> <INDENT> sum, num = sum + (num % 10), num / 10 <NEW_LINE> <DEDENT> num = sum <NEW_LINE> <DEDENT> return num | :type num: int
:rtype: int | 625941e7293b9510aa2c36eb |
def types(self): <NEW_LINE> <INDENT> return [Akonadi.AgentType()] | list-of-Akonadi.AgentType Akonadi.AgentManager.types() | 625941e771ff763f4b549aec |
def normal(self): <NEW_LINE> <INDENT> len = self.mag_square() <NEW_LINE> if len != 0: <NEW_LINE> <INDENT> len = math.sqrt(len) <NEW_LINE> self.x = self.x // len <NEW_LINE> self.y = self.y // len <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.x = 0 <NEW_LINE> self.y = 0 | :return: Normal of the vector.
:rtype: float
Normal of the vector. | 625941e766673b3332b924ea |
def peek(self): <NEW_LINE> <INDENT> valorRetirar = self.dados[self.tamanho - self.tamanhoFila()] <NEW_LINE> return valorRetirar | Mostra o próximo valor a ser retirado. | 625941e7796e427e537b0a23 |
def ispunc(c, s=set(string.punctuation)): <NEW_LINE> <INDENT> return c in s | Return True if c is a single punctuation character | 625941e791af0d3eaac9be76 |
def all_ratios(df, fill_value, prefix): <NEW_LINE> <INDENT> df = df.replace('null', 0) <NEW_LINE> cc = list(permutations(df.columns,2)) <NEW_LINE> df2 = pd.concat([df[c[1]].div(df[c[0]]) for c in cc], axis=1, keys=cc) <NEW_LINE> df2.columns = df2.columns.map('_'.join) <NEW_LINE> df2 = df2.add_prefix(prefix) <NEW_LINE> ... | will calculate the ratio for each pairing of columns in df
AB and BA for all
Parameters
----------
df : pd.DataFrame index as name:(runUID) and only columns to permute
fill_value : value to fill infinity, fails and blank with
often read from the type_command.csv interface
Returns
-------
df2 : pd.DataFrame ... | 625941e760cbc95b062c699d |
def test_rescue(self): <NEW_LINE> <INDENT> called = {'rescued': False, 'unrescued': False} <NEW_LINE> def fake_rescue(self, context, instance_ref, network_info, image_meta): <NEW_LINE> <INDENT> called['rescued'] = True <NEW_LINE> <DEDENT> self.stubs.Set(nova.virt.fake.FakeDriver, 'rescue', fake_rescue) <NEW_LINE> def f... | Ensure instance can be rescued and unrescued | 625941e797e22403b379d3f5 |
def _build_name_format_model(self, active): <NEW_LINE> <INDENT> name_format_model = Gtk.ListStore(GObject.TYPE_INT, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) <NEW_LINE> index = 0 <NEW_LINE> the_index = 0 <NEW_LINE> for num, name, fmt_str, act in _nd.get_name_format(): <NEW_LINE> <INDENT> translatio... | Create a common model for ComboBox and TreeView | 625941e766673b3332b924eb |
def create_notebook(cells): <NEW_LINE> <INDENT> notebook_dict = {} <NEW_LINE> notebook_dict["cells"] = cells <NEW_LINE> notebook_dict["metadata"] = { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": {"name": "ipython... | Creates a jupyter notebook given a list of cells | 625941e771ff763f4b549aed |
def __init__(self, *args: Union['RowColumnPacker', str, None], orientation='h'): <NEW_LINE> <INDENT> assert orientation in ('h', 'v') <NEW_LINE> assert all(isinstance(obj, Hashable) for obj in args), f"Unhashable elements in args: {args}" <NEW_LINE> self.orientation = orientation <NEW_LINE> self.items = args | :param args: The panels in this object. This can either be a nested Row/Col/RowColumnPacker object, or a string panel name, or RowColumnPacker.OTHER to indicate
that this panel takes any unclaimed windows.
:param orientation: How to stack them: 'h' for horizontal or 'v' for vertical | 625941e763f4b57ef0001566 |
def test_simple_and(self): <NEW_LINE> <INDENT> root = self.get_tree_root_from_expr_str('A and B') <NEW_LINE> prim = root.to_primitives() <NEW_LINE> self.assertTrue(prim is not root) <NEW_LINE> self.assertTrue(prim.l_child is not root.l_child) <NEW_LINE> self.assertTrue(prim.r_child is not root.r_child) <NEW_LINE> self.... | Test that no semantic change occurs for a simple AND expression. | 625941e792d797404e3045e6 |
def set_milestone(self, milestone): <NEW_LINE> <INDENT> self.milestone = milestone | Set milestone.
Args:
milestone(instance): Milestone object. | 625941e796565a6dacc8fb23 |
def init(self): <NEW_LINE> <INDENT> self.log.debug("No user defined init() function.") | User defined init. Called in module constructor before flask
app is started. | 625941e7e1aae11d1e74a115 |
def _parse_binary_peers(self,peers): <NEW_LINE> <INDENT> for i in range(0,len(peers),6): <NEW_LINE> <INDENT> yield peers[i:i+6] | Generator for peers in binary format | 625941e78e05c05ec3eea7d2 |
def __init__(self, name, identifier, link, nodes, fluid, volume, flow_factors, inlet_diameter, outlet_diameter, initial_pressure, filling): <NEW_LINE> <INDENT> assert len(fluid)==2 , "Two different fluids are required.\n" <NEW_LINE> super(DualPhaseTank, self).__init__(name, identifier, link, nodes) <NEW_LINE> self.phas... | class initializer
:param name: string which defines the name of the component
:param identifier: integer which defines the identifier of the component
:param link: associated component of the hydraulic network
:param nodes: list of nodes, it can be from 1 to * depending on the component
:param fluid: Fluid class instan... | 625941e710dbd63aa1bd2ffc |
def hasParent(self): <NEW_LINE> <INDENT> return True if self.parent is not None else False | Return True if the node is not the head else False | 625941e75fcc89381b1e1b1c |
def list_fp16_ops(): <NEW_LINE> <INDENT> return lists.symbol.FP16_FUNCS | Get the default list of FP16 ops for AMP
| 625941e7379a373c97cfafa0 |
def warp(image, u, v, additive_warp=True, normalized=False): <NEW_LINE> <INDENT> shape = tf.shape(image) <NEW_LINE> B, H, W = shape[0], shape[1], shape[2] <NEW_LINE> if normalized: <NEW_LINE> <INDENT> if not additive_warp: <NEW_LINE> <INDENT> u = (u + 1) * 0.5 <NEW_LINE> v = (v + 1) * 0.5 <NEW_LINE> <DEDENT> u *= tf.to... | warp the image with flow(u, v)
If flow=[u, v], representing motion from img1 to img2
then `warp(img2, u, v)->img1~`
Args:
image: a 4-D tensor [B, H, W, C], images to warp
u: horizontal motion vectors of optical flow
v: vertical motion vectors of optical flow
additive_warp: a boolean, if False, reg... | 625941e7fb3f5b602dac3af1 |
def test_verifies_if_expected_false_and_measured_false(self): <NEW_LINE> <INDENT> _, _, _, evaluation = evaluate_binary_condition(False, False) <NEW_LINE> self.assertTrue(evaluation.nominal) | The evaluator should be nominal if true was expected and also measured | 625941e7d4950a0f3b08c7a3 |
def update(self, friendly_name=values.unset, max_size=values.unset): <NEW_LINE> <INDENT> data = values.of({ 'FriendlyName': friendly_name, 'MaxSize': max_size, }) <NEW_LINE> payload = self._version.update( 'POST', self._uri, data=data, ) <NEW_LINE> return QueueInstance( self._version, payload, account_sid=self._solutio... | Update the QueueInstance
:param unicode friendly_name: A human readable description of the queue
:param unicode max_size: The max number of members allowed in the queue
:returns: Updated QueueInstance
:rtype: QueueInstance | 625941e7ad47b63b2c50a3d9 |
def customize_event_incident_report(**attr): <NEW_LINE> <INDENT> s3db = current.s3db <NEW_LINE> attr["rheader"] = None <NEW_LINE> tablename = "event_incident_report" <NEW_LINE> table = s3db[tablename] <NEW_LINE> table.location_id.label=T("Address") <NEW_LINE> current.response.s3.crud_strings[tablename] = Storage( title... | Customize project_project controller | 625941e721a7993f00bc8151 |
def __reports_get_org_trip_by_id( self, trip_id, x_chronosheets_auth, **kwargs ): <NEW_LINE> <INDENT> kwargs['async_req'] = kwargs.get( 'async_req', False ) <NEW_LINE> kwargs['_return_http_data_only'] = kwargs.get( '_return_http_data_only', True ) <NEW_LINE> kwargs['_preload_content'] = kwargs.get( '_preload_content', ... | Get trip by Id, for reporting purposes. Requires the 'ReportAdmin' permission. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.reports_get_org_trip_by_id(trip_id, x_chronosheets_auth, async_req=True)
>>> result... | 625941e71b99ca400220af0e |
def host_okay(self, host: str) -> bool: <NEW_LINE> <INDENT> host = host.lower() <NEW_LINE> if host in self.root_domains: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if re.match(r'\A[\d\.]*\Z', host): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.strict: <NEW_LINE> <INDENT> return self._host_okay_... | Check if a host should be crawled. | 625941e74a966d76dd55146d |
def FirstPass(lx : [str]) -> [Item]: <NEW_LINE> <INDENT> res = [] <NEW_LINE> psisLevel = 0 <NEW_LINE> for s in lx: <NEW_LINE> <INDENT> if s == '(': <NEW_LINE> <INDENT> psisLevel += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> if s == ')': <NEW_LINE> <INDENT> assert psisLevel > 0 <NEW_LINE> psisLevel -= 1 <NEW_LINE> contin... | remove parenthesis, setup vars, makes items | 625941e721bff66bcd684da8 |
def test_correction_benjamini_hochberg(self): <NEW_LINE> <INDENT> print("\nTesting Benjamini and Hochberg multiple testing correction ") <NEW_LINE> df_data = pa.read_csv(test_data_directory_multiple + 'multiple_test_data_BH.tsv', sep='\t') <NEW_LINE> self.obj.statistic_method = "pvalue_hypergeometric" <NEW_LINE> df_dat... | Datas and results are from : www.biostathandbook.com/multiplecomparisons.html
Data are from the article : onlinelibrary.wiley.com/doi/10.1002/ijc.28513/full | 625941e7851cf427c661a965 |
def convex(a, perc_back): <NEW_LINE> <INDENT> noise_center = percentileofscore(a.flat, 0, kind = 'mean') <NEW_LINE> dispersion = np.percentile(a.flat, noise_center - 25 * perc_back) <NEW_LINE> return a <= 0 * (dispersion / 2) | Assumes that noise from background pixels is centered around 0. | 625941e70fa83653e4657412 |
def unhandled_input(self, key): <NEW_LINE> <INDENT> if key in ['q', 'Q']: <NEW_LINE> <INDENT> raise KeyboardInterrupt <NEW_LINE> <DEDENT> if key == ' ': <NEW_LINE> <INDENT> x = self.tree_box.get_focus() <NEW_LINE> import pudb; pudb.set_trace() | call back from MainLoop | 625941e75fdd1c0f98dc068f |
def DeleteLogMetric(self, request, context): <NEW_LINE> <INDENT> context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) | Deletes a logs-based metric.
| 625941e732920d7e50b2862e |
def combobox_change(self): <NEW_LINE> <INDENT> self.close_all() <NEW_LINE> if self.comboBox_tcp.currentIndex() == 0 or self.comboBox_tcp.currentIndex() == 2: <NEW_LINE> <INDENT> self.label_sendto.hide() <NEW_LINE> self.textEdit_ip_send.hide() <NEW_LINE> self.textEdit_send.show() <NEW_LINE> self.label_dir.hide() <NEW_LI... | combobox控件内容改变时触发的槽
:return: None | 625941e77047854f462a185f |
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'enh_eth_tlv': 'list[EnhEthTLV]', 'dcbx_summary_data': 'list[DCBXSummaryData]' } <NEW_LINE> self.attribute_map = { 'enh_eth_tlv': 'enhEthTLV', 'dcbx_summary_data': 'dcbxSummaryData' } <NEW_LINE> self._enh_eth_tlv = None <NEW_LINE> self._dcbx_summary_data = ... | EnhEthTLVSet - 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. | 625941e79f2886367277ace4 |
def addGaussNoise(self, sigma): <NEW_LINE> <INDENT> sz = self.diagonalSize() <NEW_LINE> pts = self.coordinates() <NEW_LINE> n = len(pts) <NEW_LINE> ns = np.random.randn(n, 3)*sigma*sz/100 <NEW_LINE> vpts = vtk.vtkPoints() <NEW_LINE> vpts.SetNumberOfPoints(n) <NEW_LINE> vpts.SetData(numpy_to_vtk(pts+ns, deep=True)) <NEW... | Add gaussian noise.
:param float sigma: sigma is expressed in percent of the diagonal size of actor. | 625941e7d486a94d0b98e5a1 |
def _concat_ngram_list(ngram_list): <NEW_LINE> <INDENT> result = ngram_list[0] <NEW_LINE> for i in range(1, len(ngram_list)): <NEW_LINE> <INDENT> prev_ngram = ngram_list[i - 1] <NEW_LINE> ngram = ngram_list[i] <NEW_LINE> len_overlap = min(len(prev_ngram), len(ngram)) - 1 <NEW_LINE> result += ngram[len_overlap:] <NEW_LI... | Concatenates a list of n-grams.
Adjacent n-grams in the list are expected to be overlapping, and the
overlap is not duplicated in the returned concatenation. The contents of the
n-grams will not be checked however to verify the overlap.
E.g.
With ngram_list = ["abc", "bcde", "ef"]
the concatenation becomes "abcdef"
... | 625941e799cbb53fe679303f |
def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPacmanPos = successorGameState.getPacmanPosition() <NEW_LINE> oldFoodPos = currentGameState.getFood().asList() <NEW_LINE> newFoodPos = successorGameState.getFoo... | Design a better evaluation function here.
The evaluation function takes in the current and proposed successor
GameStates (pacman.py) and returns a number, where higher numbers are better.
The code below extracts some useful information from the state, like the
remaining food (newFood) and Pacman position after moving... | 625941e730bbd722463cc222 |
def test_get_by_patient_existing_account(self): <NEW_LINE> <INDENT> account = self.new_patient_account() <NEW_LINE> res = account._get_by_patient(account.patient_id, False, False) <NEW_LINE> self.assertEqual(account, res) | It should return patient associated with existing account | 625941e70fa83653e4657413 |
def watch(self, name, sleepsec=300): <NEW_LINE> <INDENT> logging.warn('starting %s rss feed watcher' % name) <NEW_LINE> if "<" in name or ">" in name: logging.error("not a proper feed name %s" % name) ; return <NEW_LINE> rssitem = self.byname(name) <NEW_LINE> if rssitem == None: raise RssNoItem() <NEW_LINE> rssitem.dat... | start a watcher thread | 625941e7091ae356686673b1 |
def DeleteFeed(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details("Method not implemented!") <NEW_LINE> raise NotImplementedError("Method not implemented!") | Deletes an asset feed.
| 625941e78a43f66fc4b544bb |
def interface(iface): <NEW_LINE> <INDENT> iface_info, error = _get_iface_info(iface) <NEW_LINE> if error is False: <NEW_LINE> <INDENT> return iface_info.get(iface, {}).get('inet', '') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return error | Return the details of `iface` or an error if it does not exist | 625941e731939e2706e4d2be |
def nlpPipelineHelper(Input, indexQueryFlag=None, doc_id=None,): <NEW_LINE> <INDENT> sentences = segmentIntoSentences(Input) <NEW_LINE> sentence_id = 0 <NEW_LINE> sentences_index_list = [] <NEW_LINE> for sentence in sentences: <NEW_LINE> <INDENT> sentence_id += 1 <NEW_LINE> words = tokenizeIntoWords(sentence) <NEW_LINE... | Helper function for the NLP Pipeline.
This is where the main part of the pipeline happens.
INPUT:
-Input: either user input or article input.
-indexQueryFlag: Flag to determine if we need
to index into SOLR, or query from SOLR.
-doc_id: Docu... | 625941e767a9b606de4a8311 |
def p_js_empty(p): <NEW_LINE> <INDENT> p[0] = [ ] | js : | 625941e760cbc95b062c699e |
def load_roles_list(self): <NEW_LINE> <INDENT> from os.path import join <NEW_LINE> roles_obj = roles_parser() <NEW_LINE> root_obj = self.utGetROOT() <NEW_LINE> content = self.utOpenFile(join(EEAGLOSSARY_PATH, 'config', 'roles.xml')) <NEW_LINE> roles_handler, error = roles_obj.parseContent(content) <NEW_LINE> for role i... | load the role list | 625941e77b180e01f3dc4c4f |
def _insdc_feature_position_string(pos, offset=0): <NEW_LINE> <INDENT> if isinstance(pos, SeqFeature.ExactPosition): <NEW_LINE> <INDENT> return "%i" % (pos.position + offset) <NEW_LINE> <DEDENT> elif isinstance(pos, SeqFeature.WithinPosition): <NEW_LINE> <INDENT> return "(%i.%i)" % (pos.position + offset, pos.position ... | Build a GenBank/EMBL position string (PRIVATE).
Use offset=1 to add one to convert a start position from python counting. | 625941e78e05c05ec3eea7d3 |
def get_contig_fastq_file_list(basepath, names): <NEW_LINE> <INDENT> contig_fastqs = [] <NEW_LINE> for name in names: <NEW_LINE> <INDENT> path = join(basepath, name + '.group.fq') <NEW_LINE> if not exists(path): <NEW_LINE> <INDENT> sys.stderr.write('{0} is missing\n'.format(path)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <... | Get list of paths for joining basepath and names.
Report error on stdout for missing files and removes file from list
Assumes contig files are named after being created by pathdiscov.parse_contigs | 625941e721bff66bcd684da9 |
def handle_bad_response_status_code(r): <NEW_LINE> <INDENT> if not r.ok: <NEW_LINE> <INDENT> error_msg = "Bad {0} request to {1}, status code {2}\n".format( r.request.method, r.url, r.status_code) <NEW_LINE> error_msg += "{}\n".format(r.request.body) <NEW_LINE> error_msg += "{}\n".format(r.json()) <NEW_LINE> raise Agav... | Handle a response with a bad status code
| 625941e7e64d504609d74c9a |
def __len__(self): <NEW_LINE> <INDENT> curr = self._first <NEW_LINE> size = 0 <NEW_LINE> while curr is not None: <NEW_LINE> <INDENT> size += 1 <NEW_LINE> curr = curr.next <NEW_LINE> <DEDENT> return size | Return the number of elements in this list.
@type self: LinkedList
@rtype: int | 625941e766656f66f7cbc607 |
def EnterLockdownMode(self): <NEW_LINE> <INDENT> return self.delegate("EnterLockdownMode")() | Modifies the permissions on the host, so that it will only be accessible
through local console or an authorized centralized management application. Any
user defined permissions found on the host are lost.Modifies the permissions on
the host, so that it will only be accessible through local console or an
authorized cent... | 625941e744b2445a339324ed |
def __init__(self, host, port, timeout, dyn_file_func=None, write_mode=TftpServerWriteMode.Overwrite): <NEW_LINE> <INDENT> self.file_to_transfer = None <NEW_LINE> self.fileobj = None <NEW_LINE> self.options = None <NEW_LINE> self.packethook = None <NEW_LINE> self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ... | Constructor for the base context, setting shared instance
variables. | 625941e74e696a04525c98a8 |
def mean(num_list): <NEW_LINE> <INDENT> return sum(num_list) / len(num_list) | Calculate the mean of a list of numbers
Parameters
----------
num_list: list of int or float
Returns
-------
float of the mean of the list
Examples
--------
>>> mean([1, 2, 3, 4, 5])
3.0 | 625941e799fddb7c1c9de7e9 |
def get_dim_offset(dims): <NEW_LINE> <INDENT> x_off = 0 <NEW_LINE> if 'lon_u' in dims: x_off = 1 <NEW_LINE> y_off = 0 <NEW_LINE> if 'lat_v' in dims: y_off = 1 <NEW_LINE> return x_off, y_off | Return x_offset, y_offset
For the staggered dims, offset=1, otherwise offset=0 | 625941e7e64d504609d74c9b |
def _handle_factory_response(self, num_iter, response_amount, should_notify=False): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for header in self._pending_headers: <NEW_LINE> <INDENT> if isinstance(header, CQCCmdHeader): <NEW_LINE> <INDENT> if self.shouldReturn(header.instr): <NEW_LINE> <INDENT> if header.instr in (CQC_CM... | Handles the responses from a factory command and returns a list of results | 625941e71f037a2d8b946658 |
def _derivative_(self, x, diff_param=None): <NEW_LINE> <INDENT> return -2*exp(-x**2)/sqrt(pi) | Derivative of erfc function.
EXAMPLES::
sage: erfc(x).diff(x)
-2*e^(-x^2)/sqrt(pi) | 625941e76aa9bd52df037202 |
def skipUnlessGoInstalled(func): <NEW_LINE> <INDENT> def is_go_missing(self): <NEW_LINE> <INDENT> compiler = self.getGoCompilerVersion() <NEW_LINE> if not compiler: <NEW_LINE> <INDENT> return "skipping because go compiler not found" <NEW_LINE> <DEDENT> match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler) <NEW_LIN... | Decorate the item to skip tests when no Go compiler is available. | 625941e7627d3e7fe0d692ac |
def process_message(self, connector, host, secret_key, resource, parameters): <NEW_LINE> <INDENT> id = resource['id'] <NEW_LINE> rabbitmq = {} <NEW_LINE> for key, value in parameters.items(): <NEW_LINE> <INDENT> if key not in ('channel', 'header'): <NEW_LINE> <INDENT> rabbitmq[key] = value <NEW_LINE> <DEDENT> <DEDENT> ... | Acual work is done here | 625941e73317a56b8693a0a8 |
def get_interface(self, contract_name): <NEW_LINE> <INDENT> return self.__muzika_contract_interface__.get(contract_name, None) | Returns a contract interface | 625941e74428ac0f6e5bac51 |
def load_url_to_file_handle(url, retry=2, retry_period=1, timeout=10): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fh = urlopen(url, timeout=timeout) <NEW_LINE> <DEDENT> except HTTPError as e: <NEW_LINE> <INDENT> if e.code == 503 and retry: <NEW_LINE> <INDENT> time.sleep(retry_period) <NEW_LINE> return load_url_to_fil... | Loads a given url with retries, retry_periods, and timeouts
Based on https://github.com/ros-infrastructure/rosdistro/blob/master/src/rosdistro/loader.py
:param url: URL to load and return contents of
:type url: str
:param retry: number of times to retry the url on 503 or timeout
:type retry: int
:param retry_period: ... | 625941e75e10d32532c5f380 |
def mouselook(self, boolean=True): <NEW_LINE> <INDENT> self.__ent.mouselook(boolean) <NEW_LINE> return self | Toggle mouselook on the current viewport. Simply call this function
and the user will be able to drag the viewport around.
If the user starts a drag, "StopCamera" will be triggered, which will cancel any existing camera animations.
:param boolean: Activate or deactivate mouselook
:return: Self, this same entity | 625941e7cc0a2c11143dd2ed |
def test1(self): <NEW_LINE> <INDENT> th = TestHelper() <NEW_LINE> p1 = th.add_prefix('1.3.0.0/16', 'reservation', 'test') <NEW_LINE> self.assertEqual(p1.added, p1.last_modified) <NEW_LINE> time.sleep(1) <NEW_LINE> p1.description = 'updated description' <NEW_LINE> p1.save() <NEW_LINE> self.assertNotEqual(p1.added, p1.la... | The last_modified timestamp should be updated when the prefix is
edited | 625941e726068e7796caf140 |
def station_stats(df): <NEW_LINE> <INDENT> pass | Displays statistics on the most popular stations and trip.
Args:
(df) df - pandas DataFrame containing city data filtered by month and day if applicable | 625941e7d164cc61757831aa |
def remoteCapabilities(self): <NEW_LINE> <INDENT> return | Public slot to get the debug clients capabilities. | 625941e74d74a7450ccd461f |
def get_candidates(first_via_idx, via_list, std_cells): <NEW_LINE> <INDENT> candidates = [] <NEW_LINE> first_via = via_list[first_via_idx] <NEW_LINE> first_via_x = first_via[0][0] <NEW_LINE> for i in range(len(std_cells)): <NEW_LINE> <INDENT> cell_width = std_cells[i][2] <NEW_LINE> min_vias = std_cell_info[i][0] <NEW_L... | Generate a list of candidates from the first via.
Each standard cell will be considered for candidates.
If the standard cell cannot be placed there, the value is -1,
otherwise, it will be a list of vias.
:param first_via_idx: first via index in the via_list
:param via_list: the list of all vias (in a row)
:param std_c... | 625941e74d74a7450ccd4620 |
def clean_course_file(self): <NEW_LINE> <INDENT> upload = self.cleaned_data["course_file"] <NEW_LINE> log.debug("checking filename %s", upload.name) <NEW_LINE> for ext in (".zip", ".tar.gz", ".tgz"): <NEW_LINE> <INDENT> if upload.name.endswith(ext): <NEW_LINE> <INDENT> log.debug("the filename is good") <NEW_LINE> uploa... | Only certain extensions are allowed. | 625941e74527f215b584c8ad |
def __init__(self, paths): <NEW_LINE> <INDENT> rows = [] <NEW_LINE> for path in paths: <NEW_LINE> <INDENT> row = dict(path=path) <NEW_LINE> with fits.open(path) as image: <NEW_LINE> <INDENT> for key in self._parse_headers: <NEW_LINE> <INDENT> row[key] = image[0].header[key] <NEW_LINE> <DEDENT> <DEDENT> rows.append(row)... | A collection of images, with some useful features.
:param paths:
The file system paths to the images. | 625941e7a05bb46b383ecc78 |
def keyword_list(request): <NEW_LINE> <INDENT> pytrends = TrendReq(hl='ja-JP', tz=360) <NEW_LINE> response = pytrends.trending_searches(pn='japan') <NEW_LINE> object_list = response.values.tolist() <NEW_LINE> return render(request, 'cms/keyword_list.html', {'object_list': object_list}) | キーワード一覧 | 625941e74f6381625f114e97 |
def timeout_handler(signum, stack): <NEW_LINE> <INDENT> raise SystemExit("Timeout expired: Game Over!") | Handle the `SIGALRM` to kill the current process. | 625941e7dd821e528d63b600 |
def gather_acronym(acro): <NEW_LINE> <INDENT> pass | Gets the requested acronym from the user and determines if it
exists in the DB. If it does, then it returns the context. | 625941e7d58c6744b42580b9 |
def get_play_order(self): <NEW_LINE> <INDENT> return self.__gconf.get_string(PLAY_ORDER_KEY) | Returns the play order | 625941e73cc13d1c6d3c77d3 |
def Slice_Sampling(x, pdf, iters, w, m): <NEW_LINE> <INDENT> samples = np.zeros(iters) <NEW_LINE> for i in range(iters): <NEW_LINE> <INDENT> y = np.random.rand() * pdf(x) <NEW_LINE> (L, R) = steppingOut(pdf, x, y, w, m) <NEW_LINE> s = shrinkage(pdf, x, y, (L, R)) <NEW_LINE> samples[i] = s <NEW_LINE> x = s <NEW_LINE> <D... | Basic slice sampling using step-out scheme. This sampler seems
work better than MH in 1-dimension situation.
Maybe the pdf can be changed to logpdf for better precision. | 625941e7956e5f7376d712c7 |
def add_xml(self, xml: str) -> None: <NEW_LINE> <INDENT> self.__add({ "type": "Xml", "xml": xml }) | 添加xml文本
:param xml: xml文本内容
:return: 无 | 625941e7dc8b845886cb5992 |
def _add_collections( self, assets_collection, legacy_init_op, main_op, train_op): <NEW_LINE> <INDENT> self._save_and_write_assets(assets_collection) <NEW_LINE> if main_op is None: <NEW_LINE> <INDENT> self._maybe_add_legacy_init_op(legacy_init_op) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._add_main_op(main_op)... | Add asset and op collections to be saved. | 625941e7bf627c535bc1362a |
@pytest.mark.parametrize( "uri, extend_with, expected_path", [ ("https://api.github.com", "/users", "/users"), ("https://api.github.com", "/users/", "/users/"), ("https://api.github.com", "users", "/users"), ("https://api.github.com", "users/", "/users/"), ("", "users/", "/users/"), ("", "users", "/users"), ("?foo=bar"... | Verify the behaviour of extend_path. | 625941e7f9cc0f698b140a52 |
def __repr__(self): <NEW_LINE> <INDENT> return str.format('ClipPath(uid={}, type={}, children={})', repr(self.uid), repr(self.type), repr(self.children)) | Return a constructor-style representation of this ClipPath. | 625941e76fece00bbac2db9f |
def unify(x, y, subst): <NEW_LINE> <INDENT> if subst is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif x == y: <NEW_LINE> <INDENT> return subst <NEW_LINE> <DEDENT> elif isinstance(x, ExVar): <NEW_LINE> <INDENT> return unify_variable(x, y, subst) <NEW_LINE> <DEDENT> elif isinstance(y, ExVar): <NEW_LINE> ... | Unifies term x and y with initial subst.
Returns a subst (map of name->term) that unifies x and y, or None if
they can't be unified. Pass subst={} if no subst are initially
known. Note that {} means valid (but empty) subst. | 625941e7bde94217f3683248 |
def as_json(self): <NEW_LINE> <INDENT> return { "status": self.status, "cases": [c.as_json() for c in self.test_cases] } | Get all test case information as JSON/dict
Returns:
(dict): JSON object/dict of information for all test cases | 625941e78e7ae83300e4b429 |
def setSlippageModel(self, slippageModel): <NEW_LINE> <INDENT> self.__slippageModel = slippageModel | Set the slippage model to use.
:param slippageModel: The slippage model.
:type slippageModel: :class:`pyalgotrade.broker.slippage.SlippageModel` | 625941e7adb09d7d5db6cbe8 |
def _parse_repo(self, data): <NEW_LINE> <INDENT> if not isinstance(data, dict): <NEW_LINE> <INDENT> raise AttributeError("Expected a dict object") <NEW_LINE> <DEDENT> return { 'url': data['url'], 'description': data.get('description', ''), 'name': data.get('name'), 'forks': data.get('forks'), 'watchers': data.get('watc... | Returns a dict suitable for creating a project. | 625941e7a17c0f6771cbe4aa |
def parse_mysql_url(url: str): <NEW_LINE> <INDENT> res = re.findall("mysql://([\S]*):([\S]*)@([\S]*):([\d]*)/([\S]*)\?", url) <NEW_LINE> try: <NEW_LINE> <INDENT> if res: <NEW_LINE> <INDENT> attrs = res[0] <NEW_LINE> return { "user": attrs[0], "pwd": attrs[1], "host": attrs[2], "port": attrs[3], "db": attrs[4] } <NEW_LI... | parse msyql-url to dict
:url: str e.g:"mysql://root:123456@127.0.0.1:3306/test?charset=utf-8"
:returns: dict e.g:{'user': 'root', 'pwd': '123456', 'host': '127.0.0.1', 'port': '3306', 'db': 'test'}
:raises Exception: mysql-url format error! | 625941e72eb69b55b151cd11 |
def create_baseline(y_values): <NEW_LINE> <INDENT> diff = 0.25 <NEW_LINE> if type(y_values[0]) is list: <NEW_LINE> <INDENT> baseline = [list(map(lambda y: y + diff, ys)) for ys in y_values] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> baseline = list(map(lambda y: y + diff, y_values)) <NEW_LINE> <DEDENT> return baseli... | Just add a small number to the y_values to create the baseline series. | 625941e776e4537e8c351ad1 |
def darken(start_hex, amount): <NEW_LINE> <INDENT> start_rbg = hex_to_rgb(start_hex) <NEW_LINE> darker = [int(s * (1 - amount * .5)) for s in start_rbg] <NEW_LINE> return rgb_to_hex(darker) | Darken the given color by the given amount (sensitivity will be cut in half)
:param start_hex: original color
:type start_hex: str
:param amount: how much to darken (1.0 -> 50% darker)
:type amount: float
:return: darker version of color
:rtype: str | 625941e71d351010ab855f76 |
def get_files(self, list_fname): <NEW_LINE> <INDENT> list_files = [] <NEW_LINE> for i in range(0, list_fname.__len__()): <NEW_LINE> <INDENT> path = os.getcwd() + list_fname <NEW_LINE> list_files.append(path) <NEW_LINE> <DEDENT> return list_files | :return: True/False Successful/Failed | 625941e75fc7496912cc3dd9 |
def register_multi_flags_validator(flag_names, multi_flags_checker, message='Flags validation failed', flag_values=_flagvalues.FLAGS): <NEW_LINE> <INDENT> v = _validators_classes.MultiFlagsValidator( flag_names, multi_flags_checker, message) <NEW_LINE> _add_validator(flag_values, v) | Adds a constraint to multiple flags.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_names: [str], a list of the flag names to be checked.
multi_flags_checker: callable, a function to validate the flag.
input - dict, with keys(... | 625941e7d7e4931a7ee9e37a |
def get_periods(src, dest): <NEW_LINE> <INDENT> cookies = None <NEW_LINE> try: <NEW_LINE> <INDENT> url_connect = None <NEW_LINE> response_connect = requests.get(url_connect) <NEW_LINE> cookies = response_connect.cookies <NEW_LINE> url_periods = None <NEW_LINE> headers = {'Accept': 'application/json'} <NEW_LINE> respons... | Get periods. | 625941e7a17c0f6771cbe4ab |
def __str__(self): <NEW_LINE> <INDENT> if(self.data is None or self.data == ''): <NEW_LINE> <INDENT> return "{0.instruction:X}#{0.start:X}#{0.end:X}#".format(self) <NEW_LINE> <DEDENT> return "{0.instruction:X}#{0.start:X}#{0.end:X}#{1}#{2}".format( self, ','.join(["{0:X}".format(i) for i, c in enumerate(self.data) if c... | Returns a String representation of the
DisassembleInstruction. This is the instruction code in
hexadecimal, followed by a '#' followed by the start address in
hexadecimal, followed by a '#', followed by the end address in
hexadecimal, followed by a '#'. If the data property is not
None then a comma seperated list of ... | 625941e771ff763f4b549aee |
def clear_classifier(): <NEW_LINE> <INDENT> nfq_classifier = NfqClassifier() <NEW_LINE> nfq_classifier.remove_all_rsps() | Clear all created iptables rules (if any) | 625941e707d97122c4178cf1 |
def filter_queryset(self, queryset): <NEW_LINE> <INDENT> return self.filter_provision_view_queryset(queryset) | filter_queryset
:param queryset:
:return: :raise NotFound: | 625941e755399d3f05588b12 |
def _shadow_copy(self, brain): <NEW_LINE> <INDENT> towers = [] <NEW_LINE> towers.append(brain) <NEW_LINE> for i in range(1, self.gpu_num): <NEW_LINE> <INDENT> with P.device('/gpu:{}'.format(i)): <NEW_LINE> <INDENT> tower = brain.get_shadow_copy() <NEW_LINE> tower.setup() <NEW_LINE> towers.append(tower) <NEW_LINE> <DEDE... | Make `self.gpu_num` number of shadow copy of `brain`. A list of shadow
copies will be returned. The original brain will be put at the first of
the list. | 625941e7bd1bec0571d90a8a |
def finish_turn(self): <NEW_LINE> <INDENT> was_alive = set(i for i in range(self.num_players) if self.is_alive(i)) <NEW_LINE> self.do_orders() <NEW_LINE> self.do_attack() <NEW_LINE> self.do_spawn() <NEW_LINE> self.food_extra += Fraction(self.food_rate * self.num_players, self.food_turn) <NEW_LINE> food_now = self.food_... | Called by engine at the end of the turn | 625941e74e696a04525c98a9 |
def init_fields(self): <NEW_LINE> <INDENT> if self.settings.value('g_test_dir') is None: <NEW_LINE> <INDENT> self.settings.setValue('g_test_dir', '\\\\gs\\tucsonaz-w\\wsc\\Gravity Data Archive\\') <NEW_LINE> <DEDENT> if self.settings.value('g_input_dir') is None: <NEW_LINE> <INDENT> self.settings.setValue('g_input_dir'... | If it's the first time a user has opened ingestor, populate the directories/files
:return: None | 625941e7009cb60464c63809 |
def __init__(self, path, jobs=0, fillnan='ffill', nlags=24, important_future_timesteps=[1], train_val_split=0.8): <NEW_LINE> <INDENT> warnings.filterwarnings('ignore') <NEW_LINE> self.path = path <NEW_LINE> self.jobs = jobs <NEW_LINE> self.fillnan = fillnan <NEW_LINE> self.nlags = nlags <NEW_LINE> self.data = pd.read_c... | AutoML is an auto machine learning project with focus on predict
time series using simple usage and high-level understanding over
time series prediction methods.
:param path:
Path to the input csv. The csv must be in the format (date, value).
:param jobs:
Number of jobs used during the training and evaluatio... | 625941e73539df3088e2e7a7 |
def exist(self, board, word): <NEW_LINE> <INDENT> b = [[False for i in range(len(board[0]))] for j in range(len(board))] <NEW_LINE> for i in range(len(board)): <NEW_LINE> <INDENT> for j in range(len(board[0])): <NEW_LINE> <INDENT> if board[i][j] == word[0] and self.backtrack(board, word, 0, i, j, b): <NEW_LINE> <INDENT... | :type board: List[List[str]]
:type word: str
:rtype: bool | 625941e79c8ee82313fbbbd2 |
def publish_page(page, user, language): <NEW_LINE> <INDENT> page = page.reload() <NEW_LINE> class FakeRequest(object): <NEW_LINE> <INDENT> def __init__(self, user): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> <DEDENT> <DEDENT> request = FakeRequest(user) <NEW_LINE> if not page.has_publish_permission(request): <NEW_... | Publish a page. This sets `page.published` to `True` and calls publish()
which does the actual publishing.
See docs/extending_cms/api_reference.rst for more info | 625941e70a366e3fb873ec7a |
def update(self): <NEW_LINE> <INDENT> self.x += self.speed_factor <NEW_LINE> self.rect.x = self.x | Перемещает пулю вправо по экрану. | 625941e715fb5d323cde0f71 |
def processLinkFile(self, filename, capfilepath = None): <NEW_LINE> <INDENT> linkentries = [] <NEW_LINE> fd = self.vfs.open(filename, "rt") <NEW_LINE> while 1: <NEW_LINE> <INDENT> nextstep, entry = self.getLinkItem(fd, capfilepath) <NEW_LINE> if entry: <NEW_LINE> <INDENT> linkentries.append(entry) <NEW_LINE> <DEDENT> i... | Processes a link file. If capfilepath is set, it should
be the equivolent of the Path= in a .names file. | 625941e7ec188e330fd5abf2 |
def test_writeBytesDecoded(self) -> None: <NEW_LINE> <INDENT> f = self.observedFile(encoding="utf-8") <NEW_LINE> f.write(b"Hello, Mr. S\xc3\xa1nchez\n") <NEW_LINE> self.assertEqual(f.messages, ["Hello, Mr. S\xe1nchez"]) | Bytes are decoded to text. | 625941e7167d2b6e31218ff0 |
def getStrongest(self, arr, k): <NEW_LINE> <INDENT> arr.sort() <NEW_LINE> m = arr[(len(arr)-1)//2] <NEW_LINE> arr.sort(key=lambda x: (-abs(x-m), -x)) <NEW_LINE> return arr[:k] | :type arr: List[int]
:type k: int
:rtype: List[int] | 625941e756ac1b37e6264622 |
def Run(self, args): <NEW_LINE> <INDENT> conn_context = connection_context.GetConnectionContext(args) <NEW_LINE> domain_mapping_ref = args.CONCEPTS.domain.Parse() <NEW_LINE> with serverless_operations.Connect(conn_context) as client: <NEW_LINE> <INDENT> client.DeleteDomainMapping(domain_mapping_ref) <NEW_LINE> msg = ""... | Delete domain mappings. | 625941e7d53ae8145f87a6c3 |
def postA(self): <NEW_LINE> <INDENT> return S.true | assumption when the contract terminates | 625941e7c432627299f050a5 |
def build_output(self, speed: float, eta: datetime.timedelta) -> str: <NEW_LINE> <INDENT> percent = round(100 * float(self.count) / self.total, self.precision) <NEW_LINE> pad_right = '{:>{width}}' <NEW_LINE> pad_decimals = '{.{precision}f}%' <NEW_LINE> data = { 'file_path': self.name, 'count': pad_right.format(self.cou... | Builds the string that will be output to show progress.
Args:
speed: Amount of work done per second.
eta: Estimated time to complete the remaining work.
Returns:
The string to output to show progress | 625941e77b180e01f3dc4c50 |
def bond_is_conjugated_one_hot(bond, allowable_set=None, encode_unknown=False): <NEW_LINE> <INDENT> if allowable_set is None: <NEW_LINE> <INDENT> allowable_set = [False, True] <NEW_LINE> <DEDENT> return one_hot_encoding(bond.GetIsConjugated(), allowable_set, encode_unknown) | One hot encoding for whether the bond is conjugated.
Parameters
----------
bond : rdkit.Chem.rdchem.Bond
RDKit bond instance.
allowable_set : list of bool
Conditions to consider. Default: ``False`` and ``True``.
encode_unknown : bool
If True, map inputs not in the allowable set to the
additional last el... | 625941e7711fe17d825427bd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.