_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q7400
BunningsProductSpider.parse_detail
train
def parse_detail(self, response): """Parse individual product's detail""" # Product Information (a start) product_data = { 'url': response.url, 'name': response.css('div.page-title h1::text').extract_first(), } # Inventory Number inventory_number ...
python
{ "resource": "" }
q7401
_Stator.mate_top
train
def mate_top(self): " top of the stator" return Mate(self, CoordSystem( origin=(0, 0, self.length/2), xDir=(0, 1, 0), normal=(0, 0, 1) ))
python
{ "resource": "" }
q7402
_Stator.mate_bottom
train
def mate_bottom(self): " bottom of the stator" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(1, 0, 0), normal=(0, 0, -1) ))
python
{ "resource": "" }
q7403
Stepper.mount_points
train
def mount_points(self): " return mount points" wp = cq.Workplane("XY") h = wp.rect(self.hole_spacing,self.hole_spacing ,forConstruction=True).vertices() return h.objects
python
{ "resource": "" }
q7404
ParametricObject.class_param_names
train
def class_param_names(cls, hidden=True): """ Return the names of all class parameters. :param hidden: if ``False``, excludes parameters with a ``_`` prefix. :type hidden: :class:`bool` :return: set of parameter names :rtype: :class:`set` """ param_names =...
python
{ "resource": "" }
q7405
ParametricObject.serialize_parameters
train
def serialize_parameters(self): """ Get the parameter data in its serialized form. Data is serialized by each parameter's :meth:`Parameter.serialize` implementation. :return: serialized parameter data in the form: ``{<name>: <serial data>, ...}`` :rtype: :class:`dict` ...
python
{ "resource": "" }
q7406
ParametricObject.deserialize
train
def deserialize(data): """ Create instance from serial data """ # Import module & get class try: module = import_module(data.get('class').get('module')) cls = getattr(module, data.get('class').get('name')) except ImportError: raise Impo...
python
{ "resource": "" }
q7407
common_criteria
train
def common_criteria(**common): """ Wrap a function to always call with the given ``common`` named parameters. :property common: criteria common to your function call :return: decorator function :rtype: :class:`function` .. doctest:: >>> import cqparts >>> from cqparts.search i...
python
{ "resource": "" }
q7408
merge_boundboxes
train
def merge_boundboxes(*bb_list): """ Combine bounding boxes to result in a single BoundBox that encloses all of them. :param bb_list: List of bounding boxes :type bb_list: :class:`list` of :class:`cadquery.BoundBox` """ # Verify types if not all(isinstance(x, cadquery.BoundBox) for x in ...
python
{ "resource": "" }
q7409
CoordSystem.random
train
def random(cls, span=1, seed=None): """ Creates a randomized coordinate system. Useful for confirming that an *assembly* does not rely on its origin coordinate system to remain intact. For example, the :class:`CoordSysIndicator` *assembly* aligns 3 boxes along each of t...
python
{ "resource": "" }
q7410
VectorEffect.start_point
train
def start_point(self): """ Start vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector` """ edge = self.result.wire().val().Edges()[0] return edge.Vertices()[0].Center()
python
{ "resource": "" }
q7411
VectorEffect.start_coordsys
train
def start_coordsys(self): """ Coordinate system at start of effect. All axes are parallel to the original vector evaluation location, with the origin moved to this effect's start point. :return: coordinate system at start of effect :rtype: :class:`CoordSys` """ ...
python
{ "resource": "" }
q7412
VectorEffect.end_coordsys
train
def end_coordsys(self): """ Coordinate system at end of effect. All axes are parallel to the original vector evaluation location, with the origin moved to this effect's end point. :return: coordinate system at end of effect :rtype: :class:`CoordSys` """ ...
python
{ "resource": "" }
q7413
VectorEvaluator.perform_evaluation
train
def perform_evaluation(self): """ Determine which parts lie along the given vector, and what length :return: effects on the given parts (in order of the distance from the start point) :rtype: list(:class:`VectorEffect`) """ # Create effect vector (with m...
python
{ "resource": "" }
q7414
indicate_last
train
def indicate_last(items): """ iterate through list and indicate which item is the last, intended to assist tree displays of hierarchical content. :return: yielding (<bool>, <item>) where bool is True only on last entry :rtype: generator """ last_index = len(items) - 1 for (i, item) in e...
python
{ "resource": "" }
q7415
Thread.get_radii
train
def get_radii(self): """ Get the inner and outer radii of the thread. :return: (<inner radius>, <outer radius>) :rtype: :class:`tuple` .. note:: Ideally this method is overridden in inheriting classes to mathematically determine the radii. ...
python
{ "resource": "" }
q7416
Thread.make_simple
train
def make_simple(self): """ Return a cylinder with the thread's average radius & length. :math:`radius = (inner_radius + outer_radius) / 2` """ (inner_radius, outer_radius) = self.get_radii() radius = (inner_radius + outer_radius) / 2 return cadquery.Workplane('XY...
python
{ "resource": "" }
q7417
Thread.make_pilothole_cutter
train
def make_pilothole_cutter(self): """ Make a solid to subtract from an interfacing solid to bore a pilot-hole. """ # get pilothole ratio # note: not done in .initialize_parameters() because this would cause # the thread's profile to be created at initialisation (by def...
python
{ "resource": "" }
q7418
Assembly.tree_str
train
def tree_str(self, name=None, prefix='', add_repr=False, _depth=0): u""" Return string listing recursively the assembly hierarchy :param name: if set, names the tree's trunk, otherwise the object's :meth:`repr` names the tree :type name: :class:`str` :param prefix: string prefix...
python
{ "resource": "" }
q7419
_relative_path_to
train
def _relative_path_to(path_list, filename): """Get a neat relative path to files relative to the CWD""" return os.path.join( os.path.relpath(os.path.join(*path_list), os.getcwd()), filename )
python
{ "resource": "" }
q7420
TrapezoidalGear._make_tooth_template
train
def _make_tooth_template(self): """ Builds a single tooth including the cylinder with tooth faces tangential to its circumference. """ # parameters period_arc = (2 * pi) / self.tooth_count tooth_arc = period_arc * self.spacing_ratio # the arc between faces at eff...
python
{ "resource": "" }
q7421
_Ring.get_mate_center
train
def get_mate_center(self, angle=0): """ Mate at ring's center rotated ``angle`` degrees. :param angle: rotation around z-axis (unit: deg) :type angle: :class:`float` :return: mate in ring's center rotated about z-axis :rtype: :class:`Mate <cqparts.constraint.Mate>` ...
python
{ "resource": "" }
q7422
_BallRing.get_max_ballcount
train
def get_max_ballcount(cls, ball_diam, rolling_radius, min_gap=0.): """ The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float`...
python
{ "resource": "" }
q7423
map_environment
train
def map_environment(**kwargs): """ Decorator to map a DisplayEnvironment for displaying components. The decorated environment will be chosen if its condition is ``True``, and its order is the smallest. :param add_to: if set to ``globals()``, display environment's constructor may ...
python
{ "resource": "" }
q7424
DisplayEnvironment.display_callback
train
def display_callback(self, component, **kwargs): """ Display given component in this environment. .. note:: To be overridden by inheriting classes An example of a introducing a custom display environment. .. doctest:: import cqparts from c...
python
{ "resource": "" }
q7425
ShapeBuffer.add_vertex
train
def add_vertex(self, x, y, z): """ Add a ``VEC3`` of ``floats`` to the ``vert_data`` buffer """ self.vert_data.write( struct.pack('<f', x) + struct.pack('<f', y) + struct.pack('<f', z) ) # retain min/max values self.vert_min = ...
python
{ "resource": "" }
q7426
ShapeBuffer.add_poly_index
train
def add_poly_index(self, i, j, k): """ Add 3 ``SCALAR`` of ``uint`` to the ``idx_data`` buffer. """ self.idx_data.write( struct.pack(self.idx_fmt, i) + struct.pack(self.idx_fmt, j) + struct.pack(self.idx_fmt, k) )
python
{ "resource": "" }
q7427
ShapeBuffer.buffer_iter
train
def buffer_iter(self, block_size=1024): """ Iterate through chunks of the vertices, and indices buffers seamlessly. .. note:: To see a usage example, look at the :class:`ShapeBuffer` description. """ streams = ( self.vert_data, self.idx_data,...
python
{ "resource": "" }
q7428
ShapeBuffer.read
train
def read(self): """ Read buffer out as a single stream. .. warning:: Avoid using this function! **Why?** This is a *convenience* function; it doesn't encourage good memory management. All memory required for a mesh is duplicated, and returned a...
python
{ "resource": "" }
q7429
Part.bounding_box
train
def bounding_box(self): """ Generate a bounding box based on the full complexity part. :return: bounding box of part :rtype: cadquery.BoundBox """ if self.world_coords: return self.world_obj.findSolid().BoundingBox() return self.local_obj.findSolid()....
python
{ "resource": "" }
q7430
MaleFastenerPart.make_cutter
train
def make_cutter(self): """ Makes a shape to be used as a negative; it can be cut away from other shapes to make a perfectly shaped pocket for this part. For example, for a countersunk screw with a neck, the following cutter would be generated. .. image:: /_static/img/fa...
python
{ "resource": "" }
q7431
_Cup.get_cutout
train
def get_cutout(self, clearance=0): " get the cutout for the shaft" return cq.Workplane('XY', origin=(0, 0, 0)) \ .circle((self.diam / 2) + clearance) \ .extrude(10)
python
{ "resource": "" }
q7432
_Cup.mate_bottom
train
def mate_bottom(self): " connect to the bottom of the cup" return Mate(self, CoordSystem(\ origin=(0, 0, -self.height),\ xDir=(1, 0, 0),\ normal=(0, 0, 1)))
python
{ "resource": "" }
q7433
Controller._construct_api_path
train
def _construct_api_path(self, version): """Returns valid base API path based on version given The base API path for the URL is different depending on UniFi server version. Default returns correct path for latest known stable working versions. """ V2_PATH = 'api/' ...
python
{ "resource": "" }
q7434
Controller.get_alerts_unarchived
train
def get_alerts_unarchived(self): """Return a list of Alerts unarchived.""" js = json.dumps({'_sort': '-time', 'archived': False}) params = urllib.urlencode({'json': js}) return self._read(self.api_url + 'list/alarm', params)
python
{ "resource": "" }
q7435
Controller.get_statistics_24h
train
def get_statistics_24h(self, endtime): """Return statistical data last 24h from time""" js = json.dumps( {'attrs': ["bytes", "num_sta", "time"], 'start': int(endtime - 86400) * 1000, 'end': int(endtime - 3600) * 1000}) params = urllib.urlencode({'json': js}) return self._rea...
python
{ "resource": "" }
q7436
Controller.archive_all_alerts
train
def archive_all_alerts(self): """Archive all Alerts """ js = json.dumps({'cmd': 'archive-all-alarms'}) params = urllib.urlencode({'json': js}) answer = self._read(self.api_url + 'cmd/evtmgr', params)
python
{ "resource": "" }
q7437
Controller.create_backup
train
def create_backup(self): """Ask controller to create a backup archive file, response contains the path to the backup file. Warning: This process puts significant load on the controller may render it partially unresponsive for other requests. """ js = json.dumps({'cmd':...
python
{ "resource": "" }
q7438
Controller.get_backup
train
def get_backup(self, target_file='unifi-backup.unf'): """Get a backup archive from a controller. Arguments: target_file -- Filename or full path to download the backup archive to, should have .unf extension for restore. """ download_path = self.create_backup() open...
python
{ "resource": "" }
q7439
Controller.authorize_guest
train
def authorize_guest(self, guest_mac, minutes, up_bandwidth=None, down_bandwidth=None, byte_quota=None, ap_mac=None): """ Authorize a guest based on his MAC address. Arguments: guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff minutes -- duration of the aut...
python
{ "resource": "" }
q7440
Controller.unauthorize_guest
train
def unauthorize_guest(self, guest_mac): """ Unauthorize a guest based on his MAC address. Arguments: guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff """ cmd = 'unauthorize-guest' js = {'mac': guest_mac} return self._run_command(cmd, params=js)
python
{ "resource": "" }
q7441
download
train
def download(gfile, wks_name=None, col_names=False, row_names=False, credentials=None, start_cell = 'A1'): """ Download Google Spreadsheet and convert it to Pandas DataFrame :param gfile: path to Google Spreadsheet or gspread ID :param wks_name: worksheet name :param col...
python
{ "resource": "" }
q7442
get_credentials
train
def get_credentials(credentials=None, client_secret_file=CLIENT_SECRET_FILE, refresh_token=None): """Consistently returns valid credentials object. See Also: https://developers.google.com/drive/web/quickstart/python Args: client_secret_file (str): path to client secrets file, defaults to ....
python
{ "resource": "" }
q7443
create_service_credentials
train
def create_service_credentials(private_key_file=None, client_email=None, client_secret_file=CLIENT_SECRET_FILE): """Create credentials from service account information. See Also: https://developers.google.com/api-client-library/python/auth/service-accounts Args: ...
python
{ "resource": "" }
q7444
get_file_id
train
def get_file_id(credentials, gfile, write_access=False): """ Get file ID by provided path. If file does not exist and `write_access` is true, it will create whole path for you. :param credentials: provide own credentials :param gfile: path to Google Spreadsheet :param write_...
python
{ "resource": "" }
q7445
agg_conc
train
def agg_conc(original_countries, aggregates, missing_countries='test', merge_multiple_string='_&_', log_missing_countries=None, log_merge_multiple_strings=None, coco=None, as_dataframe='sparse', original_countries_cl...
python
{ "resource": "" }
q7446
match
train
def match(list_a, list_b, not_found='not_found', enforce_sublist=False, country_data=COUNTRY_DATA_FILE, additional_data=None): """ Matches the country names given in two lists into a dictionary. This function matches names given in list_a to the one provided in list_b using regular expressions de...
python
{ "resource": "" }
q7447
_parse_arg
train
def _parse_arg(valid_classifications): """ Command line parser for coco Parameters ---------- valid_classifications: list Available classifications, used for checking input parameters. Returns ------- args : ArgumentParser namespace """ parser = argparse.ArgumentParser( ...
python
{ "resource": "" }
q7448
main
train
def main(): """ Main entry point - used for command line call """ args = _parse_arg(CountryConverter().valid_class) coco = CountryConverter(additional_data=args.additional_data) converted_names = coco.convert( names=args.names, src=args.src, to=args.to, enforce_list=F...
python
{ "resource": "" }
q7449
CountryConverter._separate_exclude_cases
train
def _separate_exclude_cases(name, exclude_prefix): """ Splits the excluded Parameters ---------- name : str Name of the country/region to convert. exclude_prefix : list of valid regex strings List of indicators which negate the subsequent country/region....
python
{ "resource": "" }
q7450
CountryConverter.convert
train
def convert(self, names, src=None, to='ISO3', enforce_list=False, not_found='not found', exclude_prefix=['excl\\w.*', 'without', 'w/o']): """ Convert names from a list to another list. Note ---- A lot of the functionality can also be done directly in Pand...
python
{ "resource": "" }
q7451
CountryConverter.EU28as
train
def EU28as(self, to='name_short'): """ Return EU28 countries in the specified classification Parameters ---------- to : str, optional Output classification (valid str for an index of country_data file), default: name_short Returns -------...
python
{ "resource": "" }
q7452
CountryConverter.EU27as
train
def EU27as(self, to='name_short'): """ Return EU27 countries in the specified classification Parameters ---------- to : str, optional Output classification (valid str for an index of country_data file), default: name_short Returns -------...
python
{ "resource": "" }
q7453
CountryConverter.OECDas
train
def OECDas(self, to='name_short'): """ Return OECD member states in the specified classification Parameters ---------- to : str, optional Output classification (valid str for an index of country_data file), default: name_short Returns ---...
python
{ "resource": "" }
q7454
CountryConverter.UNas
train
def UNas(self, to='name_short'): """ Return UN member states in the specified classification Parameters ---------- to : str, optional Output classification (valid str for an index of country_data file), default: name_short Returns -------...
python
{ "resource": "" }
q7455
CountryConverter.obsoleteas
train
def obsoleteas(self, to='name_short'): """ Return obsolete countries in the specified classification Parameters ---------- to : str, optional Output classification (valid str for an index of country_data file), default: name_short Returns ...
python
{ "resource": "" }
q7456
CountryConverter.get_correspondance_dict
train
def get_correspondance_dict(self, classA, classB, restrict=None, replace_numeric=True): """ Returns a correspondance between classification A and B as dict Parameters ---------- classA: str Valid classification...
python
{ "resource": "" }
q7457
CountryConverter._validate_input_para
train
def _validate_input_para(self, para, column_names): """ Convert the input classificaton para to the correct df column name Parameters ---------- para : string column_names : list of strings Returns ------- validated_para : string Converted ...
python
{ "resource": "" }
q7458
CountryConverter._get_input_format_from_name
train
def _get_input_format_from_name(self, name): """ Determines the input format based on the given country name Parameters ---------- name : string Returns ------- string : valid input format """ try: int(name) src_format =...
python
{ "resource": "" }
q7459
Bernstein
train
def Bernstein(n, k): """Bernstein polynomial. """ coeff = binom(n, k) def _bpoly(x): return coeff * x ** k * (1 - x) ** (n - k) return _bpoly
python
{ "resource": "" }
q7460
_read_in_thread
train
def _read_in_thread(address, pty, blocking): """Read data from the pty in a thread. """ client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(address) while 1: data = pty.read(4096, blocking=blocking) if not data and not pty.isalive(): while not data...
python
{ "resource": "" }
q7461
PtyProcess.read
train
def read(self, size=1024): """Read and return at most ``size`` characters from the pty. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. """ data = self.fileobj.recv(size) if not data: self.flag_eof = True ...
python
{ "resource": "" }
q7462
PtyProcess.readline
train
def readline(self): """Read one line from the pseudoterminal as bytes. Can block if there is nothing to read. Raises :exc:`EOFError` if the terminal was closed. """ buf = [] while 1: try: ch = self.read(1) except EOFError: ...
python
{ "resource": "" }
q7463
PtyProcess.write
train
def write(self, s): """Write the string ``s`` to the pseudoterminal. Returns the number of bytes written. """ if not self.isalive(): raise EOFError('Pty is closed') if PY2: s = _unicode(s) success, nbytes = self.pty.write(s) if not succes...
python
{ "resource": "" }
q7464
PtyProcess.terminate
train
def terminate(self, force=False): """This forces a child process to terminate.""" if not self.isalive(): return True self.kill(signal.SIGINT) time.sleep(self.delayafterterminate) if not self.isalive(): return True if force: self.kill(si...
python
{ "resource": "" }
q7465
PtyProcess.setwinsize
train
def setwinsize(self, rows, cols): """Set the terminal window size of the child tty. """ self._winsize = (rows, cols) self.pty.set_size(cols, rows)
python
{ "resource": "" }
q7466
PTY.read
train
def read(self, length=1000, blocking=False): """ Read ``length`` bytes from current process output stream. Note: This method is not fully non-blocking, however it behaves like one. """ size_p = PLARGE_INTEGER(LARGE_INTEGER(0)) if not blocking: windll....
python
{ "resource": "" }
q7467
PTY.write
train
def write(self, data): """Write string data to current process input stream.""" data = data.encode('utf-8') data_p = ctypes.create_string_buffer(data) num_bytes = PLARGE_INTEGER(LARGE_INTEGER(0)) bytes_to_write = len(data) success = WriteFile(self.conin_pipe, data_p, ...
python
{ "resource": "" }
q7468
PTY.close
train
def close(self): """Close all communication process streams.""" windll.kernel32.CloseHandle(self.conout_pipe) windll.kernel32.CloseHandle(self.conin_pipe)
python
{ "resource": "" }
q7469
PTY.iseof
train
def iseof(self): """Check if current process streams are still open.""" succ = windll.kernel32.PeekNamedPipe( self.conout_pipe, None, None, None, None, None ) return not bool(succ)
python
{ "resource": "" }
q7470
IP.bin
train
def bin(self): """Full-length binary representation of the IP address. >>> ip = IP("127.0.0.1") >>> print(ip.bin()) 01111111000000000000000000000001 """ bits = self.v == 4 and 32 or 128 return bin(self.ip).split('b')[1].rjust(bits, '0')
python
{ "resource": "" }
q7471
IP.info
train
def info(self): """Show IANA allocation information for the current IP address. >>> ip = IP("127.0.0.1") >>> print(ip.info()) LOOPBACK """ b = self.bin() for i in range(len(b), 0, -1): if b[:i] in self._range[self.v]: return self._rang...
python
{ "resource": "" }
q7472
IP._dqtoi
train
def _dqtoi(self, dq): """Convert dotquad or hextet to long.""" # hex notation if dq.startswith('0x'): return self._dqtoi_hex(dq) # IPv6 if ':' in dq: return self._dqtoi_ipv6(dq) elif len(dq) == 32: # Assume full heximal notation ...
python
{ "resource": "" }
q7473
IP._itodq
train
def _itodq(self, n): """Convert long to dotquad or hextet.""" if self.v == 4: return '.'.join(map(str, [ (n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff, ])) else: n = '%032x' % n ...
python
{ "resource": "" }
q7474
IP.to_compressed
train
def to_compressed(self): """ Compress an IP address to its shortest possible compressed form. >>> print(IP('127.0.0.1').to_compressed()) 127.1 >>> print(IP('127.1.0.1').to_compressed()) 127.1.1 >>> print(IP('127.0.1.1').to_compressed()) 127.0.1.1 ...
python
{ "resource": "" }
q7475
IP.from_bin
train
def from_bin(cls, value): """Initialize a new network from binary notation.""" value = value.lstrip('b') if len(value) == 32: return cls(int(value, 2)) elif len(value) == 128: return cls(int(value, 2)) else: return ValueError('%r: invalid binar...
python
{ "resource": "" }
q7476
IP.from_hex
train
def from_hex(cls, value): """Initialize a new network from hexadecimal notation.""" if len(value) == 8: return cls(int(value, 16)) elif len(value) == 32: return cls(int(value, 16)) else: raise ValueError('%r: invalid hexadecimal notation' % (value,))
python
{ "resource": "" }
q7477
IP.to_reverse
train
def to_reverse(self): """Convert the IP address to a PTR record. Using the .in-addr.arpa zone for IPv4 and .ip6.arpa for IPv6 addresses. >>> ip = IP('192.0.2.42') >>> print(ip.to_reverse()) 42.2.0.192.in-addr.arpa >>> print(ip.to_ipv6().to_reverse()) 0.0.0.0.0.0...
python
{ "resource": "" }
q7478
Network.netmask_long
train
def netmask_long(self): """ Network netmask derived from subnet size, as long. >>> localnet = Network('127.0.0.1/8') >>> print(localnet.netmask_long()) 4278190080 """ if self.version() == 4: return (MAX_IPV4 >> (32 - self.mask)) << (32 - self.mask) ...
python
{ "resource": "" }
q7479
Network.broadcast_long
train
def broadcast_long(self): """ Broadcast address, as long. >>> localnet = Network('127.0.0.1/8') >>> print(localnet.broadcast_long()) 2147483647 """ if self.version() == 4: return self.network_long() | (MAX_IPV4 - self.netmask_long()) else: ...
python
{ "resource": "" }
q7480
Network.host_first
train
def host_first(self): """First available host in this subnet.""" if (self.version() == 4 and self.mask > 30) or \ (self.version() == 6 and self.mask > 126): return self else: return IP(self.network_long() + 1, version=self.version())
python
{ "resource": "" }
q7481
Network.host_last
train
def host_last(self): """Last available host in this subnet.""" if (self.version() == 4 and self.mask == 32) or \ (self.version() == 6 and self.mask == 128): return self elif (self.version() == 4 and self.mask == 31) or \ (self.version() == 6 and self.m...
python
{ "resource": "" }
q7482
Network.check_collision
train
def check_collision(self, other): """Check another network against the given network.""" other = Network(other) return self.network_long() <= other.network_long() <= self.broadcast_long() or \ other.network_long() <= self.network_long() <= other.broadcast_long()
python
{ "resource": "" }
q7483
CmsModelList.init_with_context
train
def init_with_context(self, context): """ Initialize the menu. """ # Apply the include/exclude patterns: listitems = self._visible_models(context['request']) # Convert to a similar data structure like the dashboard icons have. # This allows sorting the items iden...
python
{ "resource": "" }
q7484
ReturnToSiteItem.get_edited_object
train
def get_edited_object(self, request): """ Return the object which is currently being edited. Returns ``None`` if the match could not be made. """ resolvermatch = urls.resolve(request.path_info) if resolvermatch.namespace == 'admin' and resolvermatch.url_name and resolverm...
python
{ "resource": "" }
q7485
get_application_groups
train
def get_application_groups(): """ Return the applications of the system, organized in various groups. These groups are not connected with the application names, but rather with a pattern of applications. """ groups = [] for title, groupdict in appsettings.FLUENT_DASHBOARD_APP_GROUPS: ...
python
{ "resource": "" }
q7486
is_cms_app
train
def is_cms_app(app_name): """ Return whether the given application is a CMS app """ for pat in appsettings.FLUENT_DASHBOARD_CMS_APP_NAMES: if fnmatch(app_name, pat): return True return False
python
{ "resource": "" }
q7487
get_cms_model_order
train
def get_cms_model_order(model_name): """ Return a numeric ordering for a model name. """ for (name, order) in iteritems(appsettings.FLUENT_DASHBOARD_CMS_MODEL_ORDER): if name in model_name: return order return 999
python
{ "resource": "" }
q7488
FluentMenu.init_with_context
train
def init_with_context(self, context): """ Initialize the menu items. """ site_name = get_admin_site_name(context) self.children += [ items.MenuItem(_('Dashboard'), reverse('{0}:index'.format(site_name))), items.Bookmarks(), ] for title, k...
python
{ "resource": "" }
q7489
PersonalModule.init_with_context
train
def init_with_context(self, context): """ Initializes the link list. """ super(PersonalModule, self).init_with_context(context) current_user = context['request'].user if django.VERSION < (1, 5): current_username = current_user.first_name or current_user.userna...
python
{ "resource": "" }
q7490
AppIconList.get_icon_url
train
def get_icon_url(self, icon): """ Replaces the "icon name" with a full usable URL. * When the icon is an absolute URL, it is used as-is. * When the icon contains a slash, it is relative from the ``STATIC_URL``. * Otherwise, it's relative to the theme url folder. """ ...
python
{ "resource": "" }
q7491
CacheStatusGroup.init_with_context
train
def init_with_context(self, context): """ Initializes the status list. """ super(CacheStatusGroup, self).init_with_context(context) if 'dashboardmods' in settings.INSTALLED_APPS: import dashboardmods memcache_mods = dashboardmods.get_memcache_dash_modules...
python
{ "resource": "" }
q7492
get_requirements
train
def get_requirements(): """Get the dependencies.""" with open("requirements/project.txt") as f: requirements = [] for line in f.readlines(): line = line.strip() if line and not line.startswith('#'): requirements.append(line) return requirements
python
{ "resource": "" }
q7493
_cached_css_compile
train
def _cached_css_compile(pattern, namespaces, custom, flags): """Cached CSS compile.""" custom_selectors = process_custom(custom) return cm.SoupSieve( pattern, CSSParser(pattern, custom=custom_selectors, flags=flags).process_selectors(), namespaces, custom, flags ...
python
{ "resource": "" }
q7494
process_custom
train
def process_custom(custom): """Process custom.""" custom_selectors = {} if custom is not None: for key, value in custom.items(): name = util.lower(key) if RE_CUSTOM.match(name) is None: raise SelectorSyntaxError("The name '{}' is not a valid custom pseudo-cla...
python
{ "resource": "" }
q7495
css_unescape
train
def css_unescape(content, string=False): """ Unescape CSS value. Strings allow for spanning the value on multiple strings by escaping a new line. """ def replace(m): """Replace with the appropriate substitute.""" if m.group(1): codepoint = int(m.group(1)[1:], 16) ...
python
{ "resource": "" }
q7496
escape
train
def escape(ident): """Escape identifier.""" string = [] length = len(ident) start_dash = length > 0 and ident[0] == '-' if length == 1 and start_dash: # Need to escape identifier that is a single `-` with no other characters string.append('\\{}'.format(ident)) else: for ...
python
{ "resource": "" }
q7497
SpecialPseudoPattern.match
train
def match(self, selector, index): """Match the selector.""" pseudo = None m = self.re_pseudo_name.match(selector, index) if m: name = util.lower(css_unescape(m.group('name'))) pattern = self.patterns.get(name) if pattern: pseudo = patt...
python
{ "resource": "" }
q7498
_Selector._freeze_relations
train
def _freeze_relations(self, relations): """Freeze relation.""" if relations: sel = relations[0] sel.relations.extend(relations[1:]) return ct.SelectorList([sel.freeze()]) else: return ct.SelectorList()
python
{ "resource": "" }
q7499
_Selector.freeze
train
def freeze(self): """Freeze self.""" if self.no_match: return ct.SelectorNull() else: return ct.Selector( self.tag, tuple(self.ids), tuple(self.classes), tuple(self.attributes), tuple(self.nt...
python
{ "resource": "" }