_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q40600
DataSet._manifest
train
def _manifest(self): """Return manifest content.""" if self._manifest_cache is None: self._manifest_cache = self._storage_broker.get_manifest() return self._manifest_cache
python
{ "resource": "" }
q40601
ProtoDataSet._identifiers
train
def _identifiers(self): """Return iterable of dataset item identifiers.""" for handle in self._storage_broker.iter_item_handles(): yield dtoolcore.utils.generate_identifier(handle)
python
{ "resource": "" }
q40602
ProtoDataSet.create
train
def create(self): """Create the required directory structure and admin metadata.""" self._storage_broker.create_structure() self._storage_broker.put_admin_metadata(self._admin_metadata)
python
{ "resource": "" }
q40603
ProtoDataSet._generate_overlays
train
def _generate_overlays(self): """Return dictionary of overlays generated from added item metadata.""" overlays = defaultdict(dict) for handle in self._storage_broker.iter_item_handles(): identifier = dtoolcore.utils.generate_identifier(handle) item_metadata = self._storag...
python
{ "resource": "" }
q40604
add_papyrus_handler
train
def add_papyrus_handler(self, route_name_prefix, base_url, handler): """ Add a Papyrus handler, i.e. a handler defining the MapFish HTTP interface. Example:: import papyrus config.include(papyrus) config.add_papyrus_handler( 'spots', '/spots', 'mypackage.handlers.SpotHa...
python
{ "resource": "" }
q40605
add_papyrus_routes
train
def add_papyrus_routes(self, route_name_prefix, base_url): """ A helper method that adds routes to view callables that, together, implement the MapFish HTTP interface. Example:: import papyrus config.include(papyrus) config.add_papyrus_routes('spots', '/spots') config.scan(...
python
{ "resource": "" }
q40606
peak_model
train
def peak_model(f): """ Given a function that models a peak, add scale and location arguments to For all functions, v is vertical offset, h is height x is horizontal offset (1st moment), w is width (2nd moment), s is skewness (3rd moment), e is excess (4th moment) """ @wraps(f) def wrapp...
python
{ "resource": "" }
q40607
_findNearest
train
def _findNearest(arr, value): """ Finds the value in arr that value is closest to """ arr = np.array(arr) # find nearest value in array idx = (abs(arr-value)).argmin() return arr[idx]
python
{ "resource": "" }
q40608
_createMagConversionDict
train
def _createMagConversionDict(): """ loads magnitude_conversion.dat which is table A% 1995ApJS..101..117K """ magnitude_conversion_filepath = resource_stream(__name__, 'data/magnitude_conversion.dat') raw_table = np.loadtxt(magnitude_conversion_filepath, '|S5') magDict = {} for row in raw_table:...
python
{ "resource": "" }
q40609
_BaseObject._getParentClass
train
def _getParentClass(self, startClass, parentClass): """ gets the parent class by calling successive parent classes with .parent until parentclass is matched. """ try: if not startClass: # reached system with no hits raise AttributeError except AttributeError:...
python
{ "resource": "" }
q40610
Star.d
train
def d(self): """ Note this should work from child parents as .d propergates, calculates using the star estimation method estimateDistance and estimateAbsoluteMagnitude """ # TODO this will only work from a star or below. good thing? d = self.parent.d if ed_params.estimate...
python
{ "resource": "" }
q40611
Star.getLimbdarkeningCoeff
train
def getLimbdarkeningCoeff(self, wavelength=1.22): # TODO replace with pylightcurve """ Looks up quadratic limb darkening parameter from the star based on T, logg and metalicity. :param wavelength: microns :type wavelength: float :return: limb darkening coefficients 1 and 2 """...
python
{ "resource": "" }
q40612
Planet.calcTemperature
train
def calcTemperature(self): """ Calculates the temperature using which uses equations.MeanPlanetTemp, albedo assumption and potentially equations.starTemperature. issues - you cant get the albedo assumption without temp but you need it to calculate the temp. """ try: ...
python
{ "resource": "" }
q40613
Planet.calcSMA
train
def calcSMA(self): """ Calculates the semi-major axis from Keplers Third Law """ try: return eq.KeplersThirdLaw(None, self.star.M, self.P).a except HierarchyError: return np.nan
python
{ "resource": "" }
q40614
Planet.calcSMAfromT
train
def calcSMAfromT(self, epsilon=0.7): """ Calculates the semi-major axis based on planet temperature """ return eq.MeanPlanetTemp(self.albedo(), self.star.T, self.star.R, epsilon, self.T).a
python
{ "resource": "" }
q40615
Planet.calcPeriod
train
def calcPeriod(self): """ calculates period using a and stellar mass """ return eq.KeplersThirdLaw(self.a, self.star.M).P
python
{ "resource": "" }
q40616
Parameters.addParam
train
def addParam(self, key, value, attrib=None): """ Checks the key dosnt already exist, adds alternate names to a seperate list Future - format input and add units - logging """ if key in self.rejectTags: return False # TODO Replace with exception ...
python
{ "resource": "" }
q40617
SpectralType.roundedSpecClass
train
def roundedSpecClass(self): """ Spectral class with rounded class number ie A8.5V is A9 """ try: classnumber = str(int(np.around(self.classNumber))) except TypeError: classnumber = str(self.classNumber) return self.classLetter + classnumber
python
{ "resource": "" }
q40618
SpectralType._parseSpecType
train
def _parseSpecType(self, classString): """ This class attempts to parse the spectral type. It should probably use more advanced matching use regex """ try: classString = str(classString) except UnicodeEncodeError: # This is for the benefit of 1RXS1609 which curre...
python
{ "resource": "" }
q40619
Magnitude._convert_to_from
train
def _convert_to_from(self, to_mag, from_mag, fromVMag=None): """ Converts from or to V mag using the conversion tables :param to_mag: uppercase magnitude letter i.e. 'V' or 'K' :param from_mag: uppercase magnitude letter i.e. 'V' or 'K' :param fromVMag: MagV if from_mag is 'V' ...
python
{ "resource": "" }
q40620
AgilentMWD2._get_str
train
def _get_str(self, f, off): """ Convenience function to quickly pull out strings. """ f.seek(off) return f.read(2 * struct.unpack('>B', f.read(1))[0]).decode('utf-16')
python
{ "resource": "" }
q40621
delta13c_constants
train
def delta13c_constants(): """ Constants for calculating delta13C values from ratios. From website of Verkouteren & Lee 2001 Anal. Chem. """ # possible values for constants (from NIST) cst = OrderedDict() cst['Craig'] = {'S13': 0.0112372, 'S18': 0.002079, 'K': 0.008333, 'A...
python
{ "resource": "" }
q40622
delta13c_craig
train
def delta13c_craig(r45sam, r46sam, d13cstd, r45std, r46std, ks='Craig', d18ostd=23.5): """ Algorithm from Craig 1957. From the original Craig paper, we can set up a pair of equations and solve for d13C and d18O simultaneously: d45 * r45 = r13 * d13 + 0.5 * ...
python
{ "resource": "" }
q40623
delta13c_santrock
train
def delta13c_santrock(r45sam, r46sam, d13cstd, r45std, r46std, ks='Santrock', d18ostd=23.5): """ Given the measured isotope signals of a sample and a standard and the delta-13C of that standard, calculate the delta-13C of the sample. Algorithm from Santrock, Studley & Hayes 19...
python
{ "resource": "" }
q40624
walk
train
def walk(zk, path='/'): """Yields all paths under `path`.""" children = zk.get_children(path) yield path for child in children: if path == '/': subpath = "/%s" % child else: subpath = "%s/%s" % (path, child) for child in walk(zk, subpath): yie...
python
{ "resource": "" }
q40625
pretty_print_head
train
def pretty_print_head(dict_, count=10): #TODO only format and rename to pretty_head ''' Pretty print some items of a dict. For an unordered dict, ``count`` arbitrary items will be printed. Parameters ---------- dict_ : ~typing.Dict Dict to print from. count : int Number of ...
python
{ "resource": "" }
q40626
invert
train
def invert(dict_): #TODO return a MultiDict right away ''' Invert dict by swapping each value with its key. Parameters ---------- dict_ : ~typing.Dict[~typing.Hashable, ~typing.Hashable] Dict to invert. Returns ------- ~typing.Dict[~typing.Hashable, ~typing.Set[~typing.Hashable...
python
{ "resource": "" }
q40627
RequestPaginator.delete
train
def delete(self, json=None): """Send a DELETE request and return the JSON decoded result. Args: json (dict, optional): Object to encode and send in request. Returns: mixed: JSON decoded response data. """ return self._call('delete', url=self.endpoint, js...
python
{ "resource": "" }
q40628
RequestPaginator.put
train
def put(self, json=None): """Send a PUT request and return the JSON decoded result. Args: json (dict, optional): Object to encode and send in request. Returns: mixed: JSON decoded response data. """ return self._call('put', url=self.endpoint, json=json)
python
{ "resource": "" }
q40629
RequestPaginator._call
train
def _call(self, method, *args, **kwargs): """Call the remote service and return the response data.""" assert self.session if not kwargs.get('verify'): kwargs['verify'] = self.SSL_VERIFY response = self.session.request(method, *args, **kwargs) response_json = respon...
python
{ "resource": "" }
q40630
KeyedPRF.eval
train
def eval(self, x): """This method returns the evaluation of the function with input x :param x: this is the input as a Long """ aes = AES.new(self.key, AES.MODE_CFB, "\0" * AES.block_size) while True: nonce = 0 data = KeyedPRF.pad(SHA256.new(str(x + nonce...
python
{ "resource": "" }
q40631
merge_by_overlap
train
def merge_by_overlap(sets): ''' Of a list of sets, merge those that overlap, in place. The result isn't necessarily a subsequence of the original ``sets``. Parameters ---------- sets : ~typing.Sequence[~typing.Set[~typing.Any]] Sets of which to merge those that overlap. Empty sets are ...
python
{ "resource": "" }
q40632
AuthProxy.auth_proxy
train
def auth_proxy(self, method): """Authentication proxy for API requests. This is required because the API objects are naive of ``HelpScout``, so they would otherwise be unauthenticated. Args: method (callable): A method call that should be authenticated. It shou...
python
{ "resource": "" }
q40633
Users.find_in_mailbox
train
def find_in_mailbox(cls, session, mailbox_or_id): """Get the users that are associated to a Mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox_or_id (MailboxRef or int): Mailbox of the ID of the mailbox to get the folders for. ...
python
{ "resource": "" }
q40634
_hash_the_file
train
def _hash_the_file(hasher, filename): """Helper function for creating hash functions. See implementation of :func:`dtoolcore.filehasher.shasum` for more usage details. """ BUF_SIZE = 65536 with open(filename, 'rb') as f: buf = f.read(BUF_SIZE) while len(buf) > 0: has...
python
{ "resource": "" }
q40635
enable_precompute
train
def enable_precompute(panel): """Schedule a precompute task for `panel`""" use_metis = panel['data_source']['source_type'] == 'querybuilder' if use_metis: query = panel['data_source']['query'] else: query = "u'''%s'''" % panel['data_source']['code'] precompute = panel['data_source']['precompute'] ti...
python
{ "resource": "" }
q40636
disable_precompute
train
def disable_precompute(panel): """Cancel precomputation for `panel`""" task_id = panel['data_source']['precompute']['task_id'] result = scheduler_client.cancel(task_id) if result['status'] != 'success': raise RuntimeError(result.get('reason'))
python
{ "resource": "" }
q40637
QueryCompute._get_timeframe_bounds
train
def _get_timeframe_bounds(self, timeframe, bucket_width): """ Get a `bucket_width` aligned `start_time` and `end_time` from a `timeframe` dict """ if bucket_width: bucket_width_seconds = bucket_width bucket_width = epoch_time_to_kronos_time(bucket_width) # TODO(derek): Potential opt...
python
{ "resource": "" }
q40638
QueryCompute.compute
train
def compute(self, use_cache=True): """Call a user defined query and return events with optional help from the cache. :param use_cache: Specifies whether the cache should be used when possible """ if use_cache: if not self._bucket_width: raise ValueError('QueryCompute must be initializ...
python
{ "resource": "" }
q40639
QueryCompute.cache
train
def cache(self): """Call a user defined query and cache the results""" if not self._bucket_width or self._untrusted_time is None: raise ValueError('QueryCompute must be initialized with a bucket_width ' 'and an untrusted_time in order to write to the cache.') now = datetime.dat...
python
{ "resource": "" }
q40640
Customers.list
train
def list(cls, session, first_name=None, last_name=None, email=None, modified_since=None): """List the customers. Customers can be filtered on any combination of first name, last name, email, and modifiedSince. Args: session (requests.sessions.Session): Authenti...
python
{ "resource": "" }
q40641
Customers.search
train
def search(cls, session, queries): """Search for a customer given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply...
python
{ "resource": "" }
q40642
create_token
train
def create_token(key, payload): """Auth token generator payload should be a json encodable data structure """ token = hmac.new(key) token.update(json.dumps(payload)) return token.hexdigest()
python
{ "resource": "" }
q40643
get_app
train
def get_app(settings_file=None): """Get scheduler app singleton The app configuration is performed when the function is run for the first time. Because the scheduler is a threaded enviroment, it is important that this function be thread-safe. The scheduler instance is not created until the `commands/run...
python
{ "resource": "" }
q40644
Conversations.create
train
def create(cls, session, record, imported=False, auto_reply=False): """Create a conversation. Please note that conversation cannot be created with more than 100 threads, if attempted the API will respond with HTTP 412. Args: session (requests.sessions.Session): Authenticate...
python
{ "resource": "" }
q40645
Conversations.create_attachment
train
def create_attachment(cls, session, attachment): """Create an attachment. An attachment must be sent to the API before it can be used in a thread. Use this method to create the attachment, then use the resulting hash when creating a thread. Note that HelpScout only supports att...
python
{ "resource": "" }
q40646
Conversations.create_thread
train
def create_thread(cls, session, conversation, thread, imported=False): """Create a conversation thread. Please note that threads cannot be added to conversations with 100 threads (or more), if attempted the API will respond with HTTP 412. Args: conversation (helpscout.model...
python
{ "resource": "" }
q40647
Conversations.delete_attachment
train
def delete_attachment(cls, session, attachment): """Delete an attachment. Args: session (requests.sessions.Session): Authenticated session. attachment (helpscout.models.Attachment): The attachment to be deleted. Returns: NoneType: Nothing. ...
python
{ "resource": "" }
q40648
Conversations.find_customer
train
def find_customer(cls, session, mailbox, customer): """Return conversations for a specific customer in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to search. customer (helpscout.models.Custo...
python
{ "resource": "" }
q40649
Conversations.find_user
train
def find_user(cls, session, mailbox, user): """Return conversations for a specific user in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to search. user (helpscout.models.User): User to search...
python
{ "resource": "" }
q40650
Conversations.get_attachment_data
train
def get_attachment_data(cls, session, attachment_id): """Return a specific attachment's data. Args: session (requests.sessions.Session): Authenticated session. attachment_id (int): The ID of the attachment from which to get data. Returns: hel...
python
{ "resource": "" }
q40651
Conversations.list
train
def list(cls, session, mailbox): """Return conversations in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to list. Returns: RequestPaginator(output_type=helpscout.models.Conversation)...
python
{ "resource": "" }
q40652
Conversations.list_folder
train
def list_folder(cls, session, mailbox, folder): """Return conversations in a specific folder of a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox that folder is in. folder (helpscout.models.Folder...
python
{ "resource": "" }
q40653
Conversations.search
train
def search(cls, session, queries): """Search for a conversation given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will si...
python
{ "resource": "" }
q40654
Conversations.update_thread
train
def update_thread(cls, session, conversation, thread): """Update a thread. Args: session (requests.sessions.Session): Authenticated session. conversation (helpscout.models.Conversation): The conversation that the thread belongs to. thread (helpscout.m...
python
{ "resource": "" }
q40655
set_level
train
def set_level(logger, level): ''' Temporarily change log level of logger. Parameters ---------- logger : str or ~logging.Logger Logger name or logger whose log level to change. level : int Log level to set. Examples -------- >>> with set_level('sqlalchemy.engine', l...
python
{ "resource": "" }
q40656
configure
train
def configure(log_file): ''' Configure root logger to log INFO to stderr and DEBUG to log file. The log file is appended to. Stderr uses a terse format, while the log file uses a verbose unambiguous format. Root level is set to INFO. Parameters ---------- log_file : ~pathlib.Path ...
python
{ "resource": "" }
q40657
MnemonicsDataReader.get_pandasframe
train
def get_pandasframe(self): """The method loads data from dataset""" if self.dataset: self._load_dimensions() return self._get_pandasframe_one_dataset() return self._get_pandasframe_across_datasets()
python
{ "resource": "" }
q40658
KnoemaSeries.add_value
train
def add_value(self, value, index_point): """The function is addeing new value to provied index. If index does not exist""" if index_point not in self.index: self.values.append(value) self.index.append(index_point)
python
{ "resource": "" }
q40659
KnoemaSeries.get_pandas_series
train
def get_pandas_series(self): """The function creates pandas series based on index and values""" return pandas.Series(self.values, self.index, name=self.name)
python
{ "resource": "" }
q40660
TemporaryDirectory
train
def TemporaryDirectory(suffix=None, prefix=None, dir=None, on_error='ignore'): # @ReservedAssignment ''' An extension to `tempfile.TemporaryDirectory`. Unlike with `python:tempfile`, a :py:class:`~pathlib.Path` is yielded on ``__enter__``, not a `str`. Parameters ---------- suffix : str ...
python
{ "resource": "" }
q40661
hash
train
def hash(path, hash_function=hashlib.sha512): # @ReservedAssignment ''' Hash file or directory. Parameters ---------- path : ~pathlib.Path File or directory to hash. hash_function : ~typing.Callable[[], hash object] Function which creates a hashlib hash object when called. Defa...
python
{ "resource": "" }
q40662
diff_identifiers
train
def diff_identifiers(a, b): """Return list of tuples where identifiers in datasets differ. Tuple structure: (identifier, present in a, present in b) :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples where identifiers in datasets dif...
python
{ "resource": "" }
q40663
diff_sizes
train
def diff_sizes(a, b, progressbar=None): """Return list of tuples where sizes differ. Tuple structure: (identifier, size in a, size in b) Assumes list of identifiers in a and b are identical. :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: l...
python
{ "resource": "" }
q40664
diff_content
train
def diff_content(a, reference, progressbar=None): """Return list of tuples where content differ. Tuple structure: (identifier, hash in a, hash in reference) Assumes list of identifiers in a and b are identical. Storage broker of reference used to generate hash for files in a. :param a: first...
python
{ "resource": "" }
q40665
cli
train
def cli(): """Parse options from the command line""" parser = argparse.ArgumentParser(prog="sphinx-serve", formatter_class=argparse.ArgumentDefaultsHelpFormatter, conflict_handler="resolve", descriptio...
python
{ "resource": "" }
q40666
find_build_dir
train
def find_build_dir(path, build="_build"): """try to guess the build folder's location""" path = os.path.abspath(os.path.expanduser(path)) contents = os.listdir(path) filtered_contents = [directory for directory in contents if os.path.isdir(os.path.join(path, directory))] ...
python
{ "resource": "" }
q40667
flip_uuid_parts
train
def flip_uuid_parts(uuid): """ Flips high and low segments of the timestamp portion of a UUID string. This enables correct lexicographic sorting. Because it is a simple flip, this function works in both directions. """ flipped_uuid = uuid.split('-') flipped_uuid[0], flipped_uuid[2] = flipped_uuid[2], flip...
python
{ "resource": "" }
q40668
genExampleStar
train
def genExampleStar(binaryLetter='', heirarchy=True): """ generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a system and link everything up """ starPar = StarParameters() starPar.addParam('age', '7.6') starPar.addParam('magB', '9.8')...
python
{ "resource": "" }
q40669
config_list
train
def config_list(backend): """ Print the current configuration """ click.secho('Print Configuration', fg='green') print str(backend.dki.get_config())
python
{ "resource": "" }
q40670
recipe_status
train
def recipe_status(backend): """ Compare local recipe to remote recipe for the current recipe. """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You are not in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_...
python
{ "resource": "" }
q40671
recipe_conflicts
train
def recipe_conflicts(backend): """ See if there are any unresolved conflicts for this recipe. """ recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickException('You must be in a Recipe folder.') recipe_name = DKRecipeDisk.find_recipe_name() click....
python
{ "resource": "" }
q40672
kitchen_list
train
def kitchen_list(backend): """ List all Kitchens """ click.echo(click.style('%s - Getting the list of kitchens' % get_datetime(), fg='green')) check_and_print(DKCloudCommandRunner.list_kitchen(backend.dki))
python
{ "resource": "" }
q40673
kitchen_get
train
def kitchen_get(backend, kitchen_name, recipe): """ Get an existing Kitchen """ found_kitchen = DKKitchenDisk.find_kitchen_name() if found_kitchen is not None and len(found_kitchen) > 0: raise click.ClickException("You cannot get a kitchen into an existing kitchen directory structure.") ...
python
{ "resource": "" }
q40674
kitchen_create
train
def kitchen_create(backend, parent, kitchen): """ Create a new kitchen """ click.secho('%s - Creating kitchen %s from parent kitchen %s' % (get_datetime(), kitchen, parent), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.create_ki...
python
{ "resource": "" }
q40675
kitchen_delete
train
def kitchen_delete(backend, kitchen): """ Provide the name of the kitchen to delete """ click.secho('%s - Deleting kitchen %s' % (get_datetime(), kitchen), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.delete_kitchen(backend.dki,...
python
{ "resource": "" }
q40676
kitchen_config
train
def kitchen_config(backend, kitchen, add, get, unset, listall): """ Get and Set Kitchen variable overrides """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) check_and_print(DKCloudCommandRunner.config_kitchen(bac...
python
{ "resource": "" }
q40677
kitchen_merge
train
def kitchen_merge(backend, source_kitchen, target_kitchen): """ Merge two Kitchens """ click.secho('%s - Merging Kitchen %s into Kitchen %s' % (get_datetime(), source_kitchen, target_kitchen), fg='green') check_and_print(DKCloudCommandRunner.merge_kitchens_improved(backend.dki, source_kitchen, targe...
python
{ "resource": "" }
q40678
recipe_list
train
def recipe_list(backend, kitchen): """ List the Recipes in a Kitchen """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho("%s - Getting the list of Recipes for Kitchen '%s'" % (get_datetime(), use_kitche...
python
{ "resource": "" }
q40679
recipe_create
train
def recipe_create(backend, kitchen, name): """ Create a new Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho("%s - Creating Recipe %s for Kitchen '%s'" % (get_datetime(), name, use_kitchen), f...
python
{ "resource": "" }
q40680
recipe_get
train
def recipe_get(backend, recipe): """ Get the latest files for this recipe. """ recipe_root_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_root_dir is None: if recipe is None: raise click.ClickException("\nPlease change to a recipe folder or provide a recipe name arguement") ...
python
{ "resource": "" }
q40681
file_add
train
def file_add(backend, kitchen, recipe, message, filepath): """ Add a newly created file to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_n...
python
{ "resource": "" }
q40682
file_update_all
train
def file_update_all(backend, message, dryrun): """ Update all of the changed files for this Recipe """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You must be in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if re...
python
{ "resource": "" }
q40683
file_resolve
train
def file_resolve(backend, filepath): """ Mark a conflicted file as resolved, so that a merge can be completed """ recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder.') click.secho("%s - Resolving conflicts" % get_dateti...
python
{ "resource": "" }
q40684
active_serving_watcher
train
def active_serving_watcher(backend, kitchen, period): """ Watches all cooking Recipes in a Kitchen Provide the kitchen name as an argument or be in a Kitchen folder. """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_s...
python
{ "resource": "" }
q40685
order_delete
train
def order_delete(backend, kitchen, order_id): """ Delete one order or all orders in a kitchen """ use_kitchen = Backend.get_kitchen_name_soft(kitchen) print use_kitchen if use_kitchen is None and order_id is None: raise click.ClickException('You must specify either a kitchen or an order_...
python
{ "resource": "" }
q40686
order_stop
train
def order_stop(backend, order_id): """ Stop an order - Turn off the serving generation ability of an order. Stop any running jobs. Keep all state around. """ if order_id is None: raise click.ClickException('invalid order id %s' % order_id) click.secho('%s - Stop order id %s' % (get_datetim...
python
{ "resource": "" }
q40687
order_stop
train
def order_stop(backend, order_run_id): """ Stop the run of an order - Stop the running order and keep all state around. """ if order_run_id is None: raise click.ClickException('invalid order id %s' % order_run_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_run_id), fg='gre...
python
{ "resource": "" }
q40688
orderrun_detail
train
def orderrun_detail(backend, kitchen, summary, nodestatus, runstatus, log, timing, test, all_things, order_id, order_run_id, disp_order_id, disp_order_run_id): """ Display information about an Order-Run """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitc...
python
{ "resource": "" }
q40689
delete_orderrun
train
def delete_orderrun(backend, orderrun_id): """ Delete the orderrun specified by the argument. """ click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green') check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip()))
python
{ "resource": "" }
q40690
secret_list
train
def secret_list(backend,path): """ List all Secrets """ click.echo(click.style('%s - Getting the list of secrets' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_list(backend.dki,path))
python
{ "resource": "" }
q40691
secret_write
train
def secret_write(backend,entry): """ Write a secret """ path,value=entry.split('=') if value.startswith('@'): with open(value[1:]) as vfile: value = vfile.read() click.echo(click.style('%s - Writing secret' % get_datetime(), fg='green')) check_and_print( DKCloud...
python
{ "resource": "" }
q40692
Data.readlines
train
def readlines(self, *args, **kwargs): """Return list of all lines. Always returns list of unicode.""" return list(iter(partial(self.readline, *args, **kwargs), u''))
python
{ "resource": "" }
q40693
Data.save_to
train
def save_to(self, file): """Save data to file. Will copy by either writing out the data or using :func:`shutil.copyfileobj`. :param file: A file-like object (with a ``write`` method) or a filename.""" dest = file if hasattr(dest, 'write'): ...
python
{ "resource": "" }
q40694
InficonHapsite._ions
train
def _ions(self, f): """ This is a generator that returns the mzs being measured during each time segment, one segment at a time. """ outside_pos = f.tell() doff = find_offset(f, 4 * b'\xff' + 'HapsSearch'.encode('ascii')) # actual end of prev section is 34 bytes b...
python
{ "resource": "" }
q40695
Daemon._emit_message
train
def _emit_message(cls, message): """Print a message to STDOUT.""" sys.stdout.write(message) sys.stdout.flush()
python
{ "resource": "" }
q40696
Daemon._emit_error
train
def _emit_error(cls, message): """Print an error message to STDERR.""" sys.stderr.write('ERROR: {message}\n'.format(message=message)) sys.stderr.flush()
python
{ "resource": "" }
q40697
Daemon._emit_warning
train
def _emit_warning(cls, message): """Print an warning message to STDERR.""" sys.stderr.write('WARNING: {message}\n'.format(message=message)) sys.stderr.flush()
python
{ "resource": "" }
q40698
Daemon._setup_piddir
train
def _setup_piddir(self): """Create the directory for the PID file if necessary.""" if self.pidfile is None: return piddir = os.path.dirname(self.pidfile) if not os.path.isdir(piddir): # Create the directory with sensible mode and ownership os.makedirs(...
python
{ "resource": "" }
q40699
Daemon._read_pidfile
train
def _read_pidfile(self): """Read the PID file and check to make sure it's not stale.""" if self.pidfile is None: return None if not os.path.isfile(self.pidfile): return None # Read the PID file with open(self.pidfile, 'r') as fp: try: ...
python
{ "resource": "" }