code
stringlengths
1
18.2k
"index") else None return Projection.from_optimize_result( result=optim, n=self.n, m=self.m, index=index)
def optimize_batch(self, batchsize=10, returns='best', paralell=True): """ Run multiple optimizations using different starting coordinates. Args: batchsize (`int`): Number of optimizations to run. returns (`str`): If ``'all'``, return results of all optimizations, ordered by stress, ascending. If ``'best'`` return the ...
stress. """ if returns not in ('best', 'all'): raise ValueError('returns must be either "best" or "all"') starts = [np.random.rand(self.m * 2) * 10 for i in range(batchsize)] if paralell: with Pool() as p: results = p.map(self.optimize, starts) else: results = map(self.optimize, starts) results = sorted(results, key=la...
def from_optimize_result(cls, result, n, m, index=None): """Construct a Projection from the output of an optimization. Args: result (:py:class:`scipy.optimize.OptimizeResult`): Object returned by :py:func:`scipy.optimize.minimize`. n (`int`): Number of dimensions. m (`int`): Number of samples. index (`list-like`): Name...
def _get_samples_shared_with(self, other, index=None): """Find samples shared with another dataset. Args: other (:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame` or `array-like`): The other dataset. If `other` is an instance of :py:class:`pymds.Projection` or :py:class:`pandas.DataFrame`, then `other` must ...
duplicates") if uniq_idx - set(df_other.index): raise ValueError("index has samples not in other") if uniq_idx - set(self.coords.index): raise ValueError( "index has samples not in this projection") else: uniq_idx = set(df_other.index) & set(self.coords.index) if not len(uniq_idx): raise ValueError( "No samples shared ...
def plot(self, **kwds): """Plot the coordinates in the first two dimensions of the projection. Removes axis and tick labels, and sets the grid spacing to 1 unit. One way to display the grid is to use `Seaborn`_: Args: **kwds: Passed to :py:meth:`pandas.DataFrame.plot.scatter`. Examples: >>> from pymds import DistanceMa...
def plot_lines_to(self, other, index=None, **kwds): """Plot lines from samples shared between this projection and another dataset. Args: other (:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame` or `array-like`): The other dataset to plot lines to. If other is an instance of :py:class:`pymds.Projection` or :p...
pro.plot_lines_to(other, linewidths=0.3) Returns: :py:obj:`matplotlib.axes.Axes` """ start, end = self._get_samples_shared_with(other, index=index) segments = [[start[i, :], end[i, :]] for i in range(start.shape[0])] ax = plt.gca() ax.add_artist(LineCollection(segments=segments, **kwds)) return ax
def orient_to(self, other, index=None, inplace=False, scaling=False): """Orient this Projection to another dataset. Orient this projection using reflection, rotation and translation to match another projection using procrustes superimposition. Scaling is optional. Args: other (:py:class:`pymds.Projection` or :py:class:...
>>> import pandas as pd >>> from pymds import Projection >>> array = np.random.randn(10, 2) >>> pro = Projection(pd.DataFrame(array)) >>> # Flip left-right, rotate 90 deg and translate >>> other = np.fliplr(array) >>> other = np.dot(other, np.array([[0, -1], [1, 0]])) >>> other += np.array([10, -5]) >>> oriented = pro....
def conda_prefix(user=None): """ Get the conda prefix for a particular user (~/anaconda) If user is None it defaults to /opt/anaconda """ if user == 'root': return __salt__['grains.get']('conda:prefix', default='/opt/anaconda') else: if user is None: user = __salt__['pillar.get']('system:user', 'ubuntu') for u in pwd.g...
def create(name, packages=None, user=None): """ Create a conda env """ packages = packages or '' packages = packages.split(',') packages.append('pip') args = packages + ['--yes', '-q'] cmd = _create_conda_cmd('create', args=args, env=name, user=user) ret = _execcmd(cmd, user=user, return0=True) if ret['retcode'] == 0: ...
def list_(env=None, user=None): """ List the installed packages on an environment Returns ------- Dictionary: {package: {version: 1.0.0, build: 1 } ... } """ cmd = _create_conda_cmd('list', args=['--json'], env=env, user=user) ret = _execcmd(cmd, user=user) if ret['retcode'] == 0: pkg_list = json.loads(ret['stdout']) p...
def update(packages, env=None, user=None): """ Update conda packages in a conda env Attributes ---------- packages: list of packages comma delimited """ packages = ' '.join(packages.split(',')) cmd = _create_conda_cmd('update', args=[packages, '--yes', '-q'], env=env, user=user) return _execcmd(cmd, user=user)
def remove(packages, env=None, user=None): """ Remove conda packages in a conda env Attributes ---------- packages: list of packages comma delimited """ packages = ' '.join(packages.split(',')) cmd = _create_conda_cmd('remove', args=[packages, '--yes', '-q'], env=env, user=user) return _execcmd(cmd, user=user, return0=...
def _create_conda_cmd(conda_cmd, args=None, env=None, user=None): """ Utility to create a valid conda command """ cmd = [_get_conda_path(user=user), conda_cmd] if env: cmd.extend(['-n', env]) if args is not None and isinstance(args, list) and args != []: cmd.extend(args) return cmd
def initDeviceScan(self): """Initialize Key Stored Values.""" self.__isIphone = self.detectIphoneOrIpod() self.__isAndroidPhone = self.detectAndroidPhone() self.__isTierTablet = self.detectTierTablet() self.__isTierIphone = self.detectTierIphone() self.__isTierRichCss = self.detectTierRichCss() self.__isTierGenericMobi...
def detectIphone(self): """Return detection of an iPhone Detects if the current device is an iPhone. """ # The iPad and iPod touch say they're an iPhone! So let's disambiguate. return UAgentInfo.deviceIphone in self.__userAgent \ and not self.detectIpad() \ and not self.detectIpod()
def detectIphoneOrIpod(self): """Return detection of an iPhone or iPod Touch Detects if the current device is an iPhone or iPod Touch. """ #We repeat the searches here because some iPods may report themselves as an iPhone, which would be okay. return UAgentInfo.deviceIphone in self.__userAgent \ or UAgentInfo.deviceIpo...
def detectAndroid(self): """Return detection of an Android device Detects *any* Android OS-based device: phone, tablet, and multi-media player. Also detects Google TV. """ if UAgentInfo.deviceAndroid in self.__userAgent \ or self.detectGoogleTV(): return True return False
def detectAndroidPhone(self): """Return detection of an Android phone Detects if the current device is a (small-ish) Android OS-based device used for calling and/or multi-media (like a Samsung Galaxy Player). Google says these devices will have 'Android' AND 'mobile' in user agent. Ignores tablets (Honeycomb and later)...
def detectAndroidTablet(self): """Return detection of an Android tablet Detects if the current device is a (self-reported) Android tablet. Google says these devices will have 'Android' and NOT 'mobile' in their user agent. """ #First, let's make sure we're on an Android device. if not self.detectAndroid(): return False...
def detectS60OssBrowser(self): """Return detection of Symbian S60 Browser Detects if the current browser is the Symbian S60 Open Source Browser. """ #First, test for WebKit, then make sure it's either Symbian or S60. return self.detectWebkit() \ and (UAgentInfo.deviceSymbian in self.__userAgent or UAgentInfo.deviceS60 ...
def detectSymbianOS(self): """Return detection of SymbianOS Detects if the current device is any Symbian OS-based device, including older S60, Series 70, Series 80, Series 90, and UIQ, or other browsers running on these devices. """ return UAgentInfo.deviceSymbian in self.__userAgent \ or UAgentInfo.deviceS60 in self._...
def detectWindowsMobile(self): """Return detection of Windows Mobile Detects if the current browser is a Windows Mobile device. Excludes Windows Phone 7 devices. Focuses on Windows Mobile 6.xx and earlier. """ #Exclude new Windows Phone. if self.detectWindowsPhone(): return False #Most devices use 'Windows CE', but som...
return UAgentInfo.devicePpc in self.__userAgent \ and UAgentInfo.deviceMacPpc not in self.__userAgent
def detectBlackBerry(self): """Return detection of Blackberry Detects if the current browser is any BlackBerry. Includes the PlayBook. """ return UAgentInfo.deviceBB in self.__userAgent \ or UAgentInfo.vndRIM in self.__httpAccept
def detectBlackBerry10Phone(self): """Return detection of a Blackberry 10 OS phone Detects if the current browser is a BlackBerry 10 OS phone. Excludes the PlayBook. """ return UAgentInfo.deviceBB10 in self.__userAgent \ and UAgentInfo.mobile in self.__userAgent
def detectBlackBerryTouch(self): """Return detection of a Blackberry touchscreen device Detects if the current browser is a BlackBerry Touch device, such as the Storm, Torch, and Bold Touch. Excludes the Playbook. """ return UAgentInfo.deviceBBStorm in self.__userAgent \ or UAgentInfo.deviceBBTorch in self.__userAgent ...
def detectBlackBerryHigh(self): """Return detection of a Blackberry device with a better browser Detects if the current browser is a BlackBerry device AND has a more capable recent browser. Excludes the Playbook. Examples, Storm, Bold, Tour, Curve2 Excludes the new BlackBerry OS 6 and 7 browser!! """ #Disambiguate for ...
def detectPalmOS(self): """Return detection of a PalmOS device Detects if the current browser is on a PalmOS device. """ #Most devices nowadays report as 'Palm', but some older ones reported as Blazer or Xiino. if UAgentInfo.devicePalm in self.__userAgent \ or UAgentInfo.engineBlazer in self.__userAgent \ or UAgentInfo...
def detectWebOSTablet(self): """Return detection of an HP WebOS tablet Detects if the current browser is on an HP tablet running WebOS. """ return UAgentInfo.deviceWebOShp in self.__userAgent \ and UAgentInfo.deviceTablet in self.__userAgent
def detectWebOSTV(self): """Return detection of a WebOS smart TV Detects if the current browser is on a WebOS smart TV. """ return UAgentInfo.deviceWebOStv in self.__userAgent \ and UAgentInfo.smartTV2 in self.__userAgent
def detectTizen(self): """Return detection of a Tizen device Detects a device running the Tizen smartphone OS. """ return UAgentInfo.deviceTizen in self.__userAgent \ and UAgentInfo.mobile in self.__userAgent
def detectTizenTV(self): """Return detection of a Tizen smart TV Detects if the current browser is on a Tizen smart TV. """ return UAgentInfo.deviceTizen in self.__userAgent \ and UAgentInfo.smartTV1 in self.__userAgent
def detectMeegoPhone(self): """Return detection of a Meego phone Detects a phone running the Meego OS. """ return UAgentInfo.deviceMeego in self.__userAgent \ and UAgentInfo.mobi in self.__userAgent
def detectFirefoxOSPhone(self): """Return detection of a Firefox OS phone Detects a phone (probably) running the Firefox OS. """ if self.detectIos() \ or self.detectAndroid() \ or self.detectSailfish(): return False if UAgentInfo.engineFirefox in self.__userAgent \ and UAgentInfo.mobile in self.__userAgent: return True...
def detectFirefoxOSTablet(self): """Return detection of a Firefox OS tablet Detects a tablet (probably) running the Firefox OS. """ if self.detectIos() \ or self.detectAndroid() \ or self.detectSailfish(): return False if UAgentInfo.engineFirefox in self.__userAgent \ and UAgentInfo.deviceTablet in self.__userAgent: re...
def detectSailfishPhone(self): """Return detection of a Sailfish phone Detects a phone running the Sailfish OS. """ if self.detectSailfish() \ and UAgentInfo.mobile in self.__userAgent: return True return False
def detectUbuntuPhone(self): """Return detection of an Ubuntu Mobile OS phone Detects a phone running the Ubuntu Mobile OS. """ if UAgentInfo.deviceUbuntu in self.__userAgent \ and UAgentInfo.mobile in self.__userAgent: return True return False
def detectUbuntuTablet(self): """Return detection of an Ubuntu Mobile OS tablet Detects a tablet running the Ubuntu Mobile OS. """ if UAgentInfo.deviceUbuntu in self.__userAgent \ and UAgentInfo.deviceTablet in self.__userAgent: return True return False
def detectDangerHiptop(self): """Return detection of a Danger Hiptop Detects the Danger Hiptop device. """ return UAgentInfo.deviceDanger in self.__userAgent \ or UAgentInfo.deviceHiptop in self.__userAgent
def detectOperaMobile(self): """Return detection of an Opera browser for a mobile device Detects Opera Mobile or Opera Mini. """ return UAgentInfo.engineOpera in self.__userAgent \ and (UAgentInfo.mini in self.__userAgent or UAgentInfo.mobi in self.__userAgent)
def detectWapWml(self): """Return detection of a WAP- or WML-capable device Detects whether the device supports WAP or WML. """ return UAgentInfo.vndwap in self.__httpAccept \ or UAgentInfo.wml in self.__httpAccept
def detectGamingHandheld(self): """Return detection of a gaming handheld with a modern iPhone-class browser Detects if the current device is a handheld gaming device with a touchscreen and modern iPhone-class browser. Includes the Playstation Vita. """ return UAgentInfo.devicePlaystation in self.__userAgent \ and UAgen...
def detectNintendo(self): """Return detection of Nintendo Detects if the current device is a Nintendo game device. """ return UAgentInfo.deviceNintendo in self.__userAgent \ or UAgentInfo.deviceNintendo in self.__userAgent \ or UAgentInfo.deviceNintendo in self.__userAgent
def detectMidpCapable(self): """Return detection of a MIDP mobile Java-capable device Detects if the current device supports MIDP, a mobile Java technology. """ return UAgentInfo.deviceMidp in self.__userAgent \ or UAgentInfo.deviceMidp in self.__httpAccept
def detectMaemoTablet(self): """Return detection of a Maemo OS tablet Detects if the current device is on one of the Maemo-based Nokia Internet Tablets. """ if UAgentInfo.maemo in self.__userAgent: return True return UAgentInfo.linux in self.__userAgent \ and UAgentInfo.deviceTablet in self.__userAgent \ and not self.d...
def detectSonyMylo(self): """Return detection of a Sony Mylo device Detects if the current browser is a Sony Mylo device. """ return UAgentInfo.manuSony in self.__userAgent \ and (UAgentInfo.qtembedded in self.__userAgent or UAgentInfo.mylocom2 in self.__userAgent)
def detectSmartphone(self): """Return detection of a general smartphone device Checks to see whether the device is *any* 'smartphone'. Note: It's better to use DetectTierIphone() for modern touchscreen devices. """ return self.detectTierIphone() \ or self.detectS60OssBrowser() \ or self.detectSymbianOS() \ or self.dete...
def detectMobileQuick(self): """Return detection of any mobile device using the quicker method Detects if the current device is a mobile device. This method catches most of the popular modern devices. Excludes Apple iPads and other modern tablets. """ #Let's exclude tablets if self.__isTierTablet: return False #Most mo...
def detectMobileLong(self): """Return detection of any mobile device using the more thorough method The longer and more thorough way to detect for a mobile device. Will probably detect most feature phones, smartphone-class devices, Internet Tablets, Internet-enabled game consoles, etc. This ought to catch a lot of the ...
self.__userAgent \ or UAgentInfo.svcKddi in self.__userAgent \ or UAgentInfo.svcVodafone in self.__userAgent
def detectTierTablet(self): """Return detection of any device in the Tablet Tier The quick way to detect for a tier of devices. This method detects for the new generation of HTML 5 capable, larger screen tablets. Includes iPad, Android (e.g., Xoom), BB Playbook, WebOS, etc. """ return self.detectIpad() \ or self.detect...
def detectTierIphone(self): """Return detection of any device in the iPhone/Android/WP7/WebOS Tier The quick way to detect for a tier of devices. This method detects for devices which can display iPhone-optimized web content. Includes iPhone, iPod Touch, Android, Windows Phone 7, Palm WebOS, etc. """ return self.__isIp...
def detectTierRichCss(self): """Return detection of any device in the 'Rich CSS' Tier The quick way to detect for a tier of devices. This method detects for devices which are likely to be capable of viewing CSS content optimized for the iPhone, but may not necessarily support JavaScript. Excludes all iPhone Tier device...
def str_to_date(self): """ Returns the date attribute as a date object. :returns: Date of the status if it exists. :rtype: date or NoneType """ if hasattr(self, 'date'): return date(*list(map(int, self.date.split('-')))) else: return None
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) if hasattr(self, 'date'): self.xml_element.set('date', self.da...
def cancel_on_closing(func): """ Automatically cancels a function or coroutine when the defining instance gets closed. :param func: The function to cancel on closing. :returns: A decorated function or coroutine. """ @wraps(func) async def wrapper(self, *args, **kwargs): return await self.await_until_closing(func(self, ...
async def await_until_closing(self, coro): """ Wait for some task to complete but aborts as soon asthe instance is being closed. :param coro: The coroutine or future-like object to wait for. """ wait_task = asyncio.ensure_future(self.wait_closing(), loop=self.loop) coro_task = asyncio.ensure_future(coro, loop=self.loop...
def _set_closed(self, future): """ Indicate that the instance is effectively closed. :param future: The close future. """ logger.debug("%s[%s] closed.", self.__class__.__name__, id(self)) self.on_closed.emit(self) self._closed_future.set_result(future.result())
def close(self): """ Close the instance. """ if not self.closed and not self.closing: logger.debug( "%s[%s] closing...", self.__class__.__name__, id(self), ) self._closing.set() future = asyncio.ensure_future(self.on_close(), loop=self.loop) future.add_done_callback(self._set_closed)
def register_child(self, child): """ Register a new child that will be closed whenever the current instance closes. :param child: The child instance. """ if self.closing: child.close() else: self._children.add(child) child.on_closed.connect(self.unregister_child)
def unregister_child(self, child): """ Unregister an existing child that is no longer to be owned by the current instance. :param child: The child instance. """ self._children.remove(child) child.on_closed.disconnect(self.unregister_child)
def on_open(self, callback, timeout): """ Initialize a new timeout. :param callback: The callback to execute when the timeout reaches the end of its life. May be a coroutine function. :param timeout: The maximum time to wait for, in seconds. """ super().on_open() self.callback = callback self.timeout = timeout self.rev...
def revive(self, timeout=None): """ Revive the timeout. :param timeout: If not `None`, specifies a new timeout value to use. """ if timeout is not None: self.timeout = timeout self.revive_event.set()
def on_open(self, callback, period): """ Initialize a new timer. :param callback: The function or coroutine function to call on each tick. :param period: The interval of time between two ticks. """ super().on_open() self.callback = callback self.period = period self.reset_event = asyncio.Event(loop=self.loop)
def reset(self, period=None): """ Reset the internal timer, effectively causing the next tick to happen in `self.period` seconds. :param period: If not `None`, specifies a new period to use. """ if period is not None: self.period = period self.reset_event.set()
async def read(self): """ Read from the box in a blocking manner. :returns: An item from the box. """ result = await self._queue.get() self._can_write.set() if self._queue.empty(): self._can_read.clear() return result
def read_nowait(self): """ Read from the box in a non-blocking manner. If the box is empty, an exception is thrown. You should always check for emptiness with `empty` or `wait_not_empty` before calling this method. :returns: An item from the box. """ result = self._queue.get_nowait() self._can_write.set() if self._queu...
async def write(self, item): """ Write an item in the queue. :param item: The item. """ await self._queue.put(item) self._can_read.set() if self._queue.full(): self._can_write.clear()
def write_nowait(self, item): """ Write in the box in a non-blocking manner. If the box is full, an exception is thrown. You should always check for fullness with `full` or `wait_not_full` before calling this method. :param item: An item. """ self._queue.put_nowait(item) self._can_read.set() if self._queue.full(): self...
def clone(self): """ Clone the box. :returns: A new box with the same item queue. The cloned box is not closed, no matter the initial state of the original instance. """ result = AsyncBox(maxsize=self._maxsize, loop=self.loop) result._queue = self._queue result._can_read = self._can_read result._can_write = self._can_w...
def get_expr(self, ctx): """ Returns the MUF needed to get the contents of the lvalue. Returned MUF will push the contained value onto the stack. """ varname = ctx.lookup_variable(self.varname) if varname is None: val = ctx.lookup_constant(self.varname) if val: try: return val.generate_code(ctx) except AttributeError: ...
def set_expr(self, ctx): """ Returns the MUF needed to do an assign on the lvalue. (=) Returned MUF expects a value to be on the stack. """ if self.readonly: raise MuvError( "Cannot assign value to constant '%s'." % self.varname, position=self.position ) if self.declare: varname = ctx.declare_variable(self.varname) if ...
else: fmt = "{var} @ {idx} ->[] {var} !" return fmt.format( var=varname, idx=self.indexing[0].generate_code(ctx), ) if ctx.target in ['fb7']: if ctx.assign_level > 1: fmt = "dup {var} @ {{ {idx} }}list array_nested_set pop" else: fmt = "{var} @ {{ {idx} }}list array_nested_set pop" else: if ctx.assign_level > 1: fmt = ...
def oper_set_expr(self, ctx, oper, val): """ Returns the MUF needed to do an oper-assign on the lvalue. (+=, etc.) """ if self.readonly: raise MuvError( "Cannot assign value to constant '%s'." % self.varname, position=self.position ) varname = ctx.lookup_variable(self.varname) if varname is None: raise MuvError( "Undec...
" "-rot ->[] pop" ) else: if ctx.assign_level > 1: fmt = ( "{var} @ {idx} " "over over [] {val} {oper} " "dup -4 rotate " "rot rot ->[] {var} !" ) else: fmt = ( "{var} @ {idx} " "over over [] {val} {oper} " "rot rot ->[] {var} !" ) return fmt.format( var=varname, oper=oper, val=val.generate_code(ctx), idx=self.indexing...
" "over over array_nested_get {val} {oper} " "dup -4 rotate " "rot rot array_nested_set {var} !" ) else: fmt = ( "{var} @ {{ {idx} }}list " "over over array_nested_get {val} {oper} " "rot rot array_nested_set {var} !" ) return fmt.format( var=varname, oper=oper, val=val.generate_code(ctx), idx=" ".join( x.generate_code...
def unary_set_expr(self, ctx, oper, postoper=False): """ Returns the MUF needed to do an unary operation on the lvalue. (++, --.) """ if self.readonly: raise MuvError( "Cannot increment or decrement constant '%s'." % self.varname, position=self.position ) varname = ctx.lookup_variable(self.varname) if varname is None: ...
else: if postoper: fmt = ( "{idx} {var} @ " "dup 3 pick [] " "dup -4 rotate {oper} " "swap rot ->[] {var} !" ) else: fmt = ( "{idx} {var} @ " "dup 3 pick [] {oper} " "dup -4 rotate " "swap rot ->[] {var} !" ) return fmt.format( var=varname, oper=oper, idx=self.indexing[0].generate_code(ctx), ) if ctx.target in ['fb7']:...
"dup -4 rotate {oper} " "swap rot array_nested_set {var} !" ) else: fmt = ( "{{ {idx} }}list {var} @ " "dup 3 pick array_nested_get {oper} " "dup -4 rotate " "swap rot array_nested_set {var} !" ) return fmt.format( var=varname, oper=oper, idx=" ".join( x.generate_code(ctx) for x in self.indexing ) )
def del_expr(self, ctx): """ Returns the MUF needed to delete a given lvalue. (ie: array item) Returned MUF will set a bare variable to 0, and will remove the given indexed item for an indexed array or dictionary. """ if self.readonly: raise MuvError( "Cannot assign value to constant '%s'." % self.varname, position=sel...
{{ {idx} }}list array_nested_del dup {var} !".format( var=varname, idx=" ".join(x.generate_code(ctx) for x in self.indexing), )
def from_list(cls, values, settings): """ From a list of dicts (each dict is an `Instance.to_dict`) """ logger.debug('Creating Cluster from list') self = cls() self.settings = settings self.instances = [] for instance in values: uid, ip, port = instance['uid'], instance['ip'], instance['port'] new_instance = Instance.n...
def to_list(self): """ To a list of dicts (each dict is an instances) """ ret = [] for instance in self.instances: ret.append(instance.to_dict()) return ret
def create_bare(self): """ Create instances for the Bare provider """ self.instances = [] for ip in self.settings['NODES']: new_instance = Instance.new(settings=self.settings, cluster=self) new_instance.ip = ip self.instances.append(new_instance)
def create_cloud(self): """ Create instances for the cloud providers """ instances = [] for i in range(self.settings['NUMBER_NODES']): new_instance = Instance.new(settings=self.settings, cluster=self) instances.append(new_instance) create_nodes = [instance.create(suffix=i) for i, instance in enumerate(instances)] fetch...
def deserialize_uri(value): """ Deserialize a representation of a BNode or URIRef. """ if isinstance(value, BNode): return value if isinstance(value, URIRef): return value if not value: return None if not isinstance(value, basestring): raise ValueError("Cannot create URI from {0} of type {1}".format(value, value.__clas...
def serialize_uri(value): """ Serialize a BNode or URIRef. """ if isinstance(value, BNode): return value.n3() if isinstance(value, URIRef): return unicode(value) raise ValueError("Cannot get prepvalue for {0} of type {1}".format(value, value.__class__))
def crab_gateway_request(client, method, *args): ''' Utility function that helps making requests to the CRAB service. This is a specialised version of :func:`crabpy.client.crab_request` that allows adding extra functionality for the calls made by the gateway. :param client: A :class:`suds.client.Client` for the CRAB se...
def check_lazy_load_gewest(f): ''' Decorator function to lazy load a :class:`Gewest`. ''' def wrapper(self): gewest = self attribute = 'namen' if f.__name__ == 'naam' else f.__name__ if (getattr(gewest, '_%s' % attribute, None) is None): log.debug('Lazy loading Gewest %d', gewest.id) gewest.check_gateway() g = gewest.g...
def check_lazy_load_gemeente(f): ''' Decorator function to lazy load a :class:`Gemeente`. ''' def wrapper(*args): gemeente = args[0] if ( gemeente._centroid is None or gemeente._bounding_box is None or gemeente._taal_id is None or gemeente._metadata is None ): log.debug('Lazy loading Gemeente %d', gemeente.id) gemeente...
def check_lazy_load_straat(f): ''' Decorator function to lazy load a :class:`Straat`. ''' def wrapper(*args): straat = args[0] if ( straat._namen is None or straat._metadata is None ): log.debug('Lazy loading Straat %d', straat.id) straat.check_gateway() s = straat.gateway.get_straat_by_id(straat.id) straat._namen = s....
def check_lazy_load_huisnummer(f): ''' Decorator function to lazy load a :class:`Huisnummer`. ''' def wrapper(*args): huisnummer = args[0] if ( huisnummer._metadata is None ): log.debug('Lazy loading Huisnummer %d', huisnummer.id) huisnummer.check_gateway() h = huisnummer.gateway.get_huisnummer_by_id(huisnummer.id) hui...
def check_lazy_load_wegobject(f): ''' Decorator function to lazy load a :class:`Wegobject`. ''' def wrapper(*args): wegobject = args[0] if ( wegobject._centroid is None or wegobject._bounding_box is None or wegobject._metadata is None ): log.debug('Lazy loading Wegobject %d', wegobject.id) wegobject.check_gateway() w =...
def check_lazy_load_wegsegment(f): ''' Decorator function to lazy load a :class:`Wegsegment`. ''' def wrapper(*args): wegsegment = args[0] if ( wegsegment._methode_id is None or wegsegment._geometrie is None or wegsegment._metadata is None ): log.debug('Lazy loading Wegsegment %d', wegsegment.id) wegsegment.check_gatew...
def check_lazy_load_terreinobject(f): ''' Decorator function to lazy load a :class:`Terreinobject`. ''' def wrapper(*args): terreinobject = args[0] if ( terreinobject._centroid is None or terreinobject._bounding_box is None or terreinobject._metadata is None ): log.debug('Lazy loading Terreinobject %s', terreinobject.i...
def check_lazy_load_perceel(f): ''' Decorator function to lazy load a :class:`Perceel`. ''' def wrapper(*args): perceel = args[0] if perceel._centroid is None or perceel._metadata is None: log.debug('Lazy loading Perceel %s', perceel.id) perceel.check_gateway() p = perceel.gateway.get_perceel_by_id(perceel.id) perceel....