Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals @pytest.mark.online def test_response(credentials): <|code_end|> , predict the immediate next line with the help of imports: import pytest import types from rakuten_ws.webservice import RakutenWebService from rakuten_...
ws = RakutenWebService(**credentials)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals @pytest.mark.online def test_response(credentials): ws = RakutenWebService(**credentials) response = ws.ichiba.item.search(keyword="Naruto") <|code_end|> using the current file's imports: ...
assert isinstance(response, ApiResponse)
Given snippet: <|code_start|> return PrettyStringRepr(json.dumps(self.data, ensure_ascii=False, sort_keys=True, indent=4, separators=(',', ': '))) def pages(self): yield self.response page_number = int(self.response['page']) + 1 while page_n...
method_endpoint = camelize(self.method.alias)
Given the following code snippet before the placeholder: <|code_start|> def __init__(self, endpoint, method): self.endpoint = endpoint self.method = method @property def application_id(self, *args, **kwargs): app_id = self.endpoint.service.webservice.application_id if app_id ...
request_params.update(camelize_dict(kwargs))
Given snippet: <|code_start|> self.endpoint = endpoint self.method = method @property def application_id(self, *args, **kwargs): app_id = self.endpoint.service.webservice.application_id if app_id is None: raise Exception("An 'application_id' must be provided") ...
api_request.add(sorted_dict(request_params))
Predict the next line for this snippet: <|code_start|> api_request.path.segments.append(method_endpoint) api_request.path.segments.append(api_version) api_request.path.normalize() request_params = { 'applicationId': self.application_id, 'formatVersion': self.endpo...
method_name = clean_python_variable_name(method.name)
Next line prediction: <|code_start|># coding: utf-8 from __future__ import unicode_literals class ApiMethod(object): def __init__(self, name, alias=None, api_version=None): self.name = name self.alias = alias or name self.api_version = api_version class ApiResponse(UserDict): def...
return PrettyStringRepr(json.dumps(self.data, ensure_ascii=False, sort_keys=True,
Next line prediction: <|code_start|># coding: utf-8 from __future__ import unicode_literals class ApiMethod(object): def __init__(self, name, alias=None, api_version=None): self.name = name self.alias = alias or name self.api_version = api_version <|code_end|> . Use current file impo...
class ApiResponse(UserDict):
Given snippet: <|code_start|>from __future__ import unicode_literals parker = Parker(dict_type=dict) class PrettyStringRepr(str): # Useful for debug def __repr__(self): if is_py2: return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8') else: return t...
for k, v in iteritems(data):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals parker = Parker(dict_type=dict) class PrettyStringRepr(str): # Useful for debug def __repr__(self): if is_py2: <|code_end|> using the current file's imports: import re impor...
return to_unicode(self.replace(' \n', '\n').strip()).encode('utf-8')
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals parker = Parker(dict_type=dict) class PrettyStringRepr(str): # Useful for debug def __repr__(self): <|code_end|> , predict the next line using imports from the current ...
if is_py2:
Here is a snippet: <|code_start|> parts = key.split(".") d = unflat_dict for part in parts[:-1]: if part not in d: d[part] = dictionary.__class__() d = d[part] d[parts[-1]] = value def unflatten_list_dict(dictionary): unflat_list_dict =...
scheme = urlparse(url).scheme
Given the code snippet: <|code_start|> unflat_list = [] for key in sorted(unflat_dict.keys()): unflat_list.append(unflat_dict[key]) new_value = unflat_list else: new_value = unflat_dict ...
return fileobj, guess_type(pathname2url(url))[0]
Given snippet: <|code_start|>#!/usr/bin/env python # coding: utf-8 credentials = { 'application_id': os.environ.get('RAKUTEN_APP_ID', ''), 'license_key': os.environ.get('RMS_LICENSE_KEY', ''), 'secret_service': os.environ.get('RMS_SECRET_SERVICE', ''), 'shop_url': os.environ.get('RMS_SHOP_URL', ''), }...
ws = RakutenWebService(**credentials)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals class SimpleAPI(ApiService): api_url = "https://testapi" api_version = "20140222" format_version = 2 <|code_end|> , determine the next line of code. You have imports: from rakuten_ws.baseapi import ApiServic...
item = ApiEndpoint(ApiMethod('search'), ApiMethod('ranking'))
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals class SimpleAPI(ApiService): api_url = "https://testapi" api_version = "20140222" format_version = 2 item = ApiEndpoint(ApiMethod('search'), ApiMethod('ranking')) product = ApiEndpoint(ApiMethod('get'...
class SimpleWebService(BaseWebService):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals class SimpleAPI(ApiService): api_url = "https://testapi" api_version = "20140222" format_version = 2 item = ApiEndpoint(ApiMethod('search'), ApiMethod('ranking')) product = ApiE...
assert isinstance(ws.test_api.item.search, ApiRequest)
Using the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals class SimpleAPI(ApiService): api_url = "https://testapi" api_version = "20140222" format_version = 2 <|code_end|> , determine the next line of code. You have imports: from rakuten_ws.baseapi import ApiServic...
item = ApiEndpoint(ApiMethod('search'), ApiMethod('ranking'))
Given snippet: <|code_start|> class Server(object): ''' The Server object owns the websocket connection and all attached channel information. ''' def __init__(self, token, connect=True, proxies=None): self.token = token self.username = None self.domain = None self.log...
self.api_requester = SlackRequest(proxies=proxies)
Given the following code snippet before the placeholder: <|code_start|> return self.send_to_websocket({"type": "ping"}) def websocket_safe_read(self): """ Returns data if available, otherwise ''. Newlines indicate multiple messages """ data = "" while True: ...
self.channels.append(Channel(self, name, channel_id, members))
Continue the code snippet: <|code_start|> class SlackRequest(object): def __init__(self, proxies=None): # __name__ returns 'slackclient.slackrequest', we only want 'slackclient' client_name = __name__.split('.')[0] <|code_end|> . Use current file imports: import json import requests import six ...
client_version = __version__ # Version is returned from version.py
Here is a snippet: <|code_start|> return change_to_id(magnum.cluster_show(request, cluster_id).to_dict()) @rest_utils.ajax(data_required=True) def patch(self, request, cluster_id): """Update a Cluster. Returns the Cluster object on success. """ params = request.DATA ...
stack = heat.stack_get(request, cluster["stack_id"])
Based on the snippet: <|code_start|> available_addons = [] configured_addons = getattr( settings, "MAGNUM_AVAILABLE_ADDONS", []) for configured_addon in configured_addons: addon = {} try: addon["name"] = configured_addon["name"] ...
return change_to_id(magnum.cluster_template_show(request, template_id)
Given snippet: <|code_start|> user = User.query.get('123123') self.assertIsNone(user) User.from_facebook('oauth_234234') mock_graphapi.assert_called_with(access_token='oauth_234234') graph_instance.get_object.assert_called_with(id='me') user = User.query.get('123123') ...
UserFactory(
Given snippet: <|code_start|> class UserTests(BlindrTest): @freeze_time('2015-01-01') @mock.patch('blindr.models.user.name_generator.generate_name') @mock.patch('blindr.models.user.facebook.GraphAPI') def test_from_facebook_new_user(self, mock_graphapi, mock_generate_name): graph_instance = mo...
user = User.query.get('123123')
Next line prediction: <|code_start|> class EventTests(unittest.TestCase): @freeze_time('2015-01-01') def test_create(self): events.put_item = MagicMock(return_value = 'put_item_ret') <|code_end|> . Use current file imports: (import tests.utils.fake_dynamodb import unittest import time import boto fro...
event = Event.create({'foo': 'bar'})
Given the following code snippet before the placeholder: <|code_start|> class EventTests(unittest.TestCase): @freeze_time('2015-01-01') def test_create(self): <|code_end|> , predict the next line using imports from the current file: import tests.utils.fake_dynamodb import unittest import time import boto from...
events.put_item = MagicMock(return_value = 'put_item_ret')
Here is a snippet: <|code_start|> def token_authentication(token): if not token: return False s = itsdangerous.Signer(current_app.config['AUTH_SECRET']) user_id = False try: user_id = s.unsign(token).decode('utf-8') except itsdangerous.BadSignature: pass <|code_end|> . Writ...
return User.query.get(user_id)
Predict the next line for this snippet: <|code_start|> def post(self): dst_city = request.form.get('dst_city') dst_user = request.form.get('dst_user') message = request.form.get('message') dst = None if dst_city: dst = 'city:{}'.format(dst_city.lower()) el...
success = Event.create(data)
Based on the snippet: <|code_start|> class LikeTest(BlindrTest): def test_post_first_like(self): UserFactory(id='user2') rv = self.auth_post('/events/like', data=dict(dst_user='user2')) rv_data = json.loads(rv.data.decode('utf-8')) self.assert_200(rv) match = Match.query....
MatchFactory(
Given the following code snippet before the placeholder: <|code_start|> class LikeTest(BlindrTest): def test_post_first_like(self): UserFactory(id='user2') rv = self.auth_post('/events/like', data=dict(dst_user='user2')) rv_data = json.loads(rv.data.decode('utf-8')) self.assert_20...
match = Match.query.get((self.auth_user.id,'user2'))
Continue the code snippet: <|code_start|> class NameGeneratorTest(unittest.TestCase): @mock.patch('blindr.common.name_generator.random.choice') def test_generate_name(self, mock_random_choice): mock_random_choice.side_effect = lambda x: x[0] <|code_end|> . Use current file imports: import unittest from...
name_generator.nouns = ('foo',)
Predict the next line for this snippet: <|code_start|> class History(restful.Resource): method_decorators=[authenticate] def get(self, other_id): sinceParam = int(request.args.get('since')) <|code_end|> with the help of current file imports: from flask.ext import restful from blindr.common.authentic...
return Event.fetch_history(user= self.user.id,
Based on the snippet: <|code_start|> class DislikeTest(BlindrTest): def test_post_dislike(self): MatchFactory( match_from_id=self.auth_user.id, <|code_end|> , predict the immediate next line with the help of imports: from tests.blindrtest import BlindrTest from tests.factory_boy.match_factory ...
match_to_id=UserFactory(id='user2').id,
Based on the snippet: <|code_start|> class DislikeTest(BlindrTest): def test_post_dislike(self): MatchFactory( match_from_id=self.auth_user.id, match_to_id=UserFactory(id='user2').id, mutual=True ) rv = self.auth_post('/events/dislike', data=dict(dst_use...
self.assertIsNone(Match.query.get((self.auth_user.id,'user2')))
Using the snippet: <|code_start|> class Auth(restful.Resource): def post(self): fb_token = request.form.get('fb_token') <|code_end|> , determine the next line of code. You have imports: from flask.ext import restful from flask import current_app, request, abort from blindr.models.user import User import it...
user = User.from_facebook(fb_token)
Based on the snippet: <|code_start|> class AuthTest(BlindrTest): @mock.patch('blindr.api.auth.User.from_facebook') def test_success_auth(self, mock_user): <|code_end|> , predict the immediate next line with the help of imports: from tests.blindrtest import BlindrTest from tests.factory_boy.user_factory import...
user = UserFactory.create(id='123123')
Next line prediction: <|code_start|> previous = mo.retrieve("group", unique_id=test.prev_uid)[0] assert len(previous.items) == 2, repr(previous) def test_store_stubs(sqlite): test = mo.Group(items=[mo.Group(items=[mo.LcmsRun()]), mo.LcmsRun()]) mo.store(test) test = mo.retrieve("group", unique_id=t...
for klass in metoh.Workspace.get_instance().subclass_lut.values():
Given snippet: <|code_start|>def remove_objects(objects, all_versions=True, **kwargs): """Remove objects from the database. Parameters ---------- all_versions: boolean, optional If True, remove all versions of the object sharing the current head_id. """ if isinstance(objects, st...
@set_docstring
Given the code snippet: <|code_start|># Whether to fetch stubs automatically, disabled when we want to display # a large number of objects. FETCH_STUBS = True ADDUCTS = ('','[M]+','[M+H]+','[M+H]2+','[M+2H]2+','[M+H-H2O]2+','[M+K]2+','[M+NH4]+','[M+Na]+','[M+H-H2O]+','[M-H]-','[M-2H]-','[M-H+Cl]-','[M-2H]2-','[M+Cl]-',...
workspace = Workspace.get_instance()
Given the following code snippet before the placeholder: <|code_start|> if val.unique_id != other.unique_id: msg.append((tname, other.unique_id, val.unique_id)) elif isinstance(trait, MetList): if not len(val) == len(other): msg.append((...
state['creation_time'] = format_timestamp(self.creation_time)
Here is a snippet: <|code_start|> self.last_modified = time.time() return True, None else: changed, prev_uid = self._changed, self.prev_uid if changed: self.last_modified = time.time() self.prev_uid = uuid.uuid4().hex self._c...
if recursive and isinstance(trait, MetList):
Given the code snippet: <|code_start|> Parameters ---------- all_versions: boolean, optional If True, remove all versions of the object sharing the current head_id. """ if isinstance(objects, str): print('remove_objects() expects actual objects, use remove() to' ...
name = MetUnicode('Untitled', help='Name of the object')
Given the following code snippet before the placeholder: <|code_start|># ctime = os.stat(fname).st_ctime # run = LcmsRun(name=filename, description=description, # created_by=user, # modified_by=user, # created=ctime, l...
injection_volume = MetFloat()
Predict the next line for this snippet: <|code_start|> else: changed, prev_uid = self._changed, self.prev_uid if changed: self.last_modified = time.time() self.prev_uid = uuid.uuid4().hex self._changed = False self._loopback_guard = False ...
elif recursive and isinstance(trait, MetInstance) and val:
Continue the code snippet: <|code_start|> If True, remove all versions of the object sharing the current head_id. """ if isinstance(objects, str): print('remove_objects() expects actual objects, use remove() to' 'remove objects by type.') workspace = Workspace.get_instan...
creation_time = MetInt(help='Unix timestamp at object creation').tag(readonly=True)
Predict the next line for this snippet: <|code_start|> how the sample was prepared and LCMS data was collected. """ protocol_ref = MetUnicode(help='Reference to a published protocol: ' + 'identical to the protocol used.') quenching_method = MetUnicode(help='Description of the method used to ' + ...
polarity = MetEnum(POLARITY, 'positive', help='polarity for the run')
Predict the next line after this snippet: <|code_start|> 'remove objects by type.') workspace = Workspace.get_instance() workspace.remove_objects(objects, all_versions, **kwargs) workspace.close_connection() def store(objects, **kwargs): """Store Metatlas objects in the database. Par...
_loopback_guard = MetBool(False).tag(readonly=True)
Based on the snippet: <|code_start|> """Remove objects from the database. Parameters ---------- all_versions: boolean, optional If True, remove all versions of the object sharing the current head_id. """ if isinstance(objects, str): print('remove_objects() expects actual ...
class MetatlasObject(HasTraits):
Next line prediction: <|code_start|> break elif val != other: msg.append((tname, str(other), str(val))) print((tabulate(msg))) def _on_update(self, change): """When the model changes, set the update fields. """ if self._loopback...
if isinstance(value, Stub) and FETCH_STUBS:
Predict the next line for this snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): "...
analysis_number: AnalysisNumber = Int(default_value=0, read_only=True)
Given the code snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in ...
experiment: Experiment = Unicode(read_only=True)
Using the snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in gener...
exclude_files: FileMatchList = traitlets.List(trait=Unicode(), default_value=[], read_only=True)
Continue the code snippet: <|code_start|> logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=True) exper...
_all_groups: GroupList = traitlets.List(allow_none=True, default_value=None, read_only=True)
Given snippet: <|code_start|> "short_samplename": [9, 12, 13, 14], } out = pd.DataFrame(columns=fields.keys()) for i, lcms_file in enumerate(self.lcmsruns): tokens = lcms_file.name.split(".")[0].split("_") for name, idxs in fields.items(): ...
def _files_dict(self) -> Dict[str, LcmsRunDict]:
Predict the next line for this snippet: <|code_start|> logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generating an analysis""" project_directory: PathString = Unicode(read_only=T...
_lcmsruns: LcmsRunsList = traitlets.List(allow_none=True, default_value=None, read_only=True)
Given the following code snippet before the placeholder: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(...
project_directory: PathString = Unicode(read_only=True)
Here is a snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in gener...
polarity: Polarity = Unicode(default_value="positive", read_only=True)
Given the following code snippet before the placeholder: <|code_start|> self.set_trait("_lcmsruns", lcmsruns) self.set_trait("_all_groups", all_groups) logger.info( "IDs: source_atlas=%s, atlas=%s, short_experiment_analysis=%s, output_dir=%s", self.source_atlas, ...
if proposal["value"] not in POLARITIES:
Given the code snippet: <|code_start|> ) self.set_trait("_lcmsruns", lcmsruns) self.set_trait("_all_groups", all_groups) logger.info( "IDs: source_atlas=%s, atlas=%s, short_experiment_analysis=%s, output_dir=%s", self.source_atlas, self.atlas, ...
def _valid_polarity(self, proposal: Proposal) -> Polarity:
Predict the next line for this snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): "...
output_type: OutputType = Unicode(read_only=True)
Predict the next line for this snippet: <|code_start|> self.short_experiment_analysis, self.output_dir, ) self.store_all_groups(exist_ok=True) self.set_trait("exclude_groups", append_inverse(self.exclude_groups, self.polarity)) @property def _default_include_group...
if proposal["value"] not in OUTPUT_TYPES:
Given the following code snippet before the placeholder: <|code_start|> @property def _exp_tokens(self) -> List[str]: """Returns list of strings from the experiment name""" return self.experiment.split("_") @property def project(self) -> int: """Returns project number (proposal i...
def short_polarity(self) -> ShortPolarity:
Using the snippet: <|code_start|> """Returns list of strings from the experiment name""" return self.experiment.split("_") @property def project(self) -> int: """Returns project number (proposal id)""" return int(self._exp_tokens[3]) @property def atlas(self) -> AtlasNam...
return SHORT_POLARITIES[self.polarity]
Given snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in generatin...
source_atlas: Optional[AtlasName] = Unicode(allow_none=True, default_value=None, read_only=True)
Based on the snippet: <|code_start|> return ["QC"] return [] def _get_default_exclude_groups(self, polarity: Polarity) -> GroupMatchList: out: GroupMatchList = ["InjBl", "InjBL"] if self.output_type not in ["data_QC"]: out.append("QC") return append_inverse(ou...
get_atlas(proposed_name, cast(Username, "*")) # raises error if not found or matches multiple
Given the code snippet: <|code_start|>""" AnalysisIdentifiers object for use with MetatlasDataset """ # pylint: disable=too-many-lines logger = logging.getLogger(__name__) DEFAULT_GROUPS_CONTROLLED_VOCAB = cast(GroupMatchList, ["QC", "InjBl", "ISTD"]) class AnalysisIdentifiers(HasTraits): """Names used in ...
username: Username = Unicode(default_value=getpass.getuser(), read_only=True)
Given snippet: <|code_start|> fields: optional dict with column names as key and list of lcms filename metadata fields positions as value """ if fields is None: fields = { "full_filename": list(range(16)), "sample_treatment": [12...
write_utils.export_dataframe_die_on_diff(
Using the snippet: <|code_start|> _groups: GroupList = traitlets.List(allow_none=True, default_value=None, read_only=True) # pylint: disable=no-self-use,too-many-arguments,too-many-locals def __init__( self, project_directory, experiment, output_type, polarity, ...
self.set_trait("username", or_default(username, getpass.getuser()))
Based on the snippet: <|code_start|> plt.rcParams.update({'font.weight': 'bold'}) plt.rcParams['axes.linewidth'] = 2 # set the value globally for i,name in enumerate(names): plot_chromatogram(my_data[i], name, ax=ax[i]) f.savefig(file_name) plt.close(f) def plot_compounds_and_file...
file_names = ma_data.get_file_names(data)
Next line prediction: <|code_start|> def convert(ind, fname): """Helper function, converts a single file""" logger.info("Converting file number %d: %s", ind + 1, fname) # Get relevant information about the file. username = _file_name_to_username(fname, DEFAULT_USERNAME) info = patt.match(o...
run = LcmsRun(name=info['path'],
Given the following code snippet before the placeholder: <|code_start|> if info: info = info.groupdict() else: logger.error("Invalid path name: %s", fname) return dirname = os.path.dirname(fname) # Convert to HDF and store the entry in the database. try: hdf5...
store(run)
Continue the code snippet: <|code_start|> if start_time is not None and '-infinity' not in start_time: date_object = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') utc_timestamp = int(time.mktime(date_object.timetuple())) else: utc_timestamp = int(0) return utc_timestamp ...
runs = retrieve('lcmsrun', username='*', mzml_file=fname)
Based on the snippet: <|code_start|> move_file(fname, fail_path) try: os.remove(hdf5_file) except: pass def update_metatlas(directory): """ Converts all files to HDF in metatlas. Emails the user if there was any kind of error with converting a f...
send_mail('Metatlas Files are Inaccessible', username, body)
Based on the snippet: <|code_start|>""" Tests of RClone """ # pylint: disable=missing-function-docstring def has_rclone(): return os.system("rclone") == 256 def rclone_path(): result = subprocess.run(["which", "rclone"], stdout=subprocess.PIPE, check=True) return result.stdout.decode("utf-8").rstrip(...
rci = rclone.RClone("/bin/foobarz")
Given the following code snippet before the placeholder: <|code_start|> if lcmsruns is None: lcmsruns = get_lcmsrun_matrix() done_input_files = lcmsruns.loc[pd.notna(lcmsruns['%s_filename'%input_type]),'%s_filename'%input_type] done_output_files = lcmsruns.loc[pd.notna(lcmsruns['%s_filename'%output_...
temp['output_file'] = temp['input_file'].apply(lambda x: re.sub('\%s$'%EXTENSIONS[input_type],'%s'%EXTENSIONS[output_type],x))
Based on the snippet: <|code_start|>"""Jupyter notebook helper functions""" logger = logging.getLogger(__name__) def configure_environment(log_level: str) -> None: """ Sets environment variables and configures logging inputs: log_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' ...
activate_logging(console_level=log_level)
Predict the next line after this snippet: <|code_start|> def configure_notebook_display() -> None: """Configure output from Jupyter""" # set notebook to have minimal side margins display(HTML("<style>.container { width:100% !important; }</style>")) def setup(log_level: str, source_code_version_id: Option...
activate_module_logging("sqlalchemy.engine", console_level, console_format, file_level, filename)
Based on the snippet: <|code_start|> Sets environment variables and configures logging inputs: log_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' """ activate_logging(console_level=log_level) logger.debug("Running import and environment setup block of notebook.") logger.deb...
logger.info("Running on git commit: %s from %s", get_repo_hash(), get_commit_date())
Given snippet: <|code_start|> Sets environment variables and configures logging inputs: log_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' """ activate_logging(console_level=log_level) logger.debug("Running import and environment setup block of notebook.") logger.debug("Con...
logger.info("Running on git commit: %s from %s", get_repo_hash(), get_commit_date())
Based on the snippet: <|code_start|> """ Sets environment variables and configures logging inputs: log_level: one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL' """ activate_logging(console_level=log_level) logger.debug("Running import and environment setup block of notebook.") lo...
set_git_head(source_code_version_id)
Continue the code snippet: <|code_start|> r = my_session.get("https://newt.nersc.gov/newt/queue/%s/?user=%s"%(computer,usr)) my_jobs = r.json() # print my_jobs if do_print: print("You have",len(my_jobs),"jobs running or in the queue to run") for i,j in enumerate(my_jobs): prin...
finfo = h5q.get_info(myfile)
Given the following code snippet before the placeholder: <|code_start|>""" tests of parallel processing utilities """ # pylint: disable=missing-function-docstring def times_two(num): return num * 2 def error_on_zero(num): if num == 0: raise ValueError("Zero is illegal here!") return num def t...
assert sorted(parallel.parallel_process(times_two, data, len(data))) == [0, 2, 4]
Given snippet: <|code_start|># pylint: disable=missing-function-docstring, missing-module-docstring, line-too-long INCHI = "InChI=1S/C10H13N5O3/c11-9-8-10(13-3-12-9)15(4-14-8)7-1-5(17)6(2-16)18-7/h3-7,16-17H,1-2H2,(H2,11,12,13)/t5-,6+,7+/m0/s1" INCHI_KEY = "OLXZPDWKRNYJJZ-RRKCRQDMSA-N" SMILES = "C1[C@@H]([C@@H](CO)...
pre = cheminfo.get_precursor_mz(original_parent, name)
Predict the next line for this snippet: <|code_start|>"""Utility functions for working with metatlas data structures""" logger = logging.getLogger(__name__) AtlasName = NewType("AtlasName", str) Username = NewType("Username", str) <|code_end|> with the help of current file imports: import logging from typing i...
def get_atlas(name: AtlasName, username: Username) -> metob.Atlas:
Using the snippet: <|code_start|>@functools.lru_cache def inchi_or_smiles_to_molecule(molecule_id: str) -> Chem.rdchem.Mol: """Convert Inchi or smiles to rdkit Mol""" out = Chem.inchi.MolFromInchi(molecule_id) or Chem.MolFromSmiles(molecule_id) if out is None: raise ValueError(f"'{molecule_id}' is n...
desalted, _ = cleaning.desalt(mol)
Given the code snippet: <|code_start|>"""Plot set of EIC plots for a compound. One sample per sub-plot""" # pylint: disable=invalid-name,too-many-arguments,too-few-public-methods logger = logging.getLogger(__name__) MetatlasDataset = List[List[Any]] # avoiding a circular import class CompoundEic(plot_set.Plot)...
rt_ref: metob.RtReference = compound["identification"].rt_references[0]
Based on the snippet: <|code_start|>"""Plot set of TIC plots. One sample per sub-plot""" # pylint: disable=invalid-name,too-many-arguments,too-few-public-methods,too-many-locals logger = logging.getLogger(__name__) MetatlasDataset = List[List[Any]] # avoiding a circular import class Tic(plot_set.Plot): """...
tic_df = get_bpc(self.h5_file_name, dataset=dataset, integration="tic")
Predict the next line after this snippet: <|code_start|>"""Plot set of TIC plots. One sample per sub-plot""" # pylint: disable=invalid-name,too-many-arguments,too-few-public-methods,too-many-locals logger = logging.getLogger(__name__) MetatlasDataset = List[List[Any]] # avoiding a circular import class Tic(plo...
def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None:
Based on the snippet: <|code_start|> and not a key name, make it a tuple with the attribute name string as the first member, such as: ('attribute_name',). If you want to make it more explict to the reader, you can add a second member to the tuple, which will not be used, such as ('attribute_name', 'as attrib...
mzs = [extract(aci, ['mz_references', 0], metob.MzReference()) for aci in atlas.compound_identifications]
Given the following code snippet before the placeholder: <|code_start|> polarity = 1 else: polarity = 0 mz_theor = mz_ref.mz if mz_ref.mz_tolerance_units == 'ppm': #convert to ppm ppm_uncertainty = mz_ref.mz_tolerance else: ppm_uncertainty = mz_ref.mz_tolerance / mz_ref...
ms1_data = h5q.get_data(fid,
Given the following code snippet before the placeholder: <|code_start|> newstr = re.sub(r'\.', 'p', newstr) # 2 or more in regexp newstr = re.sub(r'[\[\]]', '', newstr) newstr = re.sub('[^A-Za-z0-9+-]+', '_', newstr) newstr = re.sub('i_[A-Za-z]+_i_', '', newstr) if newstr[0] in [...
write_utils.export_dataframe(metob.to_dataframe([myatlas]), atlas_path, "atlas metadata",
Given snippet: <|code_start|> d_1 = yield_ppm(data, 'ppm', threshold, tolerance, mz_t, rt_max) # Looking through MS2, precursor data = dataset[ms2] data_filter = (abs(data['precursor_MZ'] - mz_t) * 1e6) <= tolerance * mz_t filtered = data[data_filter] thresh = filtered[filtered.i >= thre...
dataset = ma_data.df_container_from_metatlas_file(hdf5_name)
Predict the next line for this snippet: <|code_start|>std_name = 'ABMBA' rt_max = -1 run_times: Dict[str, Any] = {} save_path = '/project/projectdirs/metatlas/projects/istd_logs/' def check_metatlas(): """ Checks for invalid runs. """ invalid_runs = find_invalid_runs(_override=True) # C...
send_mail('Metatlas Runs are Invalid', username, body)
Predict the next line after this snippet: <|code_start|>"""Test of notebook functions""" # pylint: disable=missing-function-docstring def test_create_notebook_with_parameters01(): orig_data = { "cells": [ { "metadata": {"tags": ["parameters"]}, "source": [ ...
notebook.create_notebook(
Given the following code snippet before the placeholder: <|code_start|> def __exit__(self, exc_type, exc_value, exc_tb): self.close() def limit_axes( self, x_min: Optional[float], x_max: Optional[float], y_min: Optional[float], y_max: Optional[float], ) -> Non...
write_utils.check_existing_file(file_name, overwrite)
Based on the snippet: <|code_start|>"""Set of plots""" # pylint: disable=invalid-name,too-many-arguments,too-few-public-methods logger = logging.getLogger(__name__) def restore_matplotlib_settings(func): """Stop function from permanently modifiying rcParams""" def wrapper(*args, **kwargs): orig...
def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None:
Continue the code snippet: <|code_start|> self.ax.annotate(l, xy, ha='right', va='center', size = 8./(num_rows+.25)) # Y-scale label self.y_scale_coordinates = np.matmul(tso_transform, self.__make_y_scale_coordinates(is_subplot) ...
write_utils.check_existing_file(self.file_name, self.overwrite)
Continue the code snippet: <|code_start|> readonly_files[username].add(dirname) continue # Get a lock on the mzml file to prevent interference. try: fid = open(fname, 'r') fcntl.flock(fid, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: ...
run = LcmsRun(name=info['path'], description=description,
Predict the next line for this snippet: <|code_start|> os.makedirs(dname) try: shutil.copy(fname, pasteur_path) except IOError as e: readonly_files[username].add(dirname) continue # Get a lock on the mzml file to prevent int...
runs = retrieve('lcmsrun', username='*', mzml_file=fname)