_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q255400
BluezProvider.disconnect_devices
validation
def disconnect_devices(self, service_uuids=[]): """Disconnect any connected devices that have the specified list of service UUIDs. The default is an empty list which means all devices are disconnected. """ service_uuids = set(service_uuids) for device in self.list_devices(): # Skip devices that aren't connected. if not device.is_connected: continue device_uuids = set(map(lambda x:
python
{ "resource": "" }
q255401
BluezProvider._get_objects
validation
def _get_objects(self, interface, parent_path='/org/bluez'): """Return a list of all bluez DBus objects that implement the requested interface name and are under the specified path. The default is to search devices under the root of all bluez objects. """ # Iterate through all the objects in bluez's DBus hierarchy and return # any that implement the requested interface under the specified path.
python
{ "resource": "" }
q255402
BluezProvider._get_objects_by_path
validation
def _get_objects_by_path(self, paths): """Return a list of all bluez DBus objects from the provided list of paths. """
python
{ "resource": "" }
q255403
BluezProvider._print_tree
validation
def _print_tree(self): """Print tree of all bluez objects, useful for debugging.""" # This is based on the bluez sample code get-managed-objects.py. objects = self._bluez.GetManagedObjects() for path in objects.keys(): print("[ %s ]" % (path)) interfaces = objects[path] for interface in interfaces.keys(): if interface in ["org.freedesktop.DBus.Introspectable", "org.freedesktop.DBus.Properties"]:
python
{ "resource": "" }
q255404
Provider.find_device
validation
def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC): """Return the first device that advertises the specified service UUIDs or has the specified name. Will wait up to timeout_sec seconds for the device to be found, and if the timeout is zero then it will not wait at all and immediately return a result. When no device is found a value of None is returned. """ start = time.time() while True: # Call find_devices and grab the first result if any are found.
python
{ "resource": "" }
q255405
CoreBluetoothMetadata.get_all
validation
def get_all(self, cbobjects): """Retrieve a list of metadata objects associated with the specified list of CoreBluetooth objects. If an object cannot be found then an exception is thrown. """ try: with self._lock: return [self._metadata[x] for x in cbobjects] except KeyError: # Note that if this error gets thrown then
python
{ "resource": "" }
q255406
CoreBluetoothMetadata.add
validation
def add(self, cbobject, metadata): """Add the specified CoreBluetooth item with the associated metadata if it doesn't already exist. Returns the newly created or preexisting metadata item. """ with self._lock:
python
{ "resource": "" }
q255407
CoreBluetoothMetadata.remove
validation
def remove(self, cbobject): """Remove any metadata associated with the provided CoreBluetooth object.
python
{ "resource": "" }
q255408
cbuuid_to_uuid
validation
def cbuuid_to_uuid(cbuuid): """Convert Objective-C CBUUID type to native Python UUID type.""" data = cbuuid.data().bytes() template = '{:0>8}-0000-1000-8000-00805f9b34fb' if len(data) <= 4 else '{:0>32}'
python
{ "resource": "" }
q255409
Colorific.set_color
validation
def set_color(self, r, g, b): """Set the red, green, blue color of the bulb.""" # See more details on the bulb's protocol from this guide: # https://learn.adafruit.com/reverse-engineering-a-bluetooth-low-energy-light-bulb/overview command = '\x58\x01\x03\x01\xFF\x00{0}{1}{2}'.format(chr(r & 0xFF),
python
{ "resource": "" }
q255410
get_provider
validation
def get_provider(): """Return an instance of the BLE provider for the current platform.""" global _provider # Set the provider based on the current platform. if _provider is None: if sys.platform.startswith('linux'): # Linux platform from .bluez_dbus.provider import BluezProvider
python
{ "resource": "" }
q255411
toBigInt
validation
def toBigInt(byteArray): """Convert the byte array to a BigInteger""" array = byteArray[::-1] # reverse array out = 0 for key, value in enumerate(array):
python
{ "resource": "" }
q255412
GooglePlayAPI.encryptPassword
validation
def encryptPassword(self, login, passwd): """Encrypt credentials using the google publickey, with the RSA algorithm""" # structure of the binary key: # # *-------------------------------------------------------* # | modulus_length | modulus | exponent_length | exponent | # *-------------------------------------------------------* # # modulus_length and exponent_length are uint32 binaryKey = b64decode(config.GOOGLE_PUBKEY) # modulus i = utils.readInt(binaryKey, 0) modulus = utils.toBigInt(binaryKey[4:][0:i]) # exponent j = utils.readInt(binaryKey, i + 4) exponent = utils.toBigInt(binaryKey[i + 8:][0:j]) # calculate SHA1 of the pub key digest = hashes.Hash(hashes.SHA1(), backend=default_backend())
python
{ "resource": "" }
q255413
GooglePlayAPI.getHeaders
validation
def getHeaders(self, upload_fields=False): """Return the default set of request headers, which can later be expanded, based on the request type""" if upload_fields: headers = self.deviceBuilder.getDeviceUploadHeaders() else: headers = self.deviceBuilder.getBaseHeaders() if self.gsfId is not None: headers["X-DFE-Device-Id"] = "{0:x}".format(self.gsfId) if self.authSubToken is not None: headers["Authorization"] = "GoogleLogin auth=%s" % self.authSubToken
python
{ "resource": "" }
q255414
GooglePlayAPI.search
validation
def search(self, query): """ Search the play store for an app. nb_result (int): is the maximum number of result to be returned offset (int): is used to take result starting from an index. """ if self.authSubToken is None: raise LoginError("You need to login before executing any request")
python
{ "resource": "" }
q255415
GooglePlayAPI.details
validation
def details(self, packageName): """Get app details from a package name. packageName is the app unique ID (usually starting with 'com.').""" path = DETAILS_URL + "?doc={}".format(requests.utils.quote(packageName))
python
{ "resource": "" }
q255416
GooglePlayAPI.bulkDetails
validation
def bulkDetails(self, packageNames): """Get several apps details from a list of package names. This is much more efficient than calling N times details() since it requires only one request. If an item is not found it returns an empty object instead of throwing a RequestError('Item not found') like the details() function Args: packageNames (list): a list of app IDs (usually starting with 'com.'). Returns: a list of dictionaries
python
{ "resource": "" }
q255417
GooglePlayAPI.list
validation
def list(self, cat, ctr=None, nb_results=None, offset=None): """List all possible subcategories for a specific category. If also a subcategory is provided, list apps from this category. Args: cat (str): category id ctr (str): subcategory id nb_results (int): if a subcategory is specified, limit number of results to this number offset (int): if a subcategory is specified, start counting from this result Returns: A list of categories. If subcategory is specified, a list of apps in this category. """ path = LIST_URL + "?c=3&cat={}".format(requests.utils.quote(cat)) if ctr is not None: path += "&ctr={}".format(requests.utils.quote(ctr)) if nb_results is not None: path += "&n={}".format(requests.utils.quote(str(nb_results))) if offset is not None: path += "&o={}".format(requests.utils.quote(str(offset))) data = self.executeRequestApi2(path) clusters = [] docs = [] if ctr is None: #
python
{ "resource": "" }
q255418
GooglePlayAPI.reviews
validation
def reviews(self, packageName, filterByDevice=False, sort=2, nb_results=None, offset=None): """Browse reviews for an application Args: packageName (str): app unique ID. filterByDevice (bool): filter results for current device sort (int): sorting criteria (values are unknown) nb_results (int): max number of reviews to return offset (int): return reviews starting from an offset value Returns: dict object containing all the protobuf data returned from the api """ # TODO: select the number of reviews to return
python
{ "resource": "" }
q255419
GooglePlayAPI.delivery
validation
def delivery(self, packageName, versionCode=None, offerType=1, downloadToken=None, expansion_files=False): """Download an already purchased app. Args: packageName (str): app unique ID (usually starting with 'com.') versionCode (int): version to download offerType (int): different type of downloads (mostly unused for apks) downloadToken (str): download token returned by 'purchase' API progress_bar (bool): wether or not to print a progress bar to stdout Returns: Dictionary containing apk data and a list of expansion files. As stated in android documentation, there can be at most 2 expansion files, one with main content, and one for patching the main content. Their names should follow this format: [main|patch].<expansion-version>.<package-name>.obb Data to build this name string is provided in the dict object. For more info check https://developer.android.com/google/play/expansion-files.html """ if versionCode is None: # pick up latest version versionCode = self.details(packageName).get('versionCode') params = {'ot': str(offerType), 'doc': packageName, 'vc': str(versionCode)} headers = self.getHeaders() if downloadToken is not None: params['dtok'] = downloadToken response = requests.get(DELIVERY_URL, headers=headers, params=params, verify=ssl_verify, timeout=60, proxies=self.proxies_config) response = googleplay_pb2.ResponseWrapper.FromString(response.content) if response.commands.displayErrorMessage != "": raise RequestError(response.commands.displayErrorMessage) elif response.payload.deliveryResponse.appDeliveryData.downloadUrl == "": raise RequestError('App not purchased') else: result = {}
python
{ "resource": "" }
q255420
http_connection
validation
def http_connection(timeout): """ Decorator function that injects a requests.Session instance into the decorated function's actual parameters if not given. """ def wrapper(f): def wrapped(*args, **kwargs): if not ('connection' in kwargs) or not kwargs['connection']: connection = requests.Session() kwargs['connection'] = connection else: connection = kwargs['connection']
python
{ "resource": "" }
q255421
FirebaseTokenGenerator.create_token
validation
def create_token(self, data, options=None): """ Generates a secure authentication token. Our token format follows the JSON Web Token (JWT) standard: header.claims.signature Where: 1) 'header' is a stringified, base64-encoded JSON object containing version and algorithm information. 2) 'claims' is a stringified, base64-encoded JSON object containing a set of claims: Library-generated claims: 'iat' -> The issued at time in seconds since the epoch as a number 'd' -> The arbitrary JSON object supplied by the user. User-supplied claims (these are all optional): 'exp' (optional) -> The expiration time of this token, as a number of seconds since the epoch. 'nbf' (optional) -> The 'not before' time before which the token should be rejected (seconds since the epoch) 'admin' (optional) -> If set to true, this client will bypass all security rules (use this to authenticate servers) 'debug' (optional) -> 'set to true to make this client receive debug information about security rule execution. 'simulate' (optional, internal-only for now) -> Set to true to neuter all API operations (listens / puts will run security rules but not actually write or return data).
python
{ "resource": "" }
q255422
FirebaseAuthentication.get_user
validation
def get_user(self): """ Method that gets the authenticated user. The returning user has the token, email and the provider data. """
python
{ "resource": "" }
q255423
FirebaseApplication._build_endpoint_url
validation
def _build_endpoint_url(self, url, name=None): """ Method that constructs a full url with the given url and the snapshot name. Example: full_url = _build_endpoint_url('/users', '1') full_url => 'http://firebase.localhost/users/1.json' """ if not url.endswith(self.URL_SEPERATOR):
python
{ "resource": "" }
q255424
FirebaseApplication._authenticate
validation
def _authenticate(self, params, headers): """ Method that simply adjusts authentication credentials for the request. `params` is the querystring of the request. `headers` is the header of the request. If auth instance is not provided to this class, this method simply returns without doing anything.
python
{ "resource": "" }
q255425
FirebaseApplication.get
validation
def get(self, url, name, params=None, headers=None, connection=None): """ Synchronous GET request. """ if name is None: name = '' params = params or {} headers = headers or {} endpoint =
python
{ "resource": "" }
q255426
FirebaseApplication.get_async
validation
def get_async(self, url, name, callback=None, params=None, headers=None): """ Asynchronous GET request with the process pool. """ if name is None: name = '' params = params or {} headers = headers or {} endpoint =
python
{ "resource": "" }
q255427
FirebaseApplication.put
validation
def put(self, url, name, data, params=None, headers=None, connection=None): """ Synchronous PUT request. There will be no returning output from the server, because the request will be made with ``silent`` parameter. ``data`` must be a JSONable value.
python
{ "resource": "" }
q255428
FirebaseApplication.put_async
validation
def put_async(self, url, name, data, callback=None, params=None, headers=None): """ Asynchronous PUT request with the process pool. """ if name is None: name = '' params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, name) self._authenticate(params, headers) data
python
{ "resource": "" }
q255429
FirebaseApplication.post_async
validation
def post_async(self, url, data, callback=None, params=None, headers=None): """ Asynchronous POST request with the process pool. """ params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, None) self._authenticate(params, headers) data = json.dumps(data, cls=JSONEncoder)
python
{ "resource": "" }
q255430
FirebaseApplication.delete
validation
def delete(self, url, name, params=None, headers=None, connection=None): """ Synchronous DELETE request. ``data`` must be a JSONable value. """ if not name: name = '' params = params or {} headers = headers or {}
python
{ "resource": "" }
q255431
FirebaseApplication.delete_async
validation
def delete_async(self, url, name, callback=None, params=None, headers=None): """ Asynchronous DELETE request with the process pool. """ if not name: name = '' params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url,
python
{ "resource": "" }
q255432
do_filter
validation
def do_filter(qs, keywords, exclude=False): """ Filter queryset based on keywords. Support for multiple-selected parent values. """ and_q = Q() for keyword, value in iteritems(keywords): try: values = value.split(",") if len(values) > 0: or_q = Q() for value in values:
python
{ "resource": "" }
q255433
filterchain_all
validation
def filterchain_all(request, app, model, field, foreign_key_app_name, foreign_key_model_name, foreign_key_field_name, value): """Returns filtered results followed by excluded results below.""" model_class = get_model(app, model) keywords = get_keywords(field, value) # SECURITY: Make sure all smart selects requests are opt-in foreign_model_class = get_model(foreign_key_app_name, foreign_key_model_name) if not any([(isinstance(f, ChainedManyToManyField) or isinstance(f, ChainedForeignKey)) for f in foreign_model_class._meta.get_fields()]): raise PermissionDenied("Smart select disallowed") # filter queryset using limit_choices_to limit_choices_to = get_limit_choices_to(foreign_key_app_name, foreign_key_model_name, foreign_key_field_name) queryset = get_queryset(model_class, limit_choices_to=limit_choices_to) filtered = list(do_filter(queryset, keywords)) # Sort results if model doesn't include a default ordering. if not getattr(model_class._meta, 'ordering', False): sort_results(list(filtered))
python
{ "resource": "" }
q255434
ChainedSelect._get_available_choices
validation
def _get_available_choices(self, queryset, value): """ get possible choices for selection """ item = queryset.filter(pk=value).first() if item: try: pk = getattr(item, self.chained_model_field + "_id") filter = {self.chained_model_field: pk} except AttributeError: try: # maybe m2m? pks = getattr(item, self.chained_model_field).all().values_list('pk', flat=True)
python
{ "resource": "" }
q255435
AlgoliaIndex.get_raw_record
validation
def get_raw_record(self, instance, update_fields=None): """ Gets the raw record. If `update_fields` is set, the raw record will be build with only the objectID and the given fields. Also, `_geoloc` and `_tags` will not be included. """ tmp = {'objectID': self.objectID(instance)} if update_fields: if isinstance(update_fields, str): update_fields = (update_fields,) for elt in update_fields: key = self.__translate_fields.get(elt, None) if key: tmp[key] = self.__named_fields[key](instance) else: for key, value in self.__named_fields.items(): tmp[key] = value(instance) if self.geo_field: loc = self.geo_field(instance) if isinstance(loc, tuple): tmp['_geoloc'] = {'lat': loc[0], 'lng': loc[1]} elif isinstance(loc, dict):
python
{ "resource": "" }
q255436
AlgoliaIndex._should_really_index
validation
def _should_really_index(self, instance): """Return True if according to should_index the object should be indexed.""" if self._should_index_is_method: is_method = inspect.ismethod(self.should_index) try: count_args = len(inspect.signature(self.should_index).parameters) except AttributeError: # noinspection PyDeprecation count_args = len(inspect.getargspec(self.should_index).args) if is_method or count_args is 1: # bound method, call with instance return self.should_index(instance) else: # unbound method, simply call without arguments return self.should_index() else: # property/attribute/Field, evaluate as bool attr_type = type(self.should_index) if attr_type is DeferredAttribute: attr_value = self.should_index.__get__(instance, None) elif attr_type is str:
python
{ "resource": "" }
q255437
AlgoliaIndex.get_settings
validation
def get_settings(self): """Returns the settings of the index.""" try: logger.info('GET SETTINGS ON %s', self.index_name) return self.__index.get_settings() except AlgoliaException as e: if DEBUG:
python
{ "resource": "" }
q255438
AlgoliaIndex.set_settings
validation
def set_settings(self): """Applies the settings to the index.""" if not self.settings: return try: self.__index.set_settings(self.settings) logger.info('APPLY SETTINGS ON %s', self.index_name) except AlgoliaException as e:
python
{ "resource": "" }
q255439
AlgoliaEngine.register
validation
def register(self, model, index_cls=AlgoliaIndex, auto_indexing=None): """ Registers the given model with Algolia engine. If the given model is already registered with Algolia engine, a RegistrationError will be raised. """ # Check for existing registration. if self.is_registered(model): raise RegistrationError( '{} is already registered with Algolia engine'.format(model)) # Perform the registration. if not issubclass(index_cls, AlgoliaIndex): raise RegistrationError( '{} should be a subclass of AlgoliaIndex'.format(index_cls)) index_obj = index_cls(model,
python
{ "resource": "" }
q255440
AlgoliaEngine.unregister
validation
def unregister(self, model): """ Unregisters the given model with Algolia engine. If the given model is not registered with Algolia engine, a RegistrationError will be raised. """ if not self.is_registered(model): raise RegistrationError( '{} is not registered with Algolia engine'.format(model)) #
python
{ "resource": "" }
q255441
AlgoliaEngine.get_adapter
validation
def get_adapter(self, model): """Returns the adapter associated with the given model.""" if not self.is_registered(model):
python
{ "resource": "" }
q255442
AlgoliaEngine.__post_save_receiver
validation
def __post_save_receiver(self, instance, **kwargs): """Signal handler for when a registered model has been saved."""
python
{ "resource": "" }
q255443
AlgoliaEngine.__pre_delete_receiver
validation
def __pre_delete_receiver(self, instance, **kwargs): """Signal handler for when a registered model has been deleted."""
python
{ "resource": "" }
q255444
decode
validation
def decode(geohash): """ Decode geohash, returning two strings with latitude and longitude containing only relevant digits and with trailing zeroes removed. """ lat, lon, lat_err, lon_err = decode_exactly(geohash)
python
{ "resource": "" }
q255445
encode
validation
def encode(latitude, longitude, precision=12): """ Encode a position given in float arguments latitude, longitude to a geohash which will have the character count precision. """ lat_interval, lon_interval = (-90.0, 90.0), (-180.0, 180.0) geohash = [] bits = [ 16, 8, 4, 2, 1 ] bit = 0 ch = 0 even = True while len(geohash) < precision: if even: mid = (lon_interval[0] + lon_interval[1]) / 2 if longitude > mid: ch |= bits[bit] lon_interval = (mid, lon_interval[1]) else: lon_interval = (lon_interval[0], mid) else: mid = (lat_interval[0] + lat_interval[1]) / 2 if latitude > mid:
python
{ "resource": "" }
q255446
pad_to
validation
def pad_to(unpadded, target_len): """ Pad a string to the target length in characters, or return the original string if it's longer than the target length. """
python
{ "resource": "" }
q255447
normalize_cols
validation
def normalize_cols(table): """ Pad short rows to the length of the longest row to help render "jagged" CSV files """ longest_row_len = max([len(row) for row in table])
python
{ "resource": "" }
q255448
pad_cells
validation
def pad_cells(table): """Pad each cell to the size of the largest cell in its column.""" col_sizes = [max(map(len, col)) for col in zip(*table)] for row in table:
python
{ "resource": "" }
q255449
horiz_div
validation
def horiz_div(col_widths, horiz, vert, padding): """ Create the column dividers for a table with given column widths. col_widths: list of column widths horiz: the character to use for
python
{ "resource": "" }
q255450
add_dividers
validation
def add_dividers(row, divider, padding): """Add dividers and padding to a row of cells and return a string."""
python
{ "resource": "" }
q255451
md_table
validation
def md_table(table, *, padding=DEFAULT_PADDING, divider='|', header_div='-'): """ Convert a 2D array of items into a Markdown table. padding: the number of padding spaces on either side of each divider divider: the vertical divider to place between columns header_div: the horizontal divider to place between the header row and
python
{ "resource": "" }
q255452
baseId
validation
def baseId(resource_id, return_version=False): """Calculate base id and version from a resource id. :params resource_id: Resource id. :params return_version: (optional) True if You need version, returns (resource_id, version). """ version = 0 resource_id = resource_id + 0xC4000000 # 3288334336 # TODO: version is broken due ^^, needs refactoring while resource_id > 0x01000000: # 16777216 version += 1 if version == 1: resource_id -= 0x80000000 # 2147483648 # 0x50000000 # 1342177280 ? || 0x2000000 # 33554432
python
{ "resource": "" }
q255453
Core.cardInfo
validation
def cardInfo(self, resource_id): """Return card info. :params resource_id: Resource id. """ # TODO: add referer to headers (futweb) base_id = baseId(resource_id) if base_id in self.players: return self.players[base_id]
python
{ "resource": "" }
q255454
Core.search
validation
def search(self, ctype, level=None, category=None, assetId=None, defId=None, min_price=None, max_price=None, min_buy=None, max_buy=None, league=None, club=None, position=None, zone=None, nationality=None, rare=False, playStyle=None, start=0, page_size=itemsPerPage['transferMarket'], fast=False): """Prepare search request, send and return parsed data as a dict. :param ctype: [development / ? / ?] Card type. :param level: (optional) [?/?/gold] Card level. :param category: (optional) [fitness/?/?] Card category. :param assetId: (optional) Asset id. :param defId: (optional) Definition id. :param min_price: (optional) Minimal price. :param max_price: (optional) Maximum price. :param min_buy: (optional) Minimal buy now price. :param max_buy: (optional) Maximum buy now price. :param league: (optional) League id. :param club: (optional) Club id. :param position: (optional) Position. :param nationality: (optional) Nation id. :param rare: (optional) [boolean] True for searching special cards. :param playStyle: (optional) Play style. :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n) :param page_size: (optional) Page size (items per page). """ # TODO: add "search" alias # TODO: generator method = 'GET' url = 'transfermarket' # pinEvents if start == 0: events = [self.pin.event('page_view', 'Hub - Transfers'), self.pin.event('page_view', 'Transfer Market Search')] self.pin.send(events, fast=fast) params = { 'start': start, 'num': page_size, 'type': ctype, # "type" namespace is reserved in python } if level: params['lev'] = level if category: params['cat'] = category if assetId: params['maskedDefId'] = assetId
python
{ "resource": "" }
q255455
Core.bid
validation
def bid(self, trade_id, bid, fast=False): """Make a bid. :params trade_id: Trade id. :params bid: Amount of credits You want to spend. :params fast: True for fastest bidding (skips trade status & credits check). """ method = 'PUT' url = 'trade/%s/bid' % trade_id if not fast: rc = self.tradeStatus(trade_id)[0] # don't bid if current bid is equal or greater than our max bid if rc['currentBid'] >= bid or self.credits < bid: return False # TODO: add exceptions data = {'bid': bid} try:
python
{ "resource": "" }
q255456
Core.club
validation
def club(self, sort='desc', ctype='player', defId='', start=0, count=None, page_size=itemsPerPage['club'], level=None, category=None, assetId=None, league=None, club=None, position=None, zone=None, nationality=None, rare=False, playStyle=None): """Return items in your club, excluding consumables. :param ctype: [development / ? / ?] Card type. :param level: (optional) [?/?/gold] Card level. :param category: (optional) [fitness/?/?] Card category. :param assetId: (optional) Asset id. :param defId: (optional) Definition id. :param min_price: (optional) Minimal price. :param max_price: (optional) Maximum price. :param min_buy: (optional) Minimal buy now price. :param max_buy: (optional) Maximum buy now price. :param league: (optional) League id. :param club: (optional) Club id. :param position: (optional) Position. :param nationality: (optional) Nation id. :param rare: (optional) [boolean] True for searching special cards. :param playStyle: (optional) Play style. :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n) :param page_size: (optional) Page size (items per page) """ method = 'GET' url = 'club' if count: # backward compatibility, will be removed in future page_size = count params = {'sort': sort, 'type': ctype, 'defId': defId, 'start': start, 'count': page_size} if level: params['level'] = level if category: params['cat'] = category if assetId: params['maskedDefId'] = assetId if league: params['leag'] = league if club: params['team'] = club if position: params['pos'] = position if zone: params['zone'] = zone
python
{ "resource": "" }
q255457
Core.clubStaff
validation
def clubStaff(self): """Return staff in your club.""" method = 'GET' url = 'club/stats/staff'
python
{ "resource": "" }
q255458
Core.clubConsumables
validation
def clubConsumables(self, fast=False): """Return all consumables from club.""" method = 'GET' url = 'club/consumables/development' rc = self.__request__(method, url) events = [self.pin.event('page_view', 'Hub - Club')] self.pin.send(events, fast=fast) events = [self.pin.event('page_view', 'Club - Consumables')] self.pin.send(events,
python
{ "resource": "" }
q255459
Core.squad
validation
def squad(self, squad_id=0, persona_id=None): """Return a squad. :params squad_id: Squad id. """ method = 'GET' url = 'squad/%s/user/%s' % (squad_id, persona_id or self.persona_id) # pinEvents events = [self.pin.event('page_view', 'Hub - Squads')] self.pin.send(events) # TODO: ability to return other info than players only
python
{ "resource": "" }
q255460
Core.tradeStatus
validation
def tradeStatus(self, trade_id): """Return trade status. :params trade_id: Trade id. """ method = 'GET' url = 'trade/status' if not isinstance(trade_id, (list, tuple)): trade_id = (trade_id,) trade_id = (str(i) for i in trade_id)
python
{ "resource": "" }
q255461
Core.tradepile
validation
def tradepile(self): """Return items in tradepile.""" method = 'GET' url = 'tradepile' rc = self.__request__(method, url) # pinEvents events = [self.pin.event('page_view', 'Hub -
python
{ "resource": "" }
q255462
Core.sell
validation
def sell(self, item_id, bid, buy_now, duration=3600, fast=False): """Start auction. Returns trade_id. :params item_id: Item id. :params bid: Stard bid. :params buy_now: Buy now price. :params duration: Auction duration in seconds (Default: 3600).
python
{ "resource": "" }
q255463
Core.quickSell
validation
def quickSell(self, item_id): """Quick sell. :params item_id: Item id. """ method = 'DELETE' url = 'item' if not isinstance(item_id, (list, tuple)): item_id = (item_id,) item_id = (str(i) for i in item_id)
python
{ "resource": "" }
q255464
Core.watchlistDelete
validation
def watchlistDelete(self, trade_id): """Remove cards from watchlist. :params trade_id: Trade id. """ method = 'DELETE' url = 'watchlist' if not isinstance(trade_id, (list, tuple)): trade_id = (trade_id,) trade_id =
python
{ "resource": "" }
q255465
Core.tradepileDelete
validation
def tradepileDelete(self, trade_id): # item_id instead of trade_id? """Remove card from tradepile. :params trade_id: Trade id. """ method = 'DELETE' url = 'trade/%s' % trade_id
python
{ "resource": "" }
q255466
Core.sendToWatchlist
validation
def sendToWatchlist(self, trade_id): """Send to watchlist. :params trade_id: Trade id. """
python
{ "resource": "" }
q255467
Core.sendToSbs
validation
def sendToSbs(self, challenge_id, item_id): """Send card FROM CLUB to first free slot in sbs squad.""" # TODO?: multiple item_ids method = 'PUT' url = 'sbs/challenge/%s/squad' % challenge_id squad = self.sbsSquad(challenge_id) players = [] moved = False n = 0 for i in squad['squad']['players']: if i['itemData']['id'] == item_id: # item already in sbs
python
{ "resource": "" }
q255468
Core.applyConsumable
validation
def applyConsumable(self, item_id, resource_id): """Apply consumable on player. :params item_id: Item id of player. :params resource_id: Resource id of consumable. """ # TODO: catch exception when consumable is not found etc. # TODO: multiple players like in quickSell
python
{ "resource": "" }
q255469
Core.messages
validation
def messages(self): """Return active messages.""" method = 'GET' url = 'activeMessage' rc = self.__request__(method, url) # try: # return rc['activeMessage'] # except:
python
{ "resource": "" }
q255470
EAHashingAlgorithm.num2hex
validation
def num2hex(self, num): ''' Convert a decimal number to hexadecimal ''' temp = '' for i in range(0, 4): x = self.hexChars[ ( num >> (i * 8 + 4) ) & 0x0F ]
python
{ "resource": "" }
q255471
logger
validation
def logger(name=None, save=False): """Init and configure logger.""" logger = logging.getLogger(name) if save: logformat = '%(asctime)s [%(levelname)s] [%(name)s] %(funcName)s: %(message)s (line %(lineno)d)' log_file_path = 'fut.log' # TODO: define logpath open(log_file_path, 'w').write('') # remove old logs logger.setLevel(logging.DEBUG)
python
{ "resource": "" }
q255472
_ThreadImpl.run
validation
def run(self): """ Runs its worker method. This method will be terminated once its parent's is_running property turns False. """ while self._base.is_running:
python
{ "resource": "" }
q255473
Component2DImage.represent_pixel_location
validation
def represent_pixel_location(self): """ Returns a NumPy array that represents the 2D pixel location, which is defined by PFNC, of the original image data. You may use the returned NumPy array for a calculation to map the
python
{ "resource": "" }
q255474
ImageAcquirer.start_image_acquisition
validation
def start_image_acquisition(self): """ Starts image acquisition. :return: None. """ if not self._create_ds_at_connection: self._setup_data_streams() # num_required_buffers = self._num_buffers for data_stream in self._data_streams: try: num_buffers = data_stream.buffer_announce_min if num_buffers < num_required_buffers: num_buffers = num_required_buffers except InvalidParameterException as e: num_buffers = num_required_buffers self._logger.debug(e, exc_info=True) if data_stream.defines_payload_size(): buffer_size = data_stream.payload_size else: buffer_size = self.device.node_map.PayloadSize.value raw_buffers = self._create_raw_buffers( num_buffers, buffer_size ) buffer_tokens = self._create_buffer_tokens( raw_buffers ) self._announced_buffers = self._announce_buffers( data_stream=data_stream, _buffer_tokens=buffer_tokens ) self._queue_announced_buffers( data_stream=data_stream, buffers=self._announced_buffers ) # Reset the number of images to acquire. try: acq_mode = self.device.node_map.AcquisitionMode.value if acq_mode == 'Continuous': num_images_to_acquire = -1 elif acq_mode == 'SingleFrame': num_images_to_acquire = 1 elif acq_mode == 'MultiFrame': num_images_to_acquire = self.device.node_map.AcquisitionFrameCount.value else: num_images_to_acquire = -1 except LogicalErrorException as e: # The node doesn't exist. num_images_to_acquire = -1
python
{ "resource": "" }
q255475
ImageAcquirer.stop_image_acquisition
validation
def stop_image_acquisition(self): """ Stops image acquisition. :return: None. """ if self.is_acquiring_images: # self._is_acquiring_images = False # if self.thread_image_acquisition.is_running: # TODO self.thread_image_acquisition.stop() with MutexLocker(self.thread_image_acquisition): # self.device.node_map.AcquisitionStop.execute() try: # Unlock TLParamsLocked in order to allow full device # configuration: self.device.node_map.TLParamsLocked.value = 0 except LogicalErrorException: # SFNC < 2.0 pass for data_stream in self._data_streams:
python
{ "resource": "" }
q255476
Harvester.add_cti_file
validation
def add_cti_file(self, file_path: str): """ Adds a CTI file to work with to the CTI file list. :param file_path: Set a file path to the target CTI file. :return: None. """ if not os.path.exists(file_path): self._logger.warning( 'Attempted to add {0} which does not
python
{ "resource": "" }
q255477
Harvester.remove_cti_file
validation
def remove_cti_file(self, file_path: str): """ Removes the specified CTI file from the CTI file list. :param file_path: Set a file path to the target CTI file. :return: None. """ if file_path in self._cti_files:
python
{ "resource": "" }
q255478
Harvester._destroy_image_acquirer
validation
def _destroy_image_acquirer(self, ia): """ Releases all external resources including the controlling device. """ id_ = None if ia.device: # ia.stop_image_acquisition() # ia._release_data_streams() # id_ = ia._device.id_ # if ia.device.node_map: # if ia._chunk_adapter: ia._chunk_adapter.detach_buffer() ia._chunk_adapter = None self._logger.info( 'Detached a buffer from the chunk adapter of {0}.'.format(
python
{ "resource": "" }
q255479
Zabransky_spline.add_coeffs
validation
def add_coeffs(self, Tmin, Tmax, coeffs): '''Called internally during the parsing of the Zabransky database, to add coefficients as they are read one per line''' self.n += 1 if not self.Ts: self.Ts = [Tmin, Tmax] self.coeff_sets = [coeffs] else: for ind, T in enumerate(self.Ts): if Tmin < T: # Under an existing coefficient set -
python
{ "resource": "" }
q255480
Zabransky_spline._coeff_ind_from_T
validation
def _coeff_ind_from_T(self, T): '''Determines the index at which the coefficients for the current temperature are stored in `coeff_sets`. ''' # DO NOT CHANGE if self.n == 1:
python
{ "resource": "" }
q255481
HeatCapacityLiquid.calculate
validation
def calculate(self, T, method): r'''Method to calculate heat capacity of a liquid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate heat capacity, [K] method : str Name of the method to use Returns ------- Cp : float Heat capacity of the liquid at T, [J/mol/K] ''' if method == ZABRANSKY_SPLINE: return self.Zabransky_spline.calculate(T) elif method == ZABRANSKY_QUASIPOLYNOMIAL: return self.Zabransky_quasipolynomial.calculate(T) elif method == ZABRANSKY_SPLINE_C: return self.Zabransky_spline_iso.calculate(T) elif method == ZABRANSKY_QUASIPOLYNOMIAL_C: return self.Zabransky_quasipolynomial_iso.calculate(T) elif method == ZABRANSKY_SPLINE_SAT: return self.Zabransky_spline_sat.calculate(T) elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT: return self.Zabransky_quasipolynomial_sat.calculate(T) elif method == COOLPROP: return CoolProp_T_dependent_property(T, self.CASRN , 'CPMOLAR', 'l') elif method == POLING_CONST: return self.POLING_constant elif method == CRCSTD:
python
{ "resource": "" }
q255482
HeatCapacityLiquid.calculate_integral
validation
def calculate_integral(self, T1, T2, method): r'''Method to calculate the integral of a property with respect to temperature, using a specified method. Implements the analytical integrals of all available methods except for tabular data, the case of multiple coefficient sets needed to encompass the temperature range of any of the ZABRANSKY methods, and the CSP methods using the vapor phase properties. Parameters ---------- T1 : float Lower limit of integration, [K] T2 : float Upper limit of integration, [K] method : str Method for which to find the integral Returns ------- integral : float Calculated integral of the property over the given range, [`units*K`] ''' if method == ZABRANSKY_SPLINE: return
python
{ "resource": "" }
q255483
HeatCapacityLiquid.calculate_integral_over_T
validation
def calculate_integral_over_T(self, T1, T2, method): r'''Method to calculate the integral of a property over temperature with respect to temperature, using a specified method. Implements the analytical integrals of all available methods except for tabular data, the case of multiple coefficient sets needed to encompass the temperature range of any of the ZABRANSKY methods, and the CSP methods using the vapor phase properties. Parameters ---------- T1 : float Lower limit of integration, [K] T2 : float Upper limit of integration, [K] method : str Method for which to find the integral Returns ------- integral : float Calculated integral of the property over the given range, [`units`] ''' if method == ZABRANSKY_SPLINE: return self.Zabransky_spline.calculate_integral_over_T(T1, T2)
python
{ "resource": "" }
q255484
HeatCapacitySolid.calculate
validation
def calculate(self, T, method): r'''Method to calculate heat capacity of a solid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate heat capacity, [K] method : str Name of the method to use Returns ------- Cp : float Heat capacity of the solid at T, [J/mol/K] ''' if method == PERRY151:
python
{ "resource": "" }
q255485
HeatCapacityLiquidMixture.calculate
validation
def calculate(self, T, P, zs, ws, method): r'''Method to calculate heat capacity of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float Pressure at which to calculate the property, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Name of the method to use Returns ------- Cplm : float Molar heat capacity of the liquid mixture at the given conditions,
python
{ "resource": "" }
q255486
HeatCapacitySolidMixture.calculate
validation
def calculate(self, T, P, zs, ws, method): r'''Method to calculate heat capacity of a solid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float
python
{ "resource": "" }
q255487
HeatCapacityGasMixture.calculate
validation
def calculate(self, T, P, zs, ws, method): r'''Method to calculate heat capacity of a gas mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float
python
{ "resource": "" }
q255488
K_value
validation
def K_value(P=None, Psat=None, phi_l=None, phi_g=None, gamma=None, Poynting=1): r'''Calculates the equilibrium K-value assuming Raoult's law, or an equation of state model, or an activity coefficient model, or a combined equation of state-activity model. The calculation procedure will use the most advanced approach with the provided inputs: * If `P`, `Psat`, `phi_l`, `phi_g`, and `gamma` are provided, use the combined approach. * If `P`, `Psat`, and `gamma` are provided, use the modified Raoult's law. * If `phi_l` and `phi_g` are provided, use the EOS only method. * If `P` and `Psat` are provided, use Raoult's law. Definitions: .. math:: K_i=\frac{y_i}{x_i} Raoult's law: .. math:: K_i = \frac{P_{i}^{sat}}{P} Activity coefficient, no EOS (modified Raoult's law): .. math:: K_i = \frac{\gamma_i P_{i}^{sat}}{P} Equation of state only: .. math:: K_i = \frac{\phi_i^l}{\phi_i^v} = \frac{f_i^l}{f_i^v} Combined approach (liquid reference fugacity coefficient is normally calculated the saturation pressure for it as a pure species; vapor fugacity coefficient calculated normally): .. math:: K_i = \frac{\gamma_i P_i^{sat} \phi_i^{l,ref}}{\phi_i^v P} Combined approach, with Poynting Correction Factor (liquid molar volume in the integral is for i as a pure species only): .. math:: K_i = \frac{\gamma_i P_i^{sat} \phi_i^{l, ref} \exp\left[\frac{ \int_{P_i^{sat}}^P V_i^l dP}{RT}\right]}{\phi_i^v P} Parameters ---------- P : float System pressure, optional Psat : float Vapor pressure of species i, [Pa] phi_l : float Fugacity coefficient of species i in the liquid phase, either at the system conditions (EOS-only case) or at the saturation pressure of species i as a pure species (reference condition for the combined approach), optional [-] phi_g : float Fugacity coefficient of species i in the vapor phase at the system conditions, optional [-] gamma : float Activity coefficient of species i in the liquid phase, optional [-] Poynting : float Poynting correction factor, optional [-] Returns ------- K : float Equilibrium K value of component i, calculated with an approach depending on the provided inputs [-] Notes ----- The Poynting correction factor is normally simplified as follows, due to a liquid's low pressure dependency: .. math::
python
{ "resource": "" }
q255489
Rachford_Rice_flash_error
validation
def Rachford_Rice_flash_error(V_over_F, zs, Ks): r'''Calculates the objective function of the Rachford-Rice flash equation. This function should be called by a solver seeking a solution to a flash calculation. The unknown variable is `V_over_F`, for which a solution must be between 0 and 1. .. math:: \sum_i \frac{z_i(K_i-1)}{1 + \frac{V}{F}(K_i-1)} = 0 Parameters ---------- V_over_F : float Vapor fraction guess [-] zs : list[float] Overall mole fractions of all species, [-] Ks : list[float] Equilibrium K-values, [-] Returns ------- error : float Deviation between the objective function at the correct V_over_F and the attempted V_over_F, [-] Notes ----- The derivation is as follows: .. math:: F z_i = L x_i + V y_i x_i = \frac{z_i}{1 + \frac{V}{F}(K_i-1)} \sum_i y_i = \sum_i K_i x_i = 1 \sum_i(y_i - x_i)=0 \sum_i \frac{z_i(K_i-1)}{1 + \frac{V}{F}(K_i-1)} = 0 Examples --------
python
{ "resource": "" }
q255490
Wilson
validation
def Wilson(xs, params): r'''Calculates the activity coefficients of each species in a mixture using the Wilson method, given their mole fractions, and dimensionless interaction parameters. Those are normally correlated with temperature, and need to be calculated separately. .. math:: \ln \gamma_i = 1 - \ln \left(\sum_j^N \Lambda_{ij} x_j\right) -\sum_j^N \frac{\Lambda_{ji}x_j}{\displaystyle\sum_k^N \Lambda_{jk}x_k} Parameters ---------- xs : list[float] Liquid mole fractions of each species, [-] params : list[list[float]] Dimensionless interaction parameters of each compound with each other, [-] Returns ------- gammas : list[float] Activity coefficient for each species in the liquid mixture, [-] Notes ----- This model needs N^2 parameters. The original model correlated the interaction parameters using the standard pure-component molar volumes of each species at 25°C, in the following form: .. math:: \Lambda_{ij} = \frac{V_j}{V_i} \exp\left(\frac{-\lambda_{i,j}}{RT}\right) However, that form has less flexibility and offered no advantage over using only regressed parameters. Most correlations for the interaction parameters include some of the terms shown in the following form: .. math:: \ln \Lambda_{ij} =a_{ij}+\frac{b_{ij}}{T}+c_{ij}\ln T + d_{ij}T + \frac{e_{ij}}{T^2} + h_{ij}{T^2} The Wilson model is not applicable to liquid-liquid systems. Examples -------- Ethanol-water example, at 343.15 K and 1 MPa:
python
{ "resource": "" }
q255491
identify_phase
validation
def identify_phase(T, P, Tm=None, Tb=None, Tc=None, Psat=None): r'''Determines the phase of a one-species chemical system according to basic rules, using whatever information is available. Considers only the phases liquid, solid, and gas; does not consider two-phase scenarios, as should occurs between phase boundaries. * If the melting temperature is known and the temperature is under or equal to it, consider it a solid. * If the critical temperature is known and the temperature is greater or equal to it, consider it a gas. * If the vapor pressure at `T` is known and the pressure is under or equal to it, consider it a gas. If the pressure is greater than the vapor pressure, consider it a liquid. * If the melting temperature, critical temperature, and vapor pressure are not known, attempt to use the boiling point to provide phase information. If the pressure is between 90 kPa and 110 kPa (approximately normal), consider it a liquid if it is under the boiling temperature and a gas if above the boiling temperature. * If the pressure is above 110 kPa and the boiling temperature is known, consider it a liquid if the temperature is
python
{ "resource": "" }
q255492
bubble_at_P
validation
def bubble_at_P(P, zs, vapor_pressure_eqns, fugacities=None, gammas=None): '''Calculates bubble point for a given pressure Parameters ---------- P : float Pressure, [Pa] zs : list[float] Overall mole fractions of all species, [-] vapor_pressure_eqns : list[functions] Temperature dependent function for each specie, Returns Psat, [Pa] fugacities : list[float], optional fugacities of each species, defaults to list of ones, [-] gammas : list[float], optional gammas of each species, defaults to list of ones, [-] Returns ------- Tbubble : float, optional
python
{ "resource": "" }
q255493
Chemical.draw_2d
validation
def draw_2d(self, width=300, height=300, Hs=False): # pragma: no cover r'''Interface for drawing a 2D image of the molecule. Requires an HTML5 browser, and the libraries RDKit and IPython. An exception is raised if either of these libraries is absent. Parameters ---------- width : int Number of pixels wide for the view height : int Number of pixels tall for the view Hs : bool Whether or not to show hydrogen Examples -------- >>> Chemical('decane').draw_2d() # doctest: +ELLIPSIS
python
{ "resource": "" }
q255494
Chemical.draw_3d
validation
def draw_3d(self, width=300, height=500, style='stick', Hs=True): # pragma: no cover r'''Interface for drawing an interactive 3D view of the molecule. Requires an HTML5 browser, and the libraries RDKit, pymol3D, and IPython. An exception is raised if all three of these libraries are not installed. Parameters ---------- width : int Number of pixels wide for the view height : int Number of pixels tall for the view style : str One of 'stick', 'line', 'cross', or 'sphere' Hs : bool Whether or not to show hydrogen Examples -------- >>> Chemical('cubane').draw_3d() <IPython.core.display.HTML object> ''' try: import py3Dmol from IPython.display import display if Hs:
python
{ "resource": "" }
q255495
Chemical.charge
validation
def charge(self): r'''Charge of a chemical, computed with RDKit from a chemical's SMILES. If RDKit is not available, holds None. Examples -------- >>> Chemical('sodium ion').charge 1 ''' try:
python
{ "resource": "" }
q255496
Chemical.rdkitmol
validation
def rdkitmol(self): r'''RDKit object of the chemical, without hydrogen. If RDKit is not available, holds None. For examples of what can be done with RDKit, see `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_. ''' if self.__rdkitmol: return self.__rdkitmol
python
{ "resource": "" }
q255497
Chemical.rdkitmol_Hs
validation
def rdkitmol_Hs(self): r'''RDKit object of the chemical, with hydrogen. If RDKit is not available, holds None. For examples of what can be done with RDKit, see `their website <http://www.rdkit.org/docs/GettingStartedInPython.html>`_. ''' if self.__rdkitmol_Hs: return self.__rdkitmol_Hs
python
{ "resource": "" }
q255498
Chemical.legal_status
validation
def legal_status(self): r'''Dictionary of legal status indicators for the chemical. Examples -------- >>> pprint(Chemical('benzene').legal_status) {'DSL': 'LISTED', 'EINECS':
python
{ "resource": "" }
q255499
Chemical.economic_status
validation
def economic_status(self): r'''Dictionary of economic status indicators for the chemical. Examples -------- >>> pprint(Chemical('benzene').economic_status) ["US public: {'Manufactured': 6165232.1, 'Imported': 463146.474, 'Exported': 271908.252}", u'1,000,000 - 10,000,000 tonnes per annum', u'Intermediate Use Only',
python
{ "resource": "" }