code stringlengths 1 18.2k |
|---|
def _identifiers(self): """Return iterable of dataset item identifiers.""" for handle in self._storage_broker.iter_item_handles(): yield dtoolcore.utils.generate_identifier(handle) |
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) |
def add_item_metadata(self, handle, key, value): """ Add metadata to a specific item in the :class:`dtoolcore.ProtoDataSet`. :param handle: handle representing the relative path of the item in the :class:`dtoolcore.ProtoDataSet` :param key: metadata key :param value: metadata value """ self._storage_broker.add_item_met... |
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._storage_broker.get_item_metadata(handle) for k, v in i... |
def freeze(self, progressbar=None): """ Convert :class:`dtoolcore.ProtoDataSet` to :class:`dtoolcore.DataSet`. """ # Call the storage broker pre_freeze hook. self._storage_broker.pre_freeze_hook() if progressbar: progressbar.label = "Freezing dataset" # Generate and persist the manifest. manifest = self.generate_manife... |
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.SpotHandler') Arguments: ``route_name_prefix`` The prefi... |
handler, action='delete', request_method='DELETE') |
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() Arguments: ``route_name_prefix' The prefix u... |
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 wrapped_f(t, **kw): # load kwargs with... |
inspect.getargspec(f) fkw = dict([(arg, kw[arg]) for arg in anames if arg in kw]) # some functions use location or width parameters explicitly # if not, adjust the timeseries accordingly ta = t if 'x' not in anames: ta = ta - kw['x'] if 'w' not in anames: ta = ta / kw['w'] # finally call the function mod = f(ta, **fkw)... |
def download_matches(match_downloaded_callback, on_exit_callback, conf, synchronize_callback= True): """ :param match_downloaded_callback: function when a match is downloaded function is called with the match and the tier (league) of the lowest player in the match as parameters :param on_exit_callback: function when th... |
checkpoint(players_to_analyze, analyzed_players, matches_to_download, downloaded_matches): logger.info("Reached the checkpoint." .format(datetime.datetime.now().strftime("%m-%d %H:%M:%S"), len(downloaded_matches))) if on_exit_callback: on_exit_callback(players_to_analyze, analyzed_players, matches_to_download, download... |
player downloader thread. Threads: " + str(len(player_downloader_threads))) else: with logger_lock: logger.debug("Tried removing a player download thread, but there is only one left") logger.info("Starting fetching..") # Start one player downloader thread create_thread() for _ in range(matches_download_threads): match_... |
in match_downloader_threads) with pta_lock: players_in_queue = len(players_to_analyze) total_players = sum(th.total_downloads for th in player_downloader_threads) with logger_lock: logger.info("Players in queue: {}. Downloaded players: {}. Matches in queue: {}. Downloaded matches: {}" .format(players_in_queue, total_pl... |
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] |
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: if sys.hexversion >= 0x0... |
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: # i.e calling binary on an object without one raise Hierarch... |
def T(self): """ Looks for the temperature in the catalogue, if absent it calculates it using calcTemperature() :return: planet temperature """ paramTemp = self.getParam('temperature') if not paramTemp is np.nan: return paramTemp elif ed_params.estimateMissingValues: self.flags.addFlag('Calculated Temperature') return ... |
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.estimateMissingValues: if d is np.nan: d = self.estimate... |
def _get_or_convert_magnitude(self, mag_letter): """ Takes input of the magnitude letter and ouputs the magnitude fetched from the catalogue or a converted value :return: """ allowed_mags = "UBVJIHKLMN" catalogue_mags = 'BVIJHK' if mag_letter not in allowed_mags or not len(mag_letter) == 1: raise ValueError("Magnitude ... |
mag_val |
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 """ # TODO check this returns correct value - ... |
44000., 45000., 46000., 47000., 48000., 49000., 50000.] lggind = [0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5.] mhind = [-5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1., -0.5, -0.3, -0.2, -0.1, 0., 0.1, 0.2, 0.3, 0.5, 1.] # Choose the values in the table nearest our parameters tempselect = _findNearest(tempind, floa... |
be found') # TODO replace with better exception waveind = [0.365, 0.445, 0.551, 0.658, 0.806, 1.22, 1.63, 2.19, 3.45] # Wavelengths available in table # Interpolates the value at wavelength from values in the table (waveind) u1AtWavelength = np.interp(wavelength, waveind, u1array, left=0, right=0) u2AtWavelength = np.i... |
def isTransiting(self): """ Checks the the istransiting tag to see if the planet transits. Note that this only works as of catalogue version ee12343381ae4106fd2db908e25ffc537a2ee98c (11th March 2014) where the istransiting tag was implemented """ try: isTransiting = self.params['istransiting'] except KeyError: return F... |
def calcTransitDuration(self, circular=False): """ Estimation of the primary transit time assuming a circular orbit (see :py:func:`equations.transitDuration`) """ try: if circular: return eq.transitDurationCircular(self.P, self.star.R, self.R, self.a, self.i) else: return eq.TransitDuration(self.P, self.a, self.R, self... |
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: return eq.MeanPlanetTemp(self.albedo, self.star.T, se... |
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 |
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 |
def calcPeriod(self): """ calculates period using a and stellar mass """ return eq.KeplersThirdLaw(self.a, self.star.M).P |
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 # Temporary code to handle the seperation tag than can occur several times ... |
or popular name use this one, an option should be made to use either if attrib['type'] == 'pri': # first names or popular names. oldname = self.params['name'] self.params['altnames'].append(oldname) self.params['name'] = value else: self.params['altnames'].append(value) except (KeyError, TypeError): # KeyError = no typ... |
except KeyError: return False if key == 'rightascension': value = _ra_string_to_unit(value) elif key == 'declination': value = _dec_string_to_unit(value) elif key in self._defaultUnits: try: value = float(value) * self._defaultUnits[key] except: print('caught an error with {0} - {1}'.format(key, value)) self.params[key... |
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 |
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 currently has the spectral type K7\pm 1V # TODO add unicode su... |
chars for spectral types stellarClass = classString[:3] if stellarClass in _possSpectralClasses: self.classLetter = stellarClass elif stellarClass[:2] in _possSpectralClasses: # needed because A5V wouldnt match before self.classLetter = stellarClass[:2] elif stellarClass[0] in _possSpectralClasses: self.classLetter = s... |
Now check for a decimal and handle those cases if typeString[0] == '.': # handle decimal cases, we check each number in turn, add them as strings and then convert to float and add # to original number decimalNumbers = '.' for number in typeString[1:]: try: if int(number) in possNumbers: decimalNumbers += number else: p... |
of uniqueness) Lcase = typeString[:len(possL)] # match from front with length to minimise matching say IV in '<3 CIV' if possL == Lcase: self.lumType = possL return True if not self.classNumber == '': return True else: # if there no number asumme we have a name ie 'Catac. var.' self.classLetter = '' self.classNumber = ... |
def convert(self, to_mag, from_mag=None): """ Converts magnitudes using UBVRIJHKLMNQ photometry in Taurus-Auriga (Kenyon+ 1995) ReadMe+ftp1995ApJS..101..117K Colors for main-sequence stars If from_mag isn't specified the program will cycle through provided magnitudes and choose one. Note that all magnitudes are first c... |
need to convert return self.magV else: return self._convert_to_from(to_mag, 'V', self.magV) else: # Otherwise lets try all other magnitudes in turn order = "UBJHKLMN" # V is the intermediate step from the others, done by default if possible for mag_letter in order: try: magV = self._convert_to_from('V', mag_letter) if ... |
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' :return: estimated magnitude for to_mag fr... |
for that spectral type') if math.isnan(offset): raise ValueError('No data available to convert those magnitudes for that spectral type') else: from_mag_val = self.__dict__['mag'+from_mag] # safer than eval if isNanOrNone(from_mag_val): # logger.debug('2 '+from_mag) raise ValueError('You cannot convert from a magnitude ... |
data available to convert those magnitudes for that spectral type') else: return fromVMag + (offset*sign*-1) # -1 as we are now converting the other way else: raise ValueError('Can only convert from and to V magnitude. Use .convert() instead') |
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') |
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': 0.5} cst['IAEA'] = {'S13': 0.0112372, 'S18': ... |
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 * r17 * d18 d46 = r13 * ((r17**2 + r17 - r18) / a) * d13 + 1 - 0.... |
= 2 * (k['K'] * k['S18'] ** k['A']) a = (r18 + r13 * r17) * (1. + r13 + r17) # the coefficients for the calculations eqn_mat = np.array([[r13, 0.5 * r17], [r13 * ((r17 ** 2 + r17 - r18) / a), 1 - 0.5 * r17 * ((r13 ** 2 + r13 - r18) / a)]]) # precalculate the d45 and d46 of the standard versus PDB r45d45std = (eqn_mat[0... |
r17 + 0.001 * r45d45std) + r45d45std d46 = 1000. * (r46sam / r46std - 1.) * (1. + 0.001 * d46std) + d46std # solve the system of equations x = np.linalg.solve(eqn_mat, np.array([r45d45, d46])) return x[0] |
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 1985 Anal. Chem. """ k = delta13c_constants()... |
(r45sam / r45std) * c45 r46 = (r46sam / r46std) * c46 def rf(r18): return -3 * c17(r18) ** 2 + 2 * r45 * c17(r18) + 2 * r18 - r46 # r18 = scipy.optimize.root(rf, r18std).x[0] # use with scipy 0.11.0 r18 = fsolve(rf, r18std)[0] r13 = r45 - 2 * c17(r18) return 1000 * (r13 / rcpdb - 1) |
def resource_copy(package_or_requirement, resource_name, destination): ''' Copy file/dir resource to destination. Parameters ---------- package_or_requirement : str resource_name : str destination : ~pathlib.Path Path to copy to, it must not exist. ''' args = package_or_requirement, resource_name if resource_isdir(*arg... |
def simple_peak_find(s, init_slope=500, start_slope=500, end_slope=200, min_peak_height=50, max_peak_width=1.5): """ Given a Series, return a list of tuples indicating when peaks start and stop and what their baseline is. [(t_start, t_end, hints) ...] """ point_gap = 10 def slid_win(itr, size=2): """Returns a sliding w... |
a gap of up to 10 points in them peak_sts = [init_slopes[0]] peak_sts += [j for i, j in slid_win(init_slopes, 2) if j - i > 10] peak_sts.sort() en_slopes = np.arange(len(dxdt))[dxdt < -end_slope] if len(en_slopes) == 0: return [] # filter out any lone points farther than 10 away from their neighbors en_slopes = [en_slo... |
i) for i in peak_ens if i in avals]) peak_list = [] pk2 = 0 for pk in peak_sts: # don't allow overlapping peaks if pk < pk2: continue # track backwards to find the true start while dxdt[pk] > start_slope and pk > 0: pk -= 1 # now find where the peak ends dist_to_end = np.array(peak_ens) - pk pos_end = pk + dist_to_end[... |
max_peak_width).argmin() break else: break else: # if no end point is found, the end point # is the end of the timeseries pk2 = len(t) - 1 if pk == pk2: continue pk_hgt = max(y[pk:pk2]) - min(y[pk:pk2]) if pk_hgt < min_peak_height: continue peak_list.append({'t0': t[pk], 't1': t[pk2]}) return peak_list |
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): yield child |
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 items to print. Raises ------ ValueError When ... |
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]] Dict with keys and values swapped. See ... |
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, json=json) |
def get(self, params=None): """Send a POST request and return the JSON decoded result. Args: params (dict, optional): Mapping of parameters to send in request. Returns: mixed: JSON decoded response data. """ return self._call('get', url=self.endpoint, params=params) |
def post(self, json=None): """Send a POST 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('post', url=self.endpoint, json=json) |
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) |
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 = response.text and response.json() or {} if response.status_co... |
def pad(data, length): """This function returns a padded version of the input data to the given length. this function will shorten the given data to the length specified if necessary. post-condition: len(data) = length :param data: the data byte array to pad :param length: the length to pad the array to """ if (len(dat... |
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).encode()).digest(), (number.size(self.range) + 7) // 8) num = s... |
def _locate_bin(bins, n): """ Find the bin where list n has ended up: Follow bin references until we find a bin that has not moved. """ while bins[n] != n: n = bins[n] return n |
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 ignored. Notes ----- Implementatio... |
a pointer to this row's bin nums[num] = r continue else: dest = _locate_bin(bins, nums[num]) if dest == r: continue # already in the same bin if dest > r: dest, r = r, dest # always merge into the smallest bin data[dest].update(data[r]) data[r] = None # Update our indices to reflect the move bins[r] = dest r = dest # R... |
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 should accept a ``requests.Session`` as its first parameter, wh... |
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. Returns: RequestPaginator(output_type=helpscout.models.User):... |
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: hasher.update(buf) buf = f.read(BUF_SIZE) return hasher |
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'] timeframe = panel['dat... |
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')) |
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 optimization by setting the end_time equ... |
if (start_time % bucket_width) != 0: start_time -= (start_time % bucket_width) start = kronos_time_to_datetime(start_time) end = kronos_time_to_datetime(end_time) elif timeframe['mode']['value'] == 'range': end = datetime.datetime.strptime(timeframe['to'], DT_FORMAT) end_seconds = datetime_to_epoch_time(end) start = da... |
def _run_query(self, start_time, end_time, unique_id=None): """Executes a Python query string and returns events Acts as a wrapper around exec that injects necessary local variables into the scope of the user-provided query blob. :param start_time: Python datetime to be injected into query :param end_time: Python datet... |
`events` variable as computed by the pycode. events = locals_dict.get('events', []) return events |
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 initialized with a bucket_width' ' to use ca... |
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.datetime.now() untrusted_time = now - datetim... |
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): Authenticated session. first_name (str, optional): First name of cu... |
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 be returned. Otherwise, a ``Domain`` object will be gene... |
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() |
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/runscheduler.py` sc... |
return _APP |
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): Authenticated session. record (helpscout.models.Conversati... |
Returns: helpscout.models.Conversation: Newly created conversation. """ return super(Conversations, cls).create( session, record, imported=imported, auto_reply=auto_reply, ) |
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 attachments of 10MB or lower. Args: session (... |
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.models.Conversation): The conversation that the thr... |
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. """ return super(Conversations, cls).delete( session, attachment, endpoint_overr... |
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.Customer): Customer to search for. Returns: RequestPaginat... |
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 for. Returns: RequestPaginator(output_type=helpscout... |
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: helpscout.models.AttachmentData: An attachment data singleton, if existing. Other... |
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): Conversations iterator. """ endpoint = '/mailboxes/%d/conver... |
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): Folder to list. Returns: RequestPaginator(output_t... |
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 simply be returned. Otherwise, a ``Domain`` object will be ... |
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.models.Thread): The thread to be updated. Returns: helpscout.models.Co... |
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', logging.INFO): ... pass # sqlalchemy log level is set t... |
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 File to log to. Returns ------- ~typing... |
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() |
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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.