_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q8500
RequestHandler.get
train
def get(self, url, params=None): """ Initiate a GET request """ r = self.session.get(url, params=params) return self._response_parser(r, expect_json=False)
python
{ "resource": "" }
q8501
RequestHandler.post
train
def post(self, url, data, params=None): """ Initiate a POST request """ r = self.session.post(url, data=data, params=params) return self._response_parser(r, expect_json=False)
python
{ "resource": "" }
q8502
RequestHandler.send
train
def send(self, request, expect_json=True, ignore_content=False): """ Send a formatted API request :param request: a formatted request object :type request: :class:`.Request` :param bool expect_json: if True, raise :class:`.InvalidAPIAccess` if response is not in JSON...
python
{ "resource": "" }
q8503
API.login
train
def login(self, username=None, password=None, section='default'): """ Created the passport with ``username`` and ``password`` and log in. If either ``username`` or ``password`` is None or omitted, the credentials file will be parsed. :param str username: username t...
python
{ "resource": "" }
q8504
API.user_id
train
def user_id(self): """ User id of the current API user """ if self._user_id is None: if self.has_logged_in: self._user_id = self._req_get_user_aq()['data']['uid'] else: raise AuthenticationError('Not logged in.') return self...
python
{ "resource": "" }
q8505
API.username
train
def username(self): """ Username of the current API user """ if self._username is None: if self.has_logged_in: self._username = self._get_username() else: raise AuthenticationError('Not logged in.') return self._username
python
{ "resource": "" }
q8506
API.has_logged_in
train
def has_logged_in(self): """Check whether the API has logged in""" r = self.http.get(CHECKPOINT_URL) if r.state is False: return True # If logged out, flush cache self._reset_cache() return False
python
{ "resource": "" }
q8507
API.receiver_directory
train
def receiver_directory(self): """Parent directory of the downloads directory""" if self._receiver_directory is None: self._receiver_directory = self.downloads_directory.parent return self._receiver_directory
python
{ "resource": "" }
q8508
API.add_task_bt
train
def add_task_bt(self, filename, select=False): """ Add a new BT task :param str filename: path to torrent file to upload :param bool select: whether to select files in the torrent. * True: it returns the opened torrent (:class:`.Torrent`) and can then iterat...
python
{ "resource": "" }
q8509
API.get_storage_info
train
def get_storage_info(self, human=False): """ Get storage info :param bool human: whether return human-readable size :return: total and used storage :rtype: dict """ res = self._req_get_storage_info() if human: res['total'] = humanize.naturals...
python
{ "resource": "" }
q8510
API.upload
train
def upload(self, filename, directory=None): """ Upload a file ``filename`` to ``directory`` :param str filename: path to the file to upload :param directory: destionation :class:`.Directory`, defaults to :attribute:`.API.downloads_directory` if None :return: the uplo...
python
{ "resource": "" }
q8511
API.download
train
def download(self, obj, path=None, show_progress=True, resume=True, auto_retry=True, proapi=False): """ Download a file :param obj: :class:`.File` object :param str path: local path :param bool show_progress: whether to show download progress :param bool...
python
{ "resource": "" }
q8512
API.search
train
def search(self, keyword, count=30): """ Search files or directories :param str keyword: keyword :param int count: number of entries to be listed """ kwargs = {} kwargs['search_value'] = keyword root = self.root_directory entries = root._load_entr...
python
{ "resource": "" }
q8513
API._req_offline_space
train
def _req_offline_space(self): """Required before accessing lixian tasks""" url = 'http://115.com/' params = { 'ct': 'offline', 'ac': 'space', '_': get_timestamp(13) } _sign = os.environ.get('U115_BROWSER_SIGN') if _sign is not None: ...
python
{ "resource": "" }
q8514
API._req_lixian_task_lists
train
def _req_lixian_task_lists(self, page=1): """ This request will cause the system to create a default downloads directory if it does not exist """ url = 'http://115.com/lixian/' params = {'ct': 'lixian', 'ac': 'task_lists'} self._load_signatures() data = { ...
python
{ "resource": "" }
q8515
API._req_lixian_get_id
train
def _req_lixian_get_id(self, torrent=False): """Get `cid` of lixian space directory""" url = 'http://115.com/' params = { 'ct': 'lixian', 'ac': 'get_id', 'torrent': 1 if torrent else None, '_': get_timestamp(13) } req = Request(meth...
python
{ "resource": "" }
q8516
API._req_files_edit
train
def _req_files_edit(self, fid, file_name=None, is_mark=0): """Edit a file or directory""" url = self.web_api_url + '/edit' data = locals() del data['self'] req = Request(method='POST', url=url, data=data) res = self.http.send(req) if res.state: return ...
python
{ "resource": "" }
q8517
API._req_directory
train
def _req_directory(self, cid): """Return name and pid of by cid""" res = self._req_files(cid=cid, offset=0, limit=1, show_dir=1) path = res['path'] count = res['count'] for d in path: if str(d['cid']) == str(cid): res = { 'cid': d['...
python
{ "resource": "" }
q8518
API._req_upload
train
def _req_upload(self, filename, directory): """Raw request to upload a file ``filename``""" self._upload_url = self._load_upload_url() self.http.get('http://upload.115.com/crossdomain.xml') b = os.path.basename(filename) target = 'U_1_' + str(directory.cid) files = { ...
python
{ "resource": "" }
q8519
API._load_root_directory
train
def _load_root_directory(self): """ Load root directory, which has a cid of 0 """ kwargs = self._req_directory(0) self._root_directory = Directory(api=self, **kwargs)
python
{ "resource": "" }
q8520
API._load_torrents_directory
train
def _load_torrents_directory(self): """ Load torrents directory If it does not exist yet, this request will cause the system to create one """ r = self._req_lixian_get_id(torrent=True) self._downloads_directory = self._load_directory(r['cid'])
python
{ "resource": "" }
q8521
API._load_downloads_directory
train
def _load_downloads_directory(self): """ Load downloads directory If it does not exist yet, this request will cause the system to create one """ r = self._req_lixian_get_id(torrent=False) self._downloads_directory = self._load_directory(r['cid'])
python
{ "resource": "" }
q8522
API._parse_src_js_var
train
def _parse_src_js_var(self, variable): """Parse JavaScript variables in the source page""" src_url = 'http://115.com' r = self.http.get(src_url) soup = BeautifulSoup(r.content) scripts = [script.text for script in soup.find_all('script')] text = '\n'.join(scripts) ...
python
{ "resource": "" }
q8523
BaseFile.delete
train
def delete(self): """ Delete this file or directory :return: whether deletion is successful :raise: :class:`.APIError` if this file or directory is already deleted """ fcid = None pid = None if isinstance(self, File): fcid = self.fid ...
python
{ "resource": "" }
q8524
BaseFile.edit
train
def edit(self, name, mark=False): """ Edit this file or directory :param str name: new name for this entry :param bool mark: whether to bookmark this entry """ self.api.edit(self, name, mark)
python
{ "resource": "" }
q8525
File.directory
train
def directory(self): """Directory that holds this file""" if self._directory is None: self._directory = self.api._load_directory(self.cid) return self._directory
python
{ "resource": "" }
q8526
File.get_download_url
train
def get_download_url(self, proapi=False): """ Get this file's download URL :param bool proapi: whether to use pro API """ if self._download_url is None: self._download_url = \ self.api._req_files_download_url(self.pickcode, proapi) return sel...
python
{ "resource": "" }
q8527
File.download
train
def download(self, path=None, show_progress=True, resume=True, auto_retry=True, proapi=False): """Download this file""" self.api.download(self, path, show_progress, resume, auto_retry, proapi)
python
{ "resource": "" }
q8528
File.reload
train
def reload(self): """ Reload file info and metadata * name * sha * pickcode """ res = self.api._req_file(self.fid) data = res['data'][0] self.name = data['file_name'] self.sha = data['sha1'] self.pickcode = data['pick_code']
python
{ "resource": "" }
q8529
Directory.parent
train
def parent(self): """Parent directory that holds this directory""" if self._parent is None: if self.pid is not None: self._parent = self.api._load_directory(self.pid) return self._parent
python
{ "resource": "" }
q8530
Directory.reload
train
def reload(self): """ Reload directory info and metadata * `name` * `pid` * `count` """ r = self.api._req_directory(self.cid) self.pid = r['pid'] self.name = r['name'] self._count = r['count']
python
{ "resource": "" }
q8531
Directory.list
train
def list(self, count=30, order='user_ptime', asc=False, show_dir=True, natsort=True): """ List directory contents :param int count: number of entries to be listed :param str order: order of entries, originally named `o`. This value may be one of `user_ptime` (de...
python
{ "resource": "" }
q8532
Task.status_human
train
def status_human(self): """ Human readable status :return: * `DOWNLOADING`: the task is downloading files * `BEING TRANSFERRED`: the task is being transferred * `TRANSFERRED`: the task has been transferred to downloads \ directory ...
python
{ "resource": "" }
q8533
Task.directory
train
def directory(self): """Associated directory, if any, with this task""" if not self.is_directory: msg = 'This task is a file task with no associated directory.' raise TaskError(msg) if self._directory is None: if self.is_transferred: self._dire...
python
{ "resource": "" }
q8534
Task.list
train
def list(self, count=30, order='user_ptime', asc=False, show_dir=True, natsort=True): """ List files of the associated directory to this task. :param int count: number of entries to be listed :param str order: originally named `o` :param bool asc: whether in ascendi...
python
{ "resource": "" }
q8535
Torrent.submit
train
def submit(self): """Submit this torrent and create a new task""" if self.api._req_lixian_add_task_bt(self): self.submitted = True return True return False
python
{ "resource": "" }
q8536
Command.get_needful_files
train
def get_needful_files(self): """ Returns currently used static files. Assumes that manifest staticfiles.json is up-to-date. """ manifest = self.storage.load_manifest() if self.keep_unhashed_files: if PY3: needful_files = set(manifest.keys() | m...
python
{ "resource": "" }
q8537
Command.model_file_fields
train
def model_file_fields(self, model): """ Generator yielding all instances of FileField and its subclasses of a model. """ for field in model._meta.fields: if isinstance(field, models.FileField): yield field
python
{ "resource": "" }
q8538
Command.get_resource_types
train
def get_resource_types(self): """ Returns set of resource types of FileFields of all registered models. Needed by Cloudinary as resource type is needed to browse or delete specific files. """ resource_types = set() for model in self.models(): for field in self...
python
{ "resource": "" }
q8539
Command.get_needful_files
train
def get_needful_files(self): """ Returns set of media files associated with models. Those files won't be deleted. """ needful_files = [] for model in self.models(): media_fields = [] for field in self.model_file_fields(model): media...
python
{ "resource": "" }
q8540
Command.get_files_to_remove
train
def get_files_to_remove(self): """ Returns orphaned media files to be removed grouped by resource type. All files which paths start with any of exclude paths are ignored. """ files_to_remove = {} needful_files = self.get_needful_files() for resources_type, resourc...
python
{ "resource": "" }
q8541
StaticCloudinaryStorage._get_resource_type
train
def _get_resource_type(self, name): """ Implemented as static files can be of different resource types. Because web developers are the people who control those files, we can distinguish them simply by looking at their extensions, we don't need any content based validation. """ ...
python
{ "resource": "" }
q8542
StaticCloudinaryStorage._remove_extension_for_non_raw_file
train
def _remove_extension_for_non_raw_file(self, name): """ Implemented as image and video files' Cloudinary public id shouldn't contain file extensions, otherwise Cloudinary url would contain doubled extension - Cloudinary adds extension to url to allow file conversion to arbitrary ...
python
{ "resource": "" }
q8543
StaticCloudinaryStorage._exists_with_etag
train
def _exists_with_etag(self, name, content): """ Checks whether a file with a name and a content is already uploaded to Cloudinary. Uses ETAG header and MD5 hash for the content comparison. """ url = self._get_url(name) response = requests.head(url) if response.sta...
python
{ "resource": "" }
q8544
StaticCloudinaryStorage._save
train
def _save(self, name, content): """ Saves only when a file with a name and a content is not already uploaded to Cloudinary. """ name = self.clean_name(name) # to change to UNIX style path on windows if necessary if not self._exists_with_etag(name, content): content.s...
python
{ "resource": "" }
q8545
BaseCart.add
train
def add(self, pk, quantity=1, **kwargs): """Add an item to the cart. If the item is already in the cart, then its quantity will be increased by `quantity` units. Parameters ---------- pk : str or int The primary key of the item. quantity : int-conver...
python
{ "resource": "" }
q8546
BaseCart.change_quantity
train
def change_quantity(self, pk, quantity): """Change the quantity of an item. Parameters ---------- pk : str or int The primary key of the item. quantity : int-convertible A new quantity. Raises ------ ItemNotInCart Negative...
python
{ "resource": "" }
q8547
BaseCart.remove
train
def remove(self, pk): """Remove an item from the cart. Parameters ---------- pk : str or int The primary key of the item. Raises ------ ItemNotInCart """ pk = str(pk) try: del self.items[pk] except KeyErro...
python
{ "resource": "" }
q8548
BaseCart.list_items
train
def list_items(self, sort_key=None, reverse=False): """Return a list of cart items. Parameters ---------- sort_key : func A function to customize the list order, same as the 'key' argument to the built-in :func:`sorted`. reverse: bool If set t...
python
{ "resource": "" }
q8549
BaseCart.encode
train
def encode(self, formatter=None): """Return a representation of the cart as a JSON-response. Parameters ---------- formatter : func, optional A function that accepts the cart representation and returns its formatted version. Returns ------- ...
python
{ "resource": "" }
q8550
BaseCart.create_items
train
def create_items(self, session_items): """Instantiate cart items from session data. The value returned by this method is used to populate the cart's `items` attribute. Parameters ---------- session_items : dict A dictionary of pk-quantity mappings (each pk i...
python
{ "resource": "" }
q8551
BaseCart.update
train
def update(self): """Update the cart. First this method updates attributes dependent on the cart's `items`, such as `total_price` or `item_count`. After that, it saves the new cart state to the session. Generally, you'll need to call this method by yourself, only when i...
python
{ "resource": "" }
q8552
BaseCart.count_items
train
def count_items(self, unique=True): """Count items in the cart. Parameters ---------- unique : bool-convertible, optional Returns ------- int If `unique` is truthy, then the result is the number of items in the cart. Otherwise, it's the s...
python
{ "resource": "" }
q8553
hill_climber
train
def hill_climber(objective_function, initial_array, lower_bound=-float('inf'), acceptance_criteria=None, max_iterations=10 ** 3): """ Implement a basic hill climbing algorithm. Has two stopping conditions: 1. Maximum number of iterati...
python
{ "resource": "" }
q8554
simulated_annealing
train
def simulated_annealing(objective_function, initial_array, initial_temperature=10 ** 4, cooldown_rate=0.7, acceptance_criteria=None, lower_bound=-float('inf'), max_iterations=1...
python
{ "resource": "" }
q8555
_events_available_in_scheduled_slot
train
def _events_available_in_scheduled_slot(events, slots, X, **kwargs): """ Constraint that ensures that an event is scheduled in slots for which it is available """ slot_availability_array = lpu.slot_availability_array(slots=slots, events=event...
python
{ "resource": "" }
q8556
_events_available_during_other_events
train
def _events_available_during_other_events( events, slots, X, summation_type=None, **kwargs ): """ Constraint that ensures that an event is not scheduled at the same time as another event for which it is unavailable. Unavailability of events is either because it is explicitly defined or because they ...
python
{ "resource": "" }
q8557
_upper_bound_on_event_overflow
train
def _upper_bound_on_event_overflow( events, slots, X, beta, summation_type=None, **kwargs ): """ This is an artificial constraint that is used by the objective function aiming to minimise the maximum overflow in a slot. """ label = 'Artificial upper bound constraint' for row, event in enumer...
python
{ "resource": "" }
q8558
heuristic
train
def heuristic(events, slots, objective_function=None, algorithm=heu.hill_climber, initial_solution=None, initial_solution_algorithm_kwargs={}, objective_function_algorithm_kwargs={}, **kwargs): """ Compute a schedu...
python
{ "resource": "" }
q8559
solution
train
def solution(events, slots, objective_function=None, solver=None, **kwargs): """Compute a schedule in solution form Parameters ---------- events : list or tuple of :py:class:`resources.Event` instances slots : list or tuple of :py:class:`resources.Slot` instances solver : pulp.s...
python
{ "resource": "" }
q8560
array
train
def array(events, slots, objective_function=None, solver=None, **kwargs): """Compute a schedule in array form Parameters ---------- events : list or tuple of :py:class:`resources.Event` instances slots : list or tuple of :py:class:`resources.Slot` instances objective_function : ...
python
{ "resource": "" }
q8561
schedule
train
def schedule(events, slots, objective_function=None, solver=None, **kwargs): """Compute a schedule in schedule form Parameters ---------- events : list or tuple of :py:class:`resources.Event` instances slots : list or tuple of :py:class:`resources.Slot` instances solver : pulp.s...
python
{ "resource": "" }
q8562
event_schedule_difference
train
def event_schedule_difference(old_schedule, new_schedule): """Compute the difference between two schedules from an event perspective Parameters ---------- old_schedule : list or tuple of :py:class:`resources.ScheduledItem` objects new_schedule : list or tuple of :py:class:`resource...
python
{ "resource": "" }
q8563
slot_schedule_difference
train
def slot_schedule_difference(old_schedule, new_schedule): """Compute the difference between two schedules from a slot perspective Parameters ---------- old_schedule : list or tuple of :py:class:`resources.ScheduledItem` objects new_schedule : list or tuple of :py:class:`resources.Sc...
python
{ "resource": "" }
q8564
array_violations
train
def array_violations(array, events, slots, beta=None): """Take a schedule in array form and return any violated constraints Parameters ---------- array : np.array a schedule in array form events : list or tuple of resources.Event instances slots : list or tup...
python
{ "resource": "" }
q8565
is_valid_array
train
def is_valid_array(array, events, slots): """Take a schedule in array form and return whether it is a valid solution for the given constraints Parameters ---------- array : np.array a schedule in array form events : list or tuple of resources.Event instances ...
python
{ "resource": "" }
q8566
is_valid_solution
train
def is_valid_solution(solution, events, slots): """Take a solution and return whether it is valid for the given constraints Parameters ---------- solution: list or tuple a schedule in solution form events : list or tuple of resources.Event instances slots...
python
{ "resource": "" }
q8567
solution_violations
train
def solution_violations(solution, events, slots): """Take a solution and return a list of violated constraints Parameters ---------- solution: list or tuple a schedule in solution form events : list or tuple of resources.Event instances slots : list or tuple ...
python
{ "resource": "" }
q8568
is_valid_schedule
train
def is_valid_schedule(schedule, events, slots): """Take a schedule and return whether it is a valid solution for the given constraints Parameters ---------- schedule : list or tuple a schedule in schedule form events : list or tuple of resources.Event instances ...
python
{ "resource": "" }
q8569
schedule_violations
train
def schedule_violations(schedule, events, slots): """Take a schedule and return a list of violated constraints Parameters ---------- schedule : list or tuple a schedule in schedule form events : list or tuple of resources.Event instances slots : list or tuple...
python
{ "resource": "" }
q8570
tag_array
train
def tag_array(events): """ Return a numpy array mapping events to tags - Rows corresponds to events - Columns correspond to tags """ all_tags = sorted(set(tag for event in events for tag in event.tags)) array = np.zeros((len(events), len(all_tags))) for row, event in enumerate(events): ...
python
{ "resource": "" }
q8571
session_array
train
def session_array(slots): """ Return a numpy array mapping sessions to slots - Rows corresponds to sessions - Columns correspond to slots """ # Flatten the list: this assumes that the sessions do not share slots sessions = sorted(set([slot.session for slot in slots])) array = np.zeros((...
python
{ "resource": "" }
q8572
slot_availability_array
train
def slot_availability_array(events, slots): """ Return a numpy array mapping events to slots - Rows corresponds to events - Columns correspond to stags Array has value 0 if event cannot be scheduled in a given slot (1 otherwise) """ array = np.ones((len(events), len(slots))) for ro...
python
{ "resource": "" }
q8573
event_availability_array
train
def event_availability_array(events): """ Return a numpy array mapping events to events - Rows corresponds to events - Columns correspond to events Array has value 0 if event cannot be scheduled at same time as other event (1 otherwise) """ array = np.ones((len(events), len(events))) ...
python
{ "resource": "" }
q8574
concurrent_slots
train
def concurrent_slots(slots): """ Yields all concurrent slot indices. """ for i, slot in enumerate(slots): for j, other_slot in enumerate(slots[i + 1:]): if slots_overlap(slot, other_slot): yield (i, j + i + 1)
python
{ "resource": "" }
q8575
_events_with_diff_tag
train
def _events_with_diff_tag(talk, tag_array): """ Return the indices of the events with no tag in common as tag """ event_categories = np.nonzero(tag_array[talk])[0] return np.nonzero(sum(tag_array.transpose()[event_categories]) == 0)[0]
python
{ "resource": "" }
q8576
solution_to_array
train
def solution_to_array(solution, events, slots): """Convert a schedule from solution to array form Parameters ---------- solution : list or tuple of tuples of event index and slot index for each scheduled item events : list or tuple of :py:class:`resources.Event` instances slots ...
python
{ "resource": "" }
q8577
solution_to_schedule
train
def solution_to_schedule(solution, events, slots): """Convert a schedule from solution to schedule form Parameters ---------- solution : list or tuple of tuples of event index and slot index for each scheduled item events : list or tuple of :py:class:`resources.Event` instances ...
python
{ "resource": "" }
q8578
schedule_to_array
train
def schedule_to_array(schedule, events, slots): """Convert a schedule from schedule to array form Parameters ---------- schedule : list or tuple of instances of :py:class:`resources.ScheduledItem` events : list or tuple of :py:class:`resources.Event` instances slots : list or tu...
python
{ "resource": "" }
q8579
array_to_schedule
train
def array_to_schedule(array, events, slots): """Convert a schedule from array to schedule form Parameters ---------- array : np.array An E by S array (X) where E is the number of events and S the number of slots. Xij is 1 if event i is scheduled in slot j and zero otherwise ...
python
{ "resource": "" }
q8580
add_line
train
def add_line(self, line, source, *lineno): """Append one line of generated reST to the output.""" if 'conference_scheduler.scheduler' in source: module = 'scheduler' else: module = 'resources' rst[module].append(line) self.directive.result.append(self.indent + line, source, *lineno)
python
{ "resource": "" }
q8581
efficiency_capacity_demand_difference
train
def efficiency_capacity_demand_difference(slots, events, X, **kwargs): """ A function that calculates the total difference between demand for an event and the slot capacity it is scheduled in. """ overflow = 0 for row, event in enumerate(events): for col, slot in enumerate(slots): ...
python
{ "resource": "" }
q8582
get_initial_array
train
def get_initial_array(events, slots, seed=None): """ Obtain a random initial array. """ if seed is not None: np.random.seed(seed) m = len(events) n = len(slots) X = np.zeros((m, n)) for i, row in enumerate(X): X[i, i] = 1 np.random.shuffle(X) return X
python
{ "resource": "" }
q8583
fcs
train
def fcs(bits): ''' Append running bitwise FCS CRC checksum to end of generator ''' fcs = FCS() for bit in bits: yield bit fcs.update_bit(bit) # test = bitarray() # for byte in (digest & 0xff, digest >> 8): # print byte # for i in range(8): # b = (byte >> i) & 1 == 1 # test.append(b) # yield b # appe...
python
{ "resource": "" }
q8584
modulate
train
def modulate(data): ''' Generate Bell 202 AFSK samples for the given symbol generator Consumes raw wire symbols and produces the corresponding AFSK samples. ''' seconds_per_sample = 1.0 / audiogen.sampler.FRAME_RATE phase, seconds, bits = 0, 0, 0 # construct generators clock = (x / BAUD_RATE for x in itertoo...
python
{ "resource": "" }
q8585
HackerNews._get_sync
train
def _get_sync(self, url): """Internal method used for GET requests Args: url (str): URL to fetch Returns: Individual URL request's response Raises: HTTPError: If HTTP request failed. """ response = self.session.get(url) if resp...
python
{ "resource": "" }
q8586
HackerNews._get_async
train
async def _get_async(self, url, session): """Asynchronous internal method used for GET requests Args: url (str): URL to fetch session (obj): aiohttp client session for async loop Returns: data (obj): Individual URL request's response corountine """ ...
python
{ "resource": "" }
q8587
HackerNews._async_loop
train
async def _async_loop(self, urls): """Asynchronous internal method used to request multiple URLs Args: urls (list): URLs to fetch Returns: responses (obj): All URL requests' response coroutines """ results = [] async with aiohttp.ClientSession( ...
python
{ "resource": "" }
q8588
HackerNews._run_async
train
def _run_async(self, urls): """Asynchronous event loop execution Args: urls (list): URLs to fetch Returns: results (obj): All URL requests' responses """ loop = asyncio.get_event_loop() results = loop.run_until_complete(self._async_loop(urls)) ...
python
{ "resource": "" }
q8589
HackerNews.get_item
train
def get_item(self, item_id, expand=False): """Returns Hacker News `Item` object. Fetches the data from url: https://hacker-news.firebaseio.com/v0/item/<item_id>.json e.g. https://hacker-news.firebaseio.com/v0/item/69696969.json Args: item_id (int or string): Un...
python
{ "resource": "" }
q8590
HackerNews.get_items_by_ids
train
def get_items_by_ids(self, item_ids, item_type=None): """Given a list of item ids, return all the Item objects Args: item_ids (obj): List of item IDs to query item_type (str): (optional) Item type to filter results with Returns: List of `Item` objects for gi...
python
{ "resource": "" }
q8591
HackerNews.get_user
train
def get_user(self, user_id, expand=False): """Returns Hacker News `User` object. Fetches data from the url: https://hacker-news.firebaseio.com/v0/user/<user_id>.json e.g. https://hacker-news.firebaseio.com/v0/user/pg.json Args: user_id (string): unique user id ...
python
{ "resource": "" }
q8592
HackerNews.get_users_by_ids
train
def get_users_by_ids(self, user_ids): """ Given a list of user ids, return all the User objects """ urls = [urljoin(self.user_url, F"{i}.json") for i in user_ids] result = self._run_async(urls=urls) return [User(r) for r in result if r]
python
{ "resource": "" }
q8593
HackerNews.top_stories
train
def top_stories(self, raw=False, limit=None): """Returns list of item ids of current top stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to represent all objects in raw json. Returns: ...
python
{ "resource": "" }
q8594
HackerNews.new_stories
train
def new_stories(self, raw=False, limit=None): """Returns list of item ids of current new stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: ...
python
{ "resource": "" }
q8595
HackerNews.ask_stories
train
def ask_stories(self, raw=False, limit=None): """Returns list of item ids of latest Ask HN stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: ...
python
{ "resource": "" }
q8596
HackerNews.show_stories
train
def show_stories(self, raw=False, limit=None): """Returns list of item ids of latest Show HN stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: ...
python
{ "resource": "" }
q8597
HackerNews.job_stories
train
def job_stories(self, raw=False, limit=None): """Returns list of item ids of latest Job stories Args: limit (int): specifies the number of stories to be returned. raw (bool): Flag to indicate whether to transform all objects into raw json. Returns: ...
python
{ "resource": "" }
q8598
HackerNews.get_max_item
train
def get_max_item(self, expand=False): """The current largest item id Fetches data from URL: https://hacker-news.firebaseio.com/v0/maxitem.json Args: expand (bool): Flag to indicate whether to transform all IDs into objects. Returns: ...
python
{ "resource": "" }
q8599
HackerNews.get_last
train
def get_last(self, num=10): """Returns last `num` of HN stories Downloads all the HN articles and returns them as Item objects Returns: `list` object containing ids of HN stories. """ max_item = self.get_max_item() urls = [urljoin(self.item_url, F"{i}.json"...
python
{ "resource": "" }