INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a DataFrame of advanced splits data for a player - year. Note: only go back to 2012.
def advanced_splits(self, year=None): """Returns a DataFrame of advanced splits data for a player-year. Note: only go back to 2012. :year: The year for the season in question. If None, returns career advanced splits. :returns: A DataFrame of advanced splits data. """...
Template for simple award functions that simply list years such as pro bowls and first - team all pro.
def _simple_year_award(self, award_id): """Template for simple award functions that simply list years, such as pro bowls and first-team all pro. :award_id: The div ID that is appended to "leaderboard_" in selecting the table's div. :returns: List of years for the award. ...
Returns a mapping from team ID to full team name for a given season. Example of a full team name: New England Patriots
def team_names(year): """Returns a mapping from team ID to full team name for a given season. Example of a full team name: "New England Patriots" :year: The year of the season in question (as an int). :returns: A dictionary with teamID keys and full team name values. """ doc = pq(sportsref.util...
Returns a mapping from team name to team ID for a given season. Inverse mapping of team_names. Example of a full team name: New England Patriots
def team_ids(year): """Returns a mapping from team name to team ID for a given season. Inverse mapping of team_names. Example of a full team name: "New England Patriots" :year: The year of the season in question (as an int). :returns: A dictionary with full team name keys and teamID values. """ ...
Returns the real name of the franchise given the team ID.
def name(self): """Returns the real name of the franchise given the team ID. Examples: 'nwe' -> 'New England Patriots' 'sea' -> 'Seattle Seahawks' :returns: A string corresponding to the team's full name. """ doc = self.get_main_doc() headerwords = doc('...
Returns the roster table for the given year.
def roster(self, year): """Returns the roster table for the given year. :year: The year for which we want the roster; defaults to current year. :returns: A DataFrame containing roster information for that year. """ doc = self.get_year_doc('{}_roster'.format(year)) roster...
Gets list of BoxScore objects corresponding to the box scores from that year.
def boxscores(self, year): """Gets list of BoxScore objects corresponding to the box scores from that year. :year: The year for which we want the boxscores; defaults to current year. :returns: np.array of strings representing boxscore IDs. """ doc = self.get_year...
Returns a PyQuery object containing the info from the meta div at the top of the team year page with the given keyword.
def _year_info_pq(self, year, keyword): """Returns a PyQuery object containing the info from the meta div at the top of the team year page with the given keyword. :year: Int representing the season. :keyword: A keyword to filter to a single p tag in the meta div. :returns: A PyQ...
Returns head coach data by game.
def head_coaches_by_game(self, year): """Returns head coach data by game. :year: An int representing the season in question. :returns: An array with an entry per game of the season that the team played (including playoffs). Each entry is the head coach's ID for that game in the ...
Returns the # of regular season wins a team in a year.
def wins(self, year): """Returns the # of regular season wins a team in a year. :year: The year for the season in question. :returns: The number of regular season wins. """ schedule = self.schedule(year) if schedule.empty: return np.nan return schedul...
Returns a DataFrame with schedule information for the given year.
def schedule(self, year): """Returns a DataFrame with schedule information for the given year. :year: The year for the season in question. :returns: Pandas DataFrame with schedule information. """ doc = self.get_year_doc(year) table = doc('table#games') df = spor...
Returns the SRS ( Simple Rating System ) for a team in a year.
def srs(self, year): """Returns the SRS (Simple Rating System) for a team in a year. :year: The year for the season in question. :returns: A float of SRS. """ try: srs_text = self._year_info_pq(year, 'SRS').text() except ValueError: return None ...
Returns the SOS ( Strength of Schedule ) for a team in a year based on SRS.
def sos(self, year): """Returns the SOS (Strength of Schedule) for a team in a year, based on SRS. :year: The year for the season in question. :returns: A float of SOS. """ try: sos_text = self._year_info_pq(year, 'SOS').text() except ValueError: ...
Returns the coach ID for the team s OC in a given year.
def off_coordinator(self, year): """Returns the coach ID for the team's OC in a given year. :year: An int representing the year. :returns: A string containing the coach ID of the OC. """ try: oc_anchor = self._year_info_pq(year, 'Offensive Coordinator')('a') ...
Returns the coach ID for the team s DC in a given year.
def def_coordinator(self, year): """Returns the coach ID for the team's DC in a given year. :year: An int representing the year. :returns: A string containing the coach ID of the DC. """ try: dc_anchor = self._year_info_pq(year, 'Defensive Coordinator')('a') ...
Returns the ID for the stadium in which the team played in a given year.
def stadium(self, year): """Returns the ID for the stadium in which the team played in a given year. :year: The year in question. :returns: A string representing the stadium ID. """ anchor = self._year_info_pq(year, 'Stadium')('a') return sportsref.utils.rel_url_...
Returns the name of the offensive scheme the team ran in the given year.
def off_scheme(self, year): """Returns the name of the offensive scheme the team ran in the given year. :year: Int representing the season year. :returns: A string representing the offensive scheme. """ scheme_text = self._year_info_pq(year, 'Offensive Scheme').text() ...
Returns the name of the defensive alignment the team ran in the given year.
def def_alignment(self, year): """Returns the name of the defensive alignment the team ran in the given year. :year: Int representing the season year. :returns: A string representing the defensive alignment. """ scheme_text = self._year_info_pq(year, 'Defensive Alignment...
Returns a Series ( dict - like ) of team stats from the team - season page.
def team_stats(self, year): """Returns a Series (dict-like) of team stats from the team-season page. :year: Int representing the season. :returns: A Series of team stats. """ doc = self.get_year_doc(year) table = doc('table#team_stats') df = sportsref.uti...
Returns a Series ( dict - like ) of the team s opponent s stats from the team - season page.
def opp_stats(self, year): """Returns a Series (dict-like) of the team's opponent's stats from the team-season page. :year: Int representing the season. :returns: A Series of team stats. """ doc = self.get_year_doc(year) table = doc('table#team_stats') df...
Returns a DataFrame of offensive team splits for a season.
def off_splits(self, year): """Returns a DataFrame of offensive team splits for a season. :year: int representing the season. :returns: Pandas DataFrame of split data. """ doc = self.get_year_doc('{}_splits'.format(year)) tables = doc('table.stats_table') dfs = [...
Gets the HTML for the given URL using a GET request.
def get_html(url): """Gets the HTML for the given URL using a GET request. :url: the absolute URL of the desired page. :returns: a string of HTML. """ global last_request_time with throttle_process_lock: with throttle_thread_lock: # sleep until THROTTLE_DELAY secs have passe...
Parses a table from sports - reference sites into a pandas dataframe.
def parse_table(table, flatten=True, footer=False): """Parses a table from sports-reference sites into a pandas dataframe. :param table: the PyQuery object representing the HTML table :param flatten: if True, flattens relative URLs to IDs. otherwise, leaves all fields as text without cleaning. ...
Parses an info table like the Game Info table or the Officials table on the PFR Boxscore page. Keys are lower case and have spaces/ special characters converted to underscores.
def parse_info_table(table): """Parses an info table, like the "Game Info" table or the "Officials" table on the PFR Boxscore page. Keys are lower case and have spaces/special characters converted to underscores. :table: PyQuery object representing the HTML table. :returns: A dictionary representin...
Flattens relative URLs within text of a table cell to IDs and returns the result.
def flatten_links(td, _recurse=False): """Flattens relative URLs within text of a table cell to IDs and returns the result. :td: the PyQuery object for the HTML to convert :returns: the string with the links flattened to IDs """ # helper function to flatten individual strings/links def _fl...
Converts a relative URL to a unique ID.
def rel_url_to_id(url): """Converts a relative URL to a unique ID. Here, 'ID' refers generally to the unique ID for a given 'type' that a given datum has. For example, 'BradTo00' is Tom Brady's player ID - this corresponds to his relative URL, '/players/B/BradTo00.htm'. Similarly, '201409070dal' re...
Docstring will be filled in by __init__. py
def PlayerSeasonFinder(**kwargs): """ Docstring will be filled in by __init__.py """ if 'offset' not in kwargs: kwargs['offset'] = 0 playerSeasons = [] while True: querystring = _kwargs_to_qs(**kwargs) url = '{}?{}'.format(PSF_URL, querystring) if kwargs.get('verbose', ...
Converts kwargs given to PSF to a querystring.
def _kwargs_to_qs(**kwargs): """Converts kwargs given to PSF to a querystring. :returns: the querystring. """ # start with defaults inpOptDef = inputs_options_defaults() opts = { name: dct['value'] for name, dct in inpOptDef.items() } # clean up keys and values for ...
Main function for the processes that read from the HDF5 file.
def _Streamer__read_process(self, path, read_size, cbuf, stop, barrier, cyclic, offset, read_skip, sync): """ Main function for the processes that read from the HDF5 file. :param self: A reference to the streamer object that created these processes. :param path: The HDF5 path to the node to be read fro...
Wait until all processes have reached the barrier.
def wait(self): """Wait until all processes have reached the barrier.""" with self.cvar: self.count.value += 1 self.cvar.notify_all() while self.count.value < self.n_procs: self.cvar.wait()
Wait until all processes have reached the barrier.
def wait(self): """Wait until all processes have reached the barrier.""" self.barrier_A.wait() # The current barrier (barrier_A) is switched with the reserve barrier. # This is because the current barrier cannot be safely reset until the reserve barrier has been passed. self.barr...
Block until it is the turn indicated by index.: param index:: param next_index: Set the index to this value after finishing. Releases the process waiting on next_index. Defaults to incrementing index by 1.: return:
def wait(self, index, next_index=None): """ Block until it is the turn indicated by index. :param index: :param next_index: Set the index to this value after finishing. Releases the process waiting on next_index. Defaults to incrementing index by 1. :return: "...
Create a guard that requires the resource guard to be entered and exited based on the order provided by index.: param guard: The context manager for the resource.: param index: The order to wait for.: param next_index: The next index to release.: return:
def do(self, guard, index, next_index): """ Create a guard that requires the resource guard to be entered and exited based on the order provided by index. :param guard: The context manager for the resource. :param index: The order to wait for. :param next_index: The next index to...
Put an unsigned integer into the queue. This method always assumes that there is space in the queue. ( In the circular buffer this is guaranteed by the implementation ): param v: The item to insert. Must be > = 0 as - 2 is used to signal a queue close.: return:
def put(self, v): """ Put an unsigned integer into the queue. This method always assumes that there is space in the queue. ( In the circular buffer, this is guaranteed by the implementation ) :param v: The item to insert. Must be >= 0, as -2 is used to signal a queue close. :retu...
Fetch the next item in the queue. Blocks until an item is ready.: return: The next unsigned integer in the queue.
def get(self): """ Fetch the next item in the queue. Blocks until an item is ready. :return: The next unsigned integer in the queue. """ with self.cvar: while True: if self.size.value > 0: rval = self.vals[self.tail.value] ...
Allows direct access to the buffer element. Blocks until there is room to write into the buffer.
def put_direct(self): """ Allows direct access to the buffer element. Blocks until there is room to write into the buffer. :return: A guard object that returns the buffer element. """ # Once the guard is released, write_idx will be placed into read_queue. return...
Allows direct access to the buffer element. Blocks until there is data that can be read.
def get_direct(self): """ Allows direct access to the buffer element. Blocks until there is data that can be read. :return: A guard object that returns the buffer element. """ read_idx = self.__get_idx() if read_idx is QueueClosed: return QueueClose...
Close the queue signalling that no more data can be put into the queue.
def close(self): """Close the queue, signalling that no more data can be put into the queue.""" self.read_queue.put(QueueClosed) self.write_queue.put(QueueClosed)
Get a block of data from the node at path.
def __get_batch(self, path, length, last=False): """ Get a block of data from the node at path. :param path: The path to the node to read from. :param length: The length along the outer dimension to read. :param last: True if the remainder elements should be read. :retur...
Get the remainder elements. These elements will not be read in the direct queue access cyclic = False mode.
def get_remainder(self, path, block_size): """ Get the remainder elements. These elements will not be read in the direct queue access cyclic=False mode. :param path: The HDF5 path to the dataset to be read. :param block_size: The block size is used to calculate which elements will remai...
Get a queue that allows direct access to the internal buffer. If the dataset to be read is chunked the block_size should be a multiple of the chunk size to maximise performance. In this case it is best to leave it to the default. When cyclic = False and block_size does not divide the dataset evenly the remainder elemen...
def get_queue(self, path, n_procs=4, read_ahead=None, cyclic=False, block_size=None, ordered=False): """ Get a queue that allows direct access to the internal buffer. If the dataset to be read is chunked, the block_size should be a multiple of the chunk size to maximise performance. In this case...
Get a generator that allows convenient access to the streamed data. Elements from the dataset are returned from the generator one row at a time. Unlike the direct access queue this generator also returns the remainder elements. Additional arguments are forwarded to get_queue. See the get_queue method for documentation ...
def get_generator(self, path, *args, **kw_args): """ Get a generator that allows convenient access to the streamed data. Elements from the dataset are returned from the generator one row at a time. Unlike the direct access queue, this generator also returns the remainder elements. ...
Parse a stream.
def parse(ifp, pb_cls, **kwargs): """Parse a stream. Args: ifp (string or file-like object): input stream. pb_cls (protobuf.message.Message.__class__): The class object of the protobuf message type encoded in the stream. """ mode = 'rb' if isinstance(ifp, str): i...
Write to a stream.
def dump(ofp, *pb_objs, **kwargs): """Write to a stream. Args: ofp (string or file-like object): output stream. pb_objs (*protobuf.message.Message): list of protobuf message objects to be written. """ mode = 'wb' if isinstance(ofp, str): ostream = open(ofp, mode=...
Read a varint from file parse it and return the decoded integer.
def _read_varint(self): """Read a varint from file, parse it, and return the decoded integer. """ buff = self._fd.read(1) if buff == b'': return 0 while (bytearray(buff)[-1] & 0x80) >> 7 == 1: # while the MSB is 1 new_byte = self._fd.read(1) ...
A generator yielding all protobuf object data in the file. It is the main parser of the stream encoding.
def _get_objs(self): """A generator yielding all protobuf object data in the file. It is the main parser of the stream encoding. """ while True: count = self._read_varint() if count == 0: break # Read a group containing `count` number o...
Close the stream.
def close(self): """Close the stream.""" self.flush() if self._myfd is not None: self._myfd.close() self._myfd = None
Write a group of one or more protobuf objects to the file. Multiple object groups can be written by calling this method several times before closing stream or exiting the runtime context.
def write(self, *pb2_obj): """Write a group of one or more protobuf objects to the file. Multiple object groups can be written by calling this method several times before closing stream or exiting the runtime context. The input protobuf objects get buffered and will be written down when...
Write down buffer to the file.
def flush(self): """Write down buffer to the file.""" if not self.is_output(): return count = len(self._write_buff) if count == 0: return encodeVarint(self._fd.write, count, True) for obj in self._write_buff: obj_str = obj.SerializeT...
Returns joined game directory path relative to Steamapps
def get_game_dir(self, username=False): """Returns joined game directory path relative to Steamapps""" if not self.common and not username: raise RuntimeError("Can't determine this game's directory without username") if self.common: subdir = "common" else: ...
Used internally by deconvolve to compute the maximum a posteriori spike train for a given set of fluorescence traces and model parameters.
def _get_MAP_spikes(F, c_hat, theta, dt, tol=1E-6, maxiter=100, verbosity=0): """ Used internally by deconvolve to compute the maximum a posteriori spike train for a given set of fluorescence traces and model parameters. See the documentation for deconvolve for the meaning of the arguments Ret...
The tridiagonal matrix ( Thomas ) algorithm for solving tridiagonal systems of equations:
def trisolve(dl, d, du, b, inplace=False): """ The tridiagonal matrix (Thomas) algorithm for solving tridiagonal systems of equations: a_{i}x_{i-1} + b_{i}x_{i} + c_{i}x_{i+1} = y_{i} in matrix form: Mx = b TDMA is O(n), whereas standard Gaussian elimination is O(n^3). Argume...
Store reference to a WebElement instance representing the element on the DOM. Use it when an instance of WebElement has already been created ( e. g. as the result of find_element ) and you want to create a UIComponent out of it without evaluating it from the locator again. Returns an instance of the class.
def from_web_element(self, web_element): """ Store reference to a WebElement instance representing the element on the DOM. Use it when an instance of WebElement has already been created (e.g. as the result of find_element) and you want to create a UIComponent out of it withou...
Lazily locates the element on the DOM if the WebElement instance is not available already. Returns a WebElement object. It also caches the element if caching has been set through cache ().
def locate(self): """ Lazily locates the element on the DOM if the WebElement instance is not available already. Returns a WebElement object. It also caches the element if caching has been set through cache(). """ if self._web_element: return self....
Works around the problem of emulating user interactions with text inputs. Emulates a key - down action on the first char of the input. This way implementations which require key - down event to trigger auto - suggest are testable. Then the chains sends the rest of the text and releases the key.
def input_text_with_keyboard_emulation(self, text): """ Works around the problem of emulating user interactions with text inputs. Emulates a key-down action on the first char of the input. This way, implementations which require key-down event to trigger auto-suggest are test...
Generate 2D fake fluorescence movie
def make_fake_movie(nframes, mask_shape=(64, 64), mask_center=None, bg_intensity=0.1, mask_sigma=10, dt=0.02, rate=1.0, tau=1., sigma=0.001, seed=None): """ Generate 2D fake fluorescence movie Arguments: -----------------------------------------------------------...
Evaluates traits and returns a list containing the description of traits which are not true. Notice that if LAZY_EVALUATION is set to False all traits are evaluated before returning. Use this option only for debugging purposes.
def evaluate_traits(self): """ Evaluates traits and returns a list containing the description of traits which are not true. Notice that if LAZY_EVALUATION is set to False all traits are evaluated before returning. Use this option only for debugging purposes. """ return_va...
Waits until conditions is True or returns a non - None value. If any of the trait is still not present after timeout raises a TimeoutException.
def until_condition(self, condition, condition_description): """ Waits until conditions is True or returns a non-None value. If any of the trait is still not present after timeout, raises a TimeoutException. """ end_time = time.time() + self._timeout count = 1 whi...
Waits until all traits are present. If any of the traits is still not present after timeout raises a TimeoutException.
def until_traits_are_present(self, element_with_traits): """ Waits until all traits are present. If any of the traits is still not present after timeout, raises a TimeoutException. """ end_time = time.time() + self._timeout count = 1 missing_traits_descriptions = ...
Set a list of exceptions that should be ignored inside the wait loop.
def with_ignored_exceptions(self, *ignored_exceptions): """ Set a list of exceptions that should be ignored inside the wait loop. """ for exception in ignored_exceptions: self._ignored_exceptions = self._ignored_exceptions + (exception,) return self
convert seconds to a pretty d hh: mm: ss. s format
def s2h(ss): """convert seconds to a pretty "d hh:mm:ss.s" format""" mm, ss = divmod(ss, 60) hh, mm = divmod(mm, 60) dd, hh = divmod(hh, 24) tstr = "%02i:%04.1f" % (mm, ss) if hh > 0: tstr = ("%02i:" % hh) + tstr if dd > 0: tstr = ("%id " % dd) + tstr return tstr
Write a command to the receiver and read the value it returns.
def exec_command(self, domain, function, operator, value=None): """ Write a command to the receiver and read the value it returns. The receiver will always return a value, also when setting a value. """ if operator in CMDS[domain][function]['supported_operators']: if...
Execute Main. Volume.
def main_volume(self, operator, value=None): """ Execute Main.Volume. Returns int """ try: res = int(self.exec_command('main', 'volume', operator, value)) return res except (ValueError, TypeError): pass return None
Execute Main. Source.
def main_source(self, operator, value=None): """ Execute Main.Source. Returns int """ try: source = int(self.exec_command('main', 'source', operator, value)) return source except (ValueError, TypeError): pass return None
Send a command string to the amplifier.
def _send(self, message, read_reply=False): """Send a command string to the amplifier.""" sock = None for tries in range(0, 3): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self._host, self.PORT)) break ...
Return the status of the device.
def status(self): """ Return the status of the device. Returns a dictionary with keys 'volume' (int 0-200) , 'power' (bool), 'muted' (bool) and 'source' (str). """ nad_reply = self._send(self.POLL_VOLUME + self.POLL_POWER + ...
Power the device off.
def power_off(self): """Power the device off.""" status = self.status() if status['power']: # Setting power off when it is already off can cause hangs self._send(self.CMD_POWERSAVE + self.CMD_OFF)
Power the device on.
def power_on(self): """Power the device on.""" status = self.status() if not status['power']: self._send(self.CMD_ON, read_reply=True) sleep(0.5)
Set volume level of the device. Accepts integer values 0 - 200.
def set_volume(self, volume): """Set volume level of the device. Accepts integer values 0-200.""" if 0 <= volume <= 200: volume = format(volume, "02x") # Convert to hex self._send(self.CMD_VOLUME + volume)
Select a source from the list of sources.
def select_source(self, source): """Select a source from the list of sources.""" status = self.status() if status['power']: # Changing source when off may hang NAD7050 if status['source'] != source: # Setting the source to the current source will hang the NAD7050 if...
Write a command to the receiver and read the value it returns.
def exec_command(self, domain, function, operator, value=None): """ Write a command to the receiver and read the value it returns. """ if operator in CMDS[domain][function]['supported_operators']: if operator is '=' and value is None: raise ValueError('No valu...
Deobfuscates the URL and returns HttpResponse from source view. SEO juice is mostly ignored as it is intended for display purposes only.
def deobfuscate(request, key, juice=None): """ Deobfuscates the URL and returns HttpResponse from source view. SEO juice is mostly ignored as it is intended for display purposes only. """ try: url = decrypt(str(key), settings.UNFRIENDLY_SECRET, set...
Pads secret if not legal AES block size ( 16 24 32 )
def _lazysecret(secret, blocksize=32, padding='}'): """Pads secret if not legal AES block size (16, 24, 32)""" if not len(secret) in (16, 24, 32): return secret + (blocksize - len(secret)) * padding return secret
Generates crc32. Modulo keep the value within int range.
def _crc(plaintext): """Generates crc32. Modulo keep the value within int range.""" if not isinstance(plaintext, six.binary_type): plaintext = six.b(plaintext) return (zlib.crc32(plaintext) % 2147483647) & 0xffffffff
Encrypts plaintext with secret plaintext - content to encrypt secret - secret to encrypt plaintext inital_vector - initial vector lazy - pad secret if less than legal blocksize ( default: True ) checksum - attach crc32 byte encoded ( default: True ) returns ciphertext
def encrypt(plaintext, secret, inital_vector, checksum=True, lazy=True): """Encrypts plaintext with secret plaintext - content to encrypt secret - secret to encrypt plaintext inital_vector - initial vector lazy - pad secret if less than legal blocksize (default: True) che...
Decrypts ciphertext with secret ciphertext - encrypted content to decrypt secret - secret to decrypt ciphertext inital_vector - initial vector lazy - pad secret if less than legal blocksize ( default: True ) checksum - verify crc32 byte encoded checksum ( default: True ) returns plaintext
def decrypt(ciphertext, secret, inital_vector, checksum=True, lazy=True): """Decrypts ciphertext with secret ciphertext - encrypted content to decrypt secret - secret to decrypt ciphertext inital_vector - initial vector lazy - pad secret if less than legal blocksize (default: ...
Template filter that obfuscates whatever text it is applied to. The text is supposed to be a URL but it will obfuscate anything.
def obfuscate(value, juice=None): """ Template filter that obfuscates whatever text it is applied to. The text is supposed to be a URL, but it will obfuscate anything. Usage: Extremely unfriendly URL: {{ "/my-secret-path/"|obfuscate }} Include some SEO juice: {{ "/my-se...
It will print the list of songs that can be downloaded
def missing_schema(self,html,song_name): ''' It will print the list of songs that can be downloaded ''' #html=self.get_html_response(url) soup=BeautifulSoup(html) name=' '.join(song_name) print '%s not found'%name print "But you can download any of the following songs :" a_list=soup.findAll('a','touch...
It will return all hyper links found in the mr - jatt page for download
def list_of_all_href(self,html): ''' It will return all hyper links found in the mr-jatt page for download ''' soup=BeautifulSoup(html) links=[] a_list=soup.findAll('a','touch') for x in xrange(len(a_list)-1): link = a_list[x].get('href') name = a_list[x] name = str(name) name=re.sub(r'<a.*/>...
Returns true if user entered artist or movie name
def check_if_song_name(self,html): ''' Returns true if user entered artist or movie name ''' soup=BeautifulSoup(html) a_list=soup.findAll('a','touch') #print a_list text=[str(x) for x in a_list] text=''.join(text) text=text.lower() string1='download in 48 kbps' string2='download in 128 kbps' str...
It will the resource URL if song is found Otherwise it will return the list of songs that can be downloaded
def Parse(self,url,song_name,flag): ''' It will the resource URL if song is found, Otherwise it will return the list of songs that can be downloaded ''' file_download=FileDownload() html=file_download.get_html_response(url) if flag == False: soup=BeautifulSoup(html) a_list=soup.findAll('a','touch') ...
It will return the google url to be searched
def google_url(self,song_name,website): ''' It will return the google url to be searched''' name='+'.join(song_name) prefix='https://www.google.co.in/search?q=' website=website.split(" ") suffix='+'.join(website) url=prefix+name+suffix #print url return url
It will parse google html response and return the first url
def parse_google(self,html): '''It will parse google html response and return the first url ''' soup = BeautifulSoup(html) href=soup.find('div','g').find('a').get('href') href_list=href.split('&') download_url=href_list[0] download_url=download_url.strip() download_url=download_url.replace('/url?q='...
song_name is a list of strings website is a string It will return the url from where music file needs to be downloaded
def Parse(self,song_name,website): ''' song_name is a list of strings website is a string It will return the url from where music file needs to be downloaded ''' url_to_be_parsed=self.google_url(song_name,website) file_download=FileDownload() html=file_download.get_html_response(url_to_be_parsed) webs...
It will download the html page specified by url and return the html response
def get_html_response(self,url): '''It will download the html page specified by url and return the html response ''' print "Downloading page %s .."%url try: response=requests.get(url,timeout=50) except requests.exceptions.SSLError: try: response=requests.get(url,verify=False,timeout=50) except requ...
It will download file specified by url using requests module
def file_download_using_requests(self,url): '''It will download file specified by url using requests module''' file_name=url.split('/')[-1] if os.path.exists(os.path.join(os.getcwd(),file_name)): print 'File already exists' return #print 'Downloading file %s '%file_name #print 'Downloading from %s'%url...
It will download file specified by url using wget utility of linux
def file_download_using_wget(self,url): '''It will download file specified by url using wget utility of linux ''' file_name=url.split('/')[-1] print 'Downloading file %s '%file_name command='wget -c --read-timeout=50 --tries=3 -q --show-progress --no-check-certificate ' url='"'+url+'"' command=command+url ...
Main CLI entrypoint.
def main(): """Main CLI entrypoint.""" #print VERSION from commands.download import Download options = docopt(__doc__, version=VERSION) #print "You reached here" #print options print "working." p=Download(options) p.run()
Create a read - only bloom filter with an upperbound of ( num_elements max_fp_prob ) as a specification and using filename as the backing datastore.
def ReadingBloomFilter(filename, want_lock=False): """ Create a read-only bloom filter with an upperbound of (num_elements, max_fp_prob) as a specification and using filename as the backing datastore. """ with open('{}.desc'.format(filename), 'r') as descriptor: num_elements = int(descri...
Create a read/ write bloom filter with an upperbound of ( num_elements max_fp_prob ) as a specification and using filename as the backing datastore.
def WritingBloomFilter(num_elements, max_fp_prob, filename=None, ignore_case=False, want_lock=False, fdatasync_on_close=True): """ Create a read/write bloom filter with an upperbound of (num_elements, max_fp_prob) as a specification and using filename as the...
Lookup AQI database for station codes in a given city.
def findStationCodesByCity(city_name, token): """Lookup AQI database for station codes in a given city.""" req = requests.get( API_ENDPOINT_SEARCH, params={ 'token': token, 'keyword': city_name }) if req.status_code == 200 and req.json()["status"] == "ok": ...
Lookup observations by geo coordinates.
def get_location_observation(lat, lng, token): """Lookup observations by geo coordinates.""" req = requests.get( API_ENDPOINT_GEO % (lat, lng), params={ 'token': token }) if req.status_code == 200 and req.json()["status"] == "ok": return parse_observation_respons...
Decode AQICN observation response JSON into python object.
def parse_observation_response(json): """Decode AQICN observation response JSON into python object.""" logging.debug(json) iaqi = json['iaqi'] result = { 'idx': json['idx'], 'city': json.get('city', ''), 'aqi': json['aqi'], 'dominentpol': json.get("dominentpol", ''), ...
Request station data for a specific station identified by code.
def get_station_observation(station_code, token): """Request station data for a specific station identified by code. A language parameter can also be specified to translate location information (default: "en") """ req = requests.get( API_ENDPOINT_OBS % (station_code), params={ ...
The list of logical paths which are used to search for an asset. This property makes sense only if the attributes was created with logical path.
def search_paths(self): """The list of logical paths which are used to search for an asset. This property makes sense only if the attributes was created with logical path. It is assumed that the logical path can be a directory containing a file named ``index`` with the same suff...
The relative path to asset without suffix. Example::
def path_without_suffix(self): """The relative path to asset without suffix. Example:: >>> attrs = AssetAttributes(environment, 'js/app.js') >>> attrs.path_without_suffix 'js/app' """ if self.suffix: return self.path[:-len(''.join(self.suf...
The logical path to asset. Example::
def logical_path(self): """The logical path to asset. Example:: >>> attrs = AssetAttributes(environment, 'js/models.js.coffee') >>> attrs.logical_path 'js/models.js' """ format_extension = self.format_extension or self.compiler_format_extension ...
The list of asset extensions. Example::
def extensions(self): """The list of asset extensions. Example:: >>> attrs = AssetAttributes(environment, 'js/models.js.coffee') >>> attrs.extensions ['.js', '.coffee'] >>> attrs = AssetAttributes(environment, 'js/lib/external.min.js.coffee') ...
The format extension of asset. Example::
def format_extension(self): """The format extension of asset. Example:: >>> attrs = AssetAttributes(environment, 'js/models.js.coffee') >>> attrs.format_extension '.js' >>> attrs = AssetAttributes(environment, 'js/lib/external.min.js.coffee') ...
The list of unknown extensions which are actually parts of asset filename. Example::
def unknown_extensions(self): """The list of unknown extensions, which are actually parts of asset filename. Example:: >>> attrs = AssetAttributes(environment, 'js/lib-2.0.min.js') >>> attrs.suffix ['.0', '.min'] """ unknown_extensions = [] fo...