query
stringlengths
1
46.9k
pos
stringlengths
75
104k
neg
listlengths
12
12
scores
listlengths
12
12
Writes a block of bytes to the bus using I2C format to the specified command register
def write_block_data(self, cmd, block): """ Writes a block of bytes to the bus using I2C format to the specified command register """ self.bus.write_i2c_block_data(self.address, cmd, block) self.log.debug( "write_block_data: Wrote [%s] to command register 0x%02X" % ( ', '.join(['0x%02X' % x for x in block]), cmd ) )
[ "def write_byte(self, cmd, value):\n \"\"\"\n Writes an 8-bit byte to the specified command register\n \"\"\"\n self.bus.write_byte_data(self.address, cmd, value)\n self.log.debug(\n \"write_byte: Wrote 0x%02X to command register 0x%02X\" % (\n value, cmd...
[ 0.8196828961372375, 0.8017083406448364, 0.7951396107673645, 0.7795867919921875, 0.7707298398017883, 0.7705806493759155, 0.7704622745513916, 0.7655630707740784, 0.7603850960731506, 0.7573021650314331, 0.7540051937103271, 0.7528988718986511 ]
Read an 8-bit byte directly from the bus
def read_raw_byte(self): """ Read an 8-bit byte directly from the bus """ result = self.bus.read_byte(self.address) self.log.debug("read_raw_byte: Read 0x%02X from the bus" % result) return result
[ "def swd_read8(self, offset):\n \"\"\"Gets a unit of ``8`` bits from the input buffer.\n\n Args:\n self (JLink): the ``JLink`` instance\n offset (int): the offset (in bits) from which to start reading\n\n Returns:\n The integer read from the input buffer.\n \"\...
[ 0.7532457709312439, 0.753187894821167, 0.7348690032958984, 0.7280040979385376, 0.7246701717376709, 0.7218279242515564, 0.7157515287399292, 0.71510249376297, 0.714870035648346, 0.7133709192276001, 0.7075726389884949, 0.707072913646698 ]
Read a block of bytes from the bus from the specified command register Amount of bytes read in is defined by length
def read_block_data(self, cmd, length): """ Read a block of bytes from the bus from the specified command register Amount of bytes read in is defined by length """ results = self.bus.read_i2c_block_data(self.address, cmd, length) self.log.debug( "read_block_data: Read [%s] from command register 0x%02X" % ( ', '.join(['0x%02X' % x for x in results]), cmd ) ) return results
[ "def read_i2c_block_data(self, address, register, length):\n \"\"\"\n I2C block transactions do not limit the number of bytes transferred\n but the SMBus layer places a limit of 32 bytes.\n\n I2C Block Read: i2c_smbus_read_i2c_block_data()\n ======================================...
[ 0.7847602367401123, 0.7669231295585632, 0.7336359024047852, 0.7215681672096252, 0.7152820825576782, 0.7151080965995789, 0.7145650386810303, 0.7091506123542786, 0.7051747441291809, 0.7051296234130859, 0.7014334201812744, 0.7014119625091553 ]
Read an unsigned byte from the specified command register
def read_unsigned_byte(self, cmd): """ Read an unsigned byte from the specified command register """ result = self.bus.read_byte_data(self.address, cmd) self.log.debug( "read_unsigned_byte: Read 0x%02X from command register 0x%02X" % ( result, cmd ) ) return result
[ "def read_unsigned_word(self, cmd, little_endian=True):\n \"\"\"\n Read an unsigned word from the specified command register\n We assume the data is in little endian mode, if it is in big endian\n mode then set little_endian to False\n \"\"\"\n result = self.bus.read_word_d...
[ 0.797266960144043, 0.772947371006012, 0.7609961032867432, 0.7418611645698547, 0.7390509247779846, 0.7367530465126038, 0.7359464168548584, 0.7352967262268066, 0.7338888049125671, 0.7202451229095459, 0.7109748721122742, 0.7084289789199829 ]
Read an unsigned word from the specified command register We assume the data is in little endian mode, if it is in big endian mode then set little_endian to False
def read_unsigned_word(self, cmd, little_endian=True): """ Read an unsigned word from the specified command register We assume the data is in little endian mode, if it is in big endian mode then set little_endian to False """ result = self.bus.read_word_data(self.address, cmd) if not little_endian: result = ((result << 8) & 0xFF00) + (result >> 8) self.log.debug( "read_unsigned_word: Read 0x%04X from command register 0x%02X" % ( result, cmd ) ) return result
[ "def read_unsigned_byte(self, cmd):\n \"\"\"\n Read an unsigned byte from the specified command register\n \"\"\"\n result = self.bus.read_byte_data(self.address, cmd)\n self.log.debug(\n \"read_unsigned_byte: Read 0x%02X from command register 0x%02X\" % (\n ...
[ 0.7329193949699402, 0.7321426868438721, 0.7232850790023804, 0.6866912245750427, 0.6802865266799927, 0.67705899477005, 0.6747961640357971, 0.668343722820282, 0.6674012541770935, 0.6657078266143799, 0.6654201745986938, 0.6635306477546692 ]
Attempt to connect to an I2C bus
def __connect_to_bus(self, bus): """ Attempt to connect to an I2C bus """ def connect(bus_num): try: self.log.debug("Attempting to connect to bus %s..." % bus_num) self.bus = smbus.SMBus(bus_num) self.log.debug("Success") except IOError: self.log.debug("Failed") raise # If the bus is not explicitly stated, try 0 and then try 1 if that # fails if bus is None: try: connect(0) return except IOError: pass try: connect(1) return except IOError: raise else: try: connect(bus) return except IOError: raise
[ "def open(self, bus):\n \"\"\"\n Open a given i2c bus.\n\n :param bus: i2c bus number (e.g. 0 or 1)\n :type bus: int\n \"\"\"\n self.fd = os.open(\"/dev/i2c-{}\".format(bus), os.O_RDWR)\n self.funcs = self._get_funcs()", "function(options) {\n options = options ...
[ 0.7433919310569763, 0.7207122445106506, 0.7194353938102722, 0.713069498538971, 0.7109002470970154, 0.7105693221092224, 0.7105294466018677, 0.7097484469413757, 0.7061082720756531, 0.7052105069160461, 0.6963741779327393, 0.695769727230072 ]
Default user to the current version owner.
def get_formset(self, request, obj=None, **kwargs): """ Default user to the current version owner. """ data = super().get_formset(request, obj, **kwargs) if obj: data.form.base_fields['user'].initial = request.user.id return data
[ "def default_owner\n unless defined? @default_owner\n username = config[:username] ? config[:username].to_s : jdbc_connection.meta_data.user_name\n @default_owner = username.nil? ? nil : username.upcase\n end\n @default_owner\n end", "def get_owner(self, default=True):\n \"\...
[ 0.7370908856391907, 0.7131034731864929, 0.7005427479743958, 0.6957241892814636, 0.6943697333335876, 0.6932656764984131, 0.6921624541282654, 0.691453218460083, 0.6903442144393921, 0.6879087090492249, 0.6876251101493835, 0.6872333288192749 ]
Function reload Reload the full object to ensure sync
def reload(self): """ Function reload Reload the full object to ensure sync """ realData = self.load() self.clear() self.update(realData)
[ "def reload(self):\n \"\"\" Function reload\n Sync the full object\n \"\"\"\n self.load(self.api.get(self.objName, self.key))", "def refresh(self):\n # type: () -> None\n \"\"\"Refresh the object in place.\"\"\"\n src = self._client.reload(self)\n self.__dic...
[ 0.875714898109436, 0.7415770888328552, 0.7407538890838623, 0.7348027229309082, 0.7307147979736328, 0.7304747700691223, 0.7252180576324463, 0.7199515104293823, 0.7190576195716858, 0.7147949934005737, 0.7137467265129089, 0.7131270170211792 ]
Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman
def updateAfterDecorator(function): """ Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman """ def _updateAfterDecorator(self, *args, **kwargs): ret = function(self, *args, **kwargs) self.reload() return ret return _updateAfterDecorator
[ "def updateBeforeDecorator(function):\n \"\"\" Function updateAfterDecorator\n Decorator to ensure local dict is sync with remote foreman\n \"\"\"\n def _updateBeforeDecorator(self, *args, **kwargs):\n if self.forceFullSync:\n self.reload()\n return f...
[ 0.9027689099311829, 0.68341463804245, 0.677200973033905, 0.6769857406616211, 0.6768900752067566, 0.6674069166183472, 0.6669563055038452, 0.6637515425682068, 0.660396158695221, 0.6586720943450928, 0.657244861125946, 0.6561042070388794 ]
Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman
def updateBeforeDecorator(function): """ Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman """ def _updateBeforeDecorator(self, *args, **kwargs): if self.forceFullSync: self.reload() return function(self, *args, **kwargs) return _updateBeforeDecorator
[ "def updateAfterDecorator(function):\n \"\"\" Function updateAfterDecorator\n Decorator to ensure local dict is sync with remote foreman\n \"\"\"\n def _updateAfterDecorator(self, *args, **kwargs):\n ret = function(self, *args, **kwargs)\n self.reload()\n ...
[ 0.940290629863739, 0.68341463804245, 0.677200973033905, 0.6769857406616211, 0.6768900752067566, 0.6674069166183472, 0.6669563055038452, 0.6637515425682068, 0.660396158695221, 0.6586720943450928, 0.657244861125946, 0.6561042070388794 ]
Function load Get the list of all objects @return RETURN: A ForemanItem list
def load(self): """ Function load Get the list of all objects @return RETURN: A ForemanItem list """ return {x[self.index]: self.itemType(self.api, x['id'], self.objName, self.payloadObj, x) for x in self.api.list(self.objName, limit=self.searchLimit)}
[ "def load(self):\n \"\"\" Function load\n Get the list of all objects\n\n @return RETURN: A ForemanItem list\n \"\"\"\n cl_tmp = self.api.list(self.objName, limit=self.searchLimit).values()\n cl = []\n for i in cl_tmp:\n cl.extend(i)\n return {x[sel...
[ 0.8650457859039307, 0.8018741607666016, 0.7024894952774048, 0.6753305196762085, 0.6598423719406128, 0.6597557663917542, 0.655421257019043, 0.653819739818573, 0.6532294154167175, 0.6501277089118958, 0.648154616355896, 0.6473885774612427 ]
Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object
def checkAndCreate(self, key, payload): """ Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object """ if key not in self: self[key] = payload return self[key]['id']
[ "def checkAndCreate(self, key, payload):\n \"\"\" Function checkAndCreate\n Check if an object exists and create it if not\n\n @param key: The targeted object\n @param payload: The targeted object description\n @return RETURN: The id of the object\n \"\"\"\n if key n...
[ 0.9320217370986938, 0.7752333283424377, 0.7522791028022766, 0.7026407718658447, 0.674565315246582, 0.6636437773704529, 0.6603406667709351, 0.6586929559707642, 0.653120756149292, 0.653052031993866, 0.6461232304573059, 0.6450947523117065 ]
Class decorator stores all calls into list. Can be used until .invalidate() is called. :return: decorated class
def operations(): """ Class decorator stores all calls into list. Can be used until .invalidate() is called. :return: decorated class """ def decorator(func): @wraps(func) def wrapped_func(*args, **kwargs): self = args[0] assert self.__can_use, "User operation queue only in 'with' block" def defaults_dict(): f_args, varargs, keywords, defaults = inspect.getargspec(func) defaults = defaults or [] return dict(zip(f_args[-len(defaults)+len(args[1:]):], defaults[len(args[1:]):])) route_args = dict(defaults_dict().items() + kwargs.items()) func(*args, **kwargs) self.operations.append((func.__name__, args[1:], route_args, )) return wrapped_func def decorate(clazz): for attr in clazz.__dict__: if callable(getattr(clazz, attr)): setattr(clazz, attr, decorator(getattr(clazz, attr))) def __init__(self): # simple parameter-less constructor self.operations = [] self.__can_use = True def invalidate(self): self.__can_use = False clazz.__init__ = __init__ clazz.invalidate = invalidate return clazz return decorate
[ "def class_register(cls):\n \"\"\"Class decorator that allows to map LSP method names to class methods.\"\"\"\n cls.handler_registry = {}\n cls.sender_registry = {}\n for method_name in dir(cls):\n method = getattr(cls, method_name)\n if hasattr(method, '_handle'):\n cls.handler...
[ 0.6748773455619812, 0.672943651676178, 0.663416862487793, 0.6629220843315125, 0.6556463837623596, 0.6541969180107117, 0.6535748243331909, 0.6490762829780579, 0.6490561962127686, 0.6469916701316833, 0.6456177830696106, 0.6455515027046204 ]
Process actions in the publishing schedule. Returns the number of actions processed.
def process_actions(action_ids=None): """ Process actions in the publishing schedule. Returns the number of actions processed. """ actions_taken = 0 action_list = PublishAction.objects.prefetch_related( 'content_object', ).filter( scheduled_time__lte=timezone.now(), ) if action_ids is not None: action_list = action_list.filter(id__in=action_ids) for action in action_list: action.process_action() action.delete() actions_taken += 1 return actions_taken
[ "def process_action(self):\n \"\"\"\n Process the action and update the related object, returns a boolean if a change is made.\n \"\"\"\n if self.publish_version == self.UNPUBLISH_CHOICE:\n actioned = self._unpublish()\n else:\n actioned = self._publish()\n\n...
[ 0.7414658069610596, 0.7352325916290283, 0.7167717218399048, 0.7096720933914185, 0.7074881196022034, 0.7056097388267517, 0.705003559589386, 0.6979048252105713, 0.696949303150177, 0.6945710778236389, 0.6918920278549194, 0.685328483581543 ]
Return a boolean if Celery tasks are enabled for this app. If the ``GLITTER_PUBLISHER_CELERY`` setting is ``True`` or ``False`` - then that value will be used. However if the setting isn't defined, then this will be enabled automatically if Celery is installed.
def celery_enabled(): """ Return a boolean if Celery tasks are enabled for this app. If the ``GLITTER_PUBLISHER_CELERY`` setting is ``True`` or ``False`` - then that value will be used. However if the setting isn't defined, then this will be enabled automatically if Celery is installed. """ enabled = getattr(settings, 'GLITTER_PUBLISHER_CELERY', None) if enabled is None: try: import celery # noqa enabled = True except ImportError: enabled = False return enabled
[ "def get_celery_info():\n \"\"\"\n Check celery availability\n \"\"\"\n import celery\n if not getattr(settings, 'USE_CELERY', False):\n log.error(\"No celery config found. Set USE_CELERY in settings to enable.\")\n return {\"status\": NO_CONFIG}\n start = datetime.now()\n try:\n ...
[ 0.6862063407897949, 0.677836537361145, 0.6738221645355225, 0.6663748025894165, 0.6523762345314026, 0.6509922742843628, 0.6505083441734314, 0.6491189002990723, 0.640676736831665, 0.6372286081314087, 0.6347237825393677, 0.6333461403846741 ]
Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object
def checkAndCreate(self, key, payload): """ Function checkAndCreate Check if an object exists and create it if not @param key: The targeted object @param payload: The targeted object description @return RETURN: The id of the object """ if key not in self: if 'templates' in payload: templates = payload.pop('templates') self[key] = payload self.reload() return self[key]['id']
[ "def checkAndCreate(self, key, payload):\n \"\"\" Function checkAndCreate\n Check if an object exists and create it if not\n\n @param key: The targeted object\n @param payload: The targeted object description\n @return RETURN: The id of the object\n \"\"\"\n if key n...
[ 0.939257025718689, 0.7752333283424377, 0.7522791028022766, 0.7026407718658447, 0.674565315246582, 0.6636437773704529, 0.6603406667709351, 0.6586929559707642, 0.653120756149292, 0.653052031993866, 0.6461232304573059, 0.6450947523117065 ]
Collect new style (44.1+) return values to old-style kv-list
def __collect_interfaces_return(interfaces): """Collect new style (44.1+) return values to old-style kv-list""" acc = [] for (interfaceName, interfaceData) in interfaces.items(): signalValues = interfaceData.get("signals", {}) for (signalName, signalValue) in signalValues.items(): pinName = "{0}.{1}".format(interfaceName, signalName) acc.append({'id': pinName, 'value': signalValue}) return acc
[ "function postProcessList( list )\r\n\t{\r\n\t\tvar children = list.children,\r\n\t\t\tchild,\r\n\t\t\tattrs,\r\n\t\t\tcount = list.children.length,\r\n\t\t\tmatch,\r\n\t\t\tmergeStyle,\r\n\t\t\tstyleTypeRegexp = /list-style-type:(.*?)(?:;|$)/,\r\n\t\t\tstylesFilter = CKEDITOR.plugins.pastefromword.filters.stylesFi...
[ 0.6900656819343567, 0.6850228309631348, 0.6828471422195435, 0.6798000335693359, 0.6776096224784851, 0.6761053204536438, 0.6748420000076294, 0.6712998151779175, 0.6667713522911072, 0.6658219695091248, 0.6653779149055481, 0.6639884114265442 ]
Guess what api we are using and return as public api does. Private has {'id':'key', 'value':'keyvalue'} format, public has {'key':'keyvalue'}
def return_values(self): """ Guess what api we are using and return as public api does. Private has {'id':'key', 'value':'keyvalue'} format, public has {'key':'keyvalue'} """ j = self.json() #TODO: FIXME: get rid of old API when its support will be removed public_api_value = j.get('returnValues') old_private_value = j.get('endpoints') new_private_value = self.__collect_interfaces_return(j.get('interfaces', {})) retvals = new_private_value or old_private_value or public_api_value or [] # TODO: Public api hack. if self._router.public_api_in_use: return retvals return self.__parse(retvals)
[ "def api_get(uri, key=None):\n \"\"\"\n Simple API endpoint get, return only the keys we care about\n \"\"\"\n response = get_json(uri)\n\n if response:\n if type(response) == list:\n r = response[0]\n elif type(response) == dict:\n r = response\n\n if type(...
[ 0.6989791393280029, 0.6979104280471802, 0.6978617906570435, 0.6952900290489197, 0.6922489404678345, 0.6918883919715881, 0.6911982893943787, 0.6867008805274963, 0.6855074167251587, 0.6841657757759094, 0.6805800199508667, 0.6770697236061096 ]
Returns activitylog object severity - filter severity ('INFO', DEBUG') start/end - time or log text
def get_activitylog(self, after=None, severity=None, start=None, end=None): """ Returns activitylog object severity - filter severity ('INFO', DEBUG') start/end - time or log text """ if after: log_raw = self._router.get_instance_activitylog(org_id=self.organizationId, instance_id=self.instanceId, params={"after": after}).json() else: log_raw = self._router.get_instance_activitylog(org_id=self.organizationId, instance_id=self.instanceId).json() return ActivityLog(log_raw, severity=severity, start=start, end=end)
[ "def get_severity(self, alert):\n \"\"\"\n Get severity of correlated alert. Used to determine previous severity.\n \"\"\"\n query = {\n 'environment': alert.environment,\n 'resource': alert.resource,\n '$or': [\n {\n 'ev...
[ 0.6896112561225891, 0.6779490113258362, 0.6729638576507568, 0.6703992486000061, 0.6701990365982056, 0.6595064401626587, 0.6534167528152466, 0.6531382203102112, 0.6529648303985596, 0.6528253555297852, 0.6501330733299255, 0.6488714218139648 ]
return __cached_json, if accessed withing 300 ms. This allows to optimize calls when many parameters of entity requires withing short time.
def json(self): """ return __cached_json, if accessed withing 300 ms. This allows to optimize calls when many parameters of entity requires withing short time. """ if self.fresh(): return self.__cached_json # noinspection PyAttributeOutsideInit self.__last_read_time = time.time() self.__cached_json = self._router.get_instance(org_id=self.organizationId, instance_id=self.instanceId).json() return self.__cached_json
[ "def get_cache_data(request):\n if 'init' in request.POST:\n init = bool(float(request.POST['init']))\n else:\n init = False\n active_variables = []\n if 'variables[]' in request.POST:\n active_variables = request.POST.getlist('variables[]')\n \"\"\"\n else:\n active_va...
[ 0.7120234370231628, 0.6977940797805786, 0.6969521045684814, 0.6892980933189392, 0.6834937930107117, 0.6795302033424377, 0.6782623529434204, 0.6782003045082092, 0.6768079400062561, 0.6752720475196838, 0.6735942959785461, 0.6715708374977112 ]
Indicated most recent update of the instance, assumption based on: - if currentWorkflow exists, its startedAt time is most recent update. - else max of workflowHistory startedAt is most recent update.
def get_most_recent_update_time(self): """ Indicated most recent update of the instance, assumption based on: - if currentWorkflow exists, its startedAt time is most recent update. - else max of workflowHistory startedAt is most recent update. """ def parse_time(t): if t: return time.gmtime(t/1000) return None try: max_wf_started_at = max([i.get('startedAt') for i in self.workflowHistory]) return parse_time(max_wf_started_at) except ValueError: return None
[ "def _is_projection_updated_instance(self):\n \"\"\"\n This method tries to guess if instance was update since last time.\n If return True, definitely Yes, if False, this means more unknown\n :return: bool\n \"\"\"\n last = self._last_workflow_started_time\n if not s...
[ 0.7245467305183411, 0.6743656396865845, 0.6735358238220215, 0.67184978723526, 0.6716688871383667, 0.6702247262001038, 0.6640412211418152, 0.661932110786438, 0.6618991494178772, 0.6616625189781189, 0.6594071984291077, 0.6588082909584045 ]
This method tries to guess if instance was update since last time. If return True, definitely Yes, if False, this means more unknown :return: bool
def _is_projection_updated_instance(self): """ This method tries to guess if instance was update since last time. If return True, definitely Yes, if False, this means more unknown :return: bool """ last = self._last_workflow_started_time if not self._router.public_api_in_use: most_recent = self.get_most_recent_update_time() else: most_recent = None if last and most_recent: return last < most_recent return False
[ "def is_updated(self):\n \"\"\"\n Checks if a resource has been updated since last publish.\n Returns False if resource has not been published before.\n \"\"\"\n\n if not self.is_published:\n return False\n\n return sanitize_date(self.sys['published_at']) < sanit...
[ 0.7202460169792175, 0.7186499834060669, 0.7087157964706421, 0.7016710638999939, 0.7003849148750305, 0.6996637582778931, 0.6942580342292786, 0.691415548324585, 0.6844378709793091, 0.6832665205001831, 0.6798832416534424, 0.6771925091743469 ]
Find regexp in activitylog find record as if type are in description.
def find(self, item, description='', event_type=''): """ Find regexp in activitylog find record as if type are in description. """ # TODO: should be refactored, dumb logic if ': ' in item: splited = item.split(': ', 1) if splited[0] in self.TYPES: description = item.split(': ')[1] event_type = item.split(': ')[0] else: description = item else: if not description: description = item if event_type: found = [x['time'] for x in self.log if re.search(description, x['description']) and x['eventTypeText'] == event_type] else: found = [x['time'] for x in self.log if re.search(description, x['description'])] if len(found): return found raise exceptions.NotFoundError("Item '{}' is not found with (description='{}', event_type='{}')". format(item, description, event_type))
[ "def _regexp(expr, item):\n ''' REGEXP function for Sqlite\n '''\n reg = re.compile(expr)\n return reg.search(item) is not None", "def filter(self, record):\n \"\"\"\n Returns True if the record shall be logged. False otherwise.\n\n https://github.com/python/cpython/blob/2.7/Lib/l...
[ 0.6934164762496948, 0.6788412928581238, 0.6724658012390137, 0.6695852279663086, 0.6676204800605774, 0.6655965447425842, 0.6647224426269531, 0.6624881029129028, 0.6604191064834595, 0.6596809029579163, 0.6591915488243103, 0.6542932987213135 ]
Currently a small stub to create an instance of Checker for the passed ``infile`` and run its test functions through linting. Args: infile Returns: int: Number of flake8 errors raised.
def do_command_line(infile: typing.IO[str]) -> int: """ Currently a small stub to create an instance of Checker for the passed ``infile`` and run its test functions through linting. Args: infile Returns: int: Number of flake8 errors raised. """ lines = infile.readlines() tree = ast.parse(''.join(lines)) checker = Checker(tree, lines, infile.name) checker.load() errors = [] # type: typing.List[AAAError] for func in checker.all_funcs(skip_noqa=True): try: errors = list(func.check_all()) except ValidationError as error: errors = [error.to_aaa()] print(func.__str__(errors), end='') return len(errors)
[ "def check(codeString, filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):\n \"\"\"Check the Python source given by codeString for unfrosted flakes.\"\"\"\n\n if not settings_path and filename:\n settings_path = os.path.dirname(os.path.abspath(filename))\n settings_path...
[ 0.7110608220100403, 0.7024708390235901, 0.6943210363388062, 0.6942464113235474, 0.6909804940223694, 0.6906939148902893, 0.6896222829818726, 0.6877042651176453, 0.6864295601844788, 0.6849697828292847, 0.6821961402893066, 0.6819117665290833 ]
finds the appropriate properties (spec) of a module, and sets its loader.
def find_spec(self, fullname, path, target=None): '''finds the appropriate properties (spec) of a module, and sets its loader.''' if not path: path = [os.getcwd()] if "." in fullname: name = fullname.split(".")[-1] else: name = fullname for entry in path: if os.path.isdir(os.path.join(entry, name)): # this module has child modules filename = os.path.join(entry, name, "__init__.py") submodule_locations = [os.path.join(entry, name)] else: filename = os.path.join(entry, name + ".py") submodule_locations = None if not os.path.exists(filename): continue return spec_from_file_location(fullname, filename, loader=MyLoader(filename), submodule_search_locations=submodule_locations) return None
[ "def find_module(cls, fullname, path=None):\n \"\"\"find the module on sys.path or 'path' based on sys.path_hooks and\n sys.path_importer_cache.\n This method is for python2 only\n \"\"\"\n spec = cls.find_spec(fullname, path)\n if spec is None:\n return None\n ...
[ 0.747175931930542, 0.7420939207077026, 0.7406797409057617, 0.7373334765434265, 0.7310171723365784, 0.7296516299247742, 0.7245499491691589, 0.7207825183868408, 0.7194115519523621, 0.7193523645401001, 0.7174927592277527, 0.7132523655891418 ]
import the source code, transforma it before executing it so that it is known to Python.
def exec_module(self, module): '''import the source code, transforma it before executing it so that it is known to Python.''' global MAIN_MODULE_NAME if module.__name__ == MAIN_MODULE_NAME: module.__name__ = "__main__" MAIN_MODULE_NAME = None with open(self.filename) as f: source = f.read() if transforms.transformers: source = transforms.transform(source) else: for line in source.split('\n'): if transforms.FROM_EXPERIMENTAL.match(line): ## transforms.transform will extract all such relevant ## lines and add them all relevant transformers source = transforms.transform(source) break exec(source, vars(module))
[ "def transform(source):\n '''Used to convert the source code, making use of known transformers.\n\n \"transformers\" are modules which must contain a function\n\n transform_source(source)\n\n which returns a tranformed source.\n Some transformers (for example, those found in the stand...
[ 0.792877733707428, 0.7396855354309082, 0.7372424602508545, 0.7340986728668213, 0.7337856888771057, 0.7240535616874695, 0.7217997908592224, 0.716796875, 0.7163119316101074, 0.715809166431427, 0.712336003780365, 0.7094584703445435 ]
Iterate through multiple lists or arrays of equal size
def _izip(*iterables): """ Iterate through multiple lists or arrays of equal size """ # This izip routine is from itertools # izip('ABCD', 'xy') --> Ax By iterators = map(iter, iterables) while iterators: yield tuple(map(next, iterators))
[ "public static void iterate(int dimension, int n, int[] size, int[] res, int dimension2, int n2, int[] size2,\n int[] res2, CoordinateFunction func) {\n if (dimension >= n || dimension2 >= n2) {\n // stop clause\n func.process(ArrayUtil.toLongArray(res), Ar...
[ 0.7043029069900513, 0.7027319073677063, 0.6970442533493042, 0.6964612007141113, 0.6948021054267883, 0.6942374110221863, 0.6927012801170349, 0.6896812319755554, 0.6895675659179688, 0.6884126663208008, 0.6859806180000305, 0.6798259019851685 ]
Check and convert any input scalar or array to numpy array
def _checkinput(zi, Mi, z=False, verbose=None): """ Check and convert any input scalar or array to numpy array """ # How many halo redshifts provided? zi = np.array(zi, ndmin=1, dtype=float) # How many halo masses provided? Mi = np.array(Mi, ndmin=1, dtype=float) # Check the input sizes for zi and Mi make sense, if not then exit unless # one axis is length one, then replicate values to the size of the other if (zi.size > 1) and (Mi.size > 1): if(zi.size != Mi.size): print("Error ambiguous request") print("Need individual redshifts for all haloes provided ") print("Or have all haloes at same redshift ") return(-1) elif (zi.size == 1) and (Mi.size > 1): if verbose: print("Assume zi is the same for all Mi halo masses provided") # Replicate redshift for all halo masses zi = np.ones_like(Mi)*zi[0] elif (Mi.size == 1) and (zi.size > 1): if verbose: print("Assume Mi halo masses are the same for all zi provided") # Replicate redshift for all halo masses Mi = np.ones_like(zi)*Mi[0] else: if verbose: print("A single Mi and zi provided") # Very simple test for size / type of incoming array # just in case numpy / list given if z is False: # Didn't pass anything, set zi = z lenzout = 1 else: # If something was passed, convert to 1D NumPy array z = np.array(z, ndmin=1, dtype=float) lenzout = z.size return(zi, Mi, z, zi.size, Mi.size, lenzout)
[ "def _check_inputs(z, m):\n \"\"\"Check inputs are arrays of same length or array and a scalar.\"\"\"\n try:\n nz = len(z)\n z = np.array(z)\n except TypeError:\n z = np.array([z])\n nz = len(z)\n try:\n nm = len(m)\n m = np.array(m)\n except TypeError:\n ...
[ 0.765717625617981, 0.7596739530563354, 0.7529251575469971, 0.7414947152137756, 0.7377985715866089, 0.729101300239563, 0.7281977534294128, 0.7256779074668884, 0.7240608930587769, 0.7231460213661194, 0.7225255966186523, 0.7208993434906006 ]
Find cosmological parameters for named cosmo in cosmology.py list
def getcosmo(cosmology): """ Find cosmological parameters for named cosmo in cosmology.py list """ defaultcosmologies = {'dragons': cg.DRAGONS(), 'wmap1': cg.WMAP1_Mill(), 'wmap3': cg.WMAP3_ML(), 'wmap5': cg.WMAP5_mean(), 'wmap7': cg.WMAP7_ML(), 'wmap9': cg.WMAP9_ML(), 'wmap1_lss': cg.WMAP1_2dF_mean(), 'wmap3_mean': cg.WMAP3_mean(), 'wmap5_ml': cg.WMAP5_ML(), 'wmap5_lss': cg.WMAP5_BAO_SN_mean(), 'wmap7_lss': cg.WMAP7_BAO_H0_mean(), 'planck13': cg.Planck_2013(), 'planck15': cg.Planck_2015()} if isinstance(cosmology, dict): # User providing their own variables cosmo = cosmology if 'A_scaling' not in cosmology.keys(): A_scaling = getAscaling(cosmology, newcosmo=True) cosmo.update({'A_scaling': A_scaling}) # Add extra variables by hand that cosmolopy requires # note that they aren't used (set to zero) for paramnames in cg.WMAP5_mean().keys(): if paramnames not in cosmology.keys(): cosmo.update({paramnames: 0}) elif cosmology.lower() in defaultcosmologies.keys(): # Load by name of cosmology instead cosmo = defaultcosmologies[cosmology.lower()] A_scaling = getAscaling(cosmology) cosmo.update({'A_scaling': A_scaling}) else: print("You haven't passed a dict of cosmological parameters ") print("OR a recognised cosmology, you gave %s" % (cosmology)) # No idea why this has to be done by hand but should be O_k = 0 cosmo = cp.distance.set_omega_k_0(cosmo) # Use the cosmology as **cosmo passed to cosmolopy routines return(cosmo)
[ "def Planck_2015(flat=False, extras=True):\n \"\"\"Planck 2015 XII: Cosmological parameters Table 4\n column Planck TT, TE, EE + lowP + lensing + ext\n from Ade et al. (2015) A&A in press (arxiv:1502.01589v1)\n\n Parameters\n ----------\n\n flat: boolean\n\n If True, sets omega_lambda_0 = 1 -...
[ 0.700488269329071, 0.6922816038131714, 0.6892850995063782, 0.6832613945007324, 0.670433521270752, 0.6544787287712097, 0.6512612104415894, 0.6474101543426514, 0.6463600993156433, 0.6381969451904297, 0.6360576152801514, 0.6343229413032532 ]
Output the cosmology to a string for writing to file
def _getcosmoheader(cosmo): """ Output the cosmology to a string for writing to file """ cosmoheader = ("# Cosmology (flat) Om:{0:.3f}, Ol:{1:.3f}, h:{2:.2f}, " "sigma8:{3:.3f}, ns:{4:.2f}".format( cosmo['omega_M_0'], cosmo['omega_lambda_0'], cosmo['h'], cosmo['sigma_8'], cosmo['n'])) return(cosmoheader)
[ "def getcosmo(cosmology):\n \"\"\" Find cosmological parameters for named cosmo in cosmology.py list \"\"\"\n\n defaultcosmologies = {'dragons': cg.DRAGONS(), 'wmap1': cg.WMAP1_Mill(),\n 'wmap3': cg.WMAP3_ML(), 'wmap5': cg.WMAP5_mean(),\n 'wmap7': cg.WMAP7_ML(...
[ 0.6981759667396545, 0.6744505763053894, 0.6708426475524902, 0.6707870960235596, 0.660865843296051, 0.6604917645454407, 0.6592658162117004, 0.6579853892326355, 0.656875491142273, 0.6565803289413452, 0.6555835604667664, 0.6547509431838989 ]
NFW conc from Duffy 08 Table 1 for halo mass and redshift
def cduffy(z, M, vir='200crit', relaxed=True): """ NFW conc from Duffy 08 Table 1 for halo mass and redshift""" if(vir == '200crit'): if relaxed: params = [6.71, -0.091, -0.44] else: params = [5.71, -0.084, -0.47] elif(vir == 'tophat'): if relaxed: params = [9.23, -0.090, -0.69] else: params = [7.85, -0.081, -0.71] elif(vir == '200mean'): if relaxed: params = [11.93, -0.090, -0.99] else: params = [10.14, -0.081, -1.01] else: print("Didn't recognise the halo boundary definition provided %s" % (vir)) return(params[0] * ((M/(2e12/0.72))**params[1]) * ((1+z)**params[2]))
[ "def c_Duffy(z, m, h=h):\n \"\"\"Concentration from c(M) relation published in Duffy et al. (2008).\n\n Parameters\n ----------\n z : float or array_like\n Redshift(s) of halos.\n m : float or array_like\n Mass(es) of halos (m200 definition), in units of solar masses.\n h : float, op...
[ 0.7682119011878967, 0.7114080190658569, 0.690197765827179, 0.6887338757514954, 0.6878402829170227, 0.6870186924934387, 0.6866941452026367, 0.6808981895446777, 0.6693978309631348, 0.6669307351112366, 0.6632845997810364, 0.6630220413208008 ]
Perturb best-fit constant of proportionality Ascaling for rho_crit - rho_2 relation for unknown cosmology (Correa et al 2015c) Parameters ---------- cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- float The perturbed 'A' relation between rho_2 and rho_crit for the cosmology Raises ------
def _delta_sigma(**cosmo): """ Perturb best-fit constant of proportionality Ascaling for rho_crit - rho_2 relation for unknown cosmology (Correa et al 2015c) Parameters ---------- cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- float The perturbed 'A' relation between rho_2 and rho_crit for the cosmology Raises ------ """ M8_cosmo = cp.perturbation.radius_to_mass(8, **cosmo) perturbed_A = (0.796/cosmo['sigma_8']) * \ (M8_cosmo/2.5e14)**((cosmo['n']-0.963)/6) return(perturbed_A)
[ "def getcosmo(cosmology):\n \"\"\" Find cosmological parameters for named cosmo in cosmology.py list \"\"\"\n\n defaultcosmologies = {'dragons': cg.DRAGONS(), 'wmap1': cg.WMAP1_Mill(),\n 'wmap3': cg.WMAP3_ML(), 'wmap5': cg.WMAP5_mean(),\n 'wmap7': cg.WMAP7_ML(...
[ 0.7133972644805908, 0.6964385509490967, 0.686434805393219, 0.677892804145813, 0.674342930316925, 0.673985481262207, 0.6658235192298889, 0.6623619198799133, 0.6607682704925537, 0.6578128933906555, 0.6576458215713501, 0.6519357562065125 ]
Returns the normalisation constant between Rho_-2 and Rho_mean(z_formation) for a given cosmology Parameters ---------- cosmology : str or dict Can be named cosmology, default WMAP7 (aka DRAGONS), or DRAGONS, WMAP1, WMAP3, WMAP5, WMAP7, WMAP9, Planck13, Planck15 or dictionary similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} newcosmo : str, optional If cosmology is not from predefined list have to perturbation A_scaling variable. Defaults to None. Returns ------- float The scaled 'A' relation between rho_2 and rho_crit for the cosmology
def getAscaling(cosmology, newcosmo=None): """ Returns the normalisation constant between Rho_-2 and Rho_mean(z_formation) for a given cosmology Parameters ---------- cosmology : str or dict Can be named cosmology, default WMAP7 (aka DRAGONS), or DRAGONS, WMAP1, WMAP3, WMAP5, WMAP7, WMAP9, Planck13, Planck15 or dictionary similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} newcosmo : str, optional If cosmology is not from predefined list have to perturbation A_scaling variable. Defaults to None. Returns ------- float The scaled 'A' relation between rho_2 and rho_crit for the cosmology """ # Values from Correa 15c defaultcosmologies = {'dragons': 887, 'wmap1': 853, 'wmap3': 850, 'wmap5': 887, 'wmap7': 887, 'wmap9': 950, 'wmap1_lss': 853, 'wmap3_mean': 850, 'wmap5_ml': 887, 'wmap5_lss': 887, 'wmap7_lss': 887, 'planck13': 880, 'planck15': 880} if newcosmo: # Scale from default WMAP5 cosmology using Correa et al 14b eqn C1 A_scaling = defaultcosmologies['wmap5'] * _delta_sigma(**cosmology) else: if cosmology.lower() in defaultcosmologies.keys(): A_scaling = defaultcosmologies[cosmology.lower()] else: print("Error, don't recognise your cosmology for A_scaling ") print("You provided %s" % (cosmology)) return(A_scaling)
[ "def _delta_sigma(**cosmo):\n \"\"\" Perturb best-fit constant of proportionality Ascaling for\n rho_crit - rho_2 relation for unknown cosmology (Correa et al 2015c)\n\n Parameters\n ----------\n cosmo : dict\n Dictionary of cosmological parameters, similar in format to:\n {'N_nu': ...
[ 0.7695544958114624, 0.7592920660972595, 0.695005476474762, 0.6937953233718872, 0.6598114967346191, 0.6570345759391785, 0.6557053923606873, 0.6541890501976013, 0.6424201726913452, 0.6384008526802063, 0.6375933885574341, 0.6364959478378296 ]
Returns integral of the linear growth factor from z=200 to z=z
def _int_growth(z, **cosmo): """ Returns integral of the linear growth factor from z=200 to z=z """ zmax = 200 if hasattr(z, "__len__"): for zval in z: assert(zval < zmax) else: assert(z < zmax) y, yerr = scipy.integrate.quad( lambda z: (1 + z)/(cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(1.5), z, zmax) return(y)
[ "def _deriv_growth(z, **cosmo):\n \"\"\" Returns derivative of the linear growth factor at z\n for a given cosmology **cosmo \"\"\"\n\n inv_h = (cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(-0.5)\n fz = (1 + z) * inv_h**3\n\n deriv_g = growthfactor(z, norm=True, **cosmo)*(inv_h**2) ...
[ 0.7333215475082397, 0.7216445803642273, 0.7022789716720581, 0.6984469890594482, 0.6969737410545349, 0.6935060024261475, 0.6865224838256836, 0.6841789484024048, 0.6812206506729126, 0.6792978644371033, 0.6761254072189331, 0.6734105944633484 ]
Returns derivative of the linear growth factor at z for a given cosmology **cosmo
def _deriv_growth(z, **cosmo): """ Returns derivative of the linear growth factor at z for a given cosmology **cosmo """ inv_h = (cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(-0.5) fz = (1 + z) * inv_h**3 deriv_g = growthfactor(z, norm=True, **cosmo)*(inv_h**2) *\ 1.5 * cosmo['omega_M_0'] * (1 + z)**2 -\ fz * growthfactor(z, norm=True, **cosmo)/_int_growth(z, **cosmo) return(deriv_g)
[ "def _int_growth(z, **cosmo):\n \"\"\" Returns integral of the linear growth factor from z=200 to z=z \"\"\"\n\n zmax = 200\n\n if hasattr(z, \"__len__\"):\n for zval in z:\n assert(zval < zmax)\n else:\n assert(z < zmax)\n\n y, yerr = scipy.integrate.quad(\n lambda z:...
[ 0.8032103180885315, 0.7147066593170166, 0.7002454996109009, 0.6993910074234009, 0.6919756531715393, 0.6883453726768494, 0.6882690191268921, 0.6829437017440796, 0.6825976371765137, 0.6817625164985657, 0.6801071763038635, 0.6786118745803833 ]
Returns linear growth factor at a given redshift, normalised to z=0 by default, for a given cosmology Parameters ---------- z : float or numpy array The redshift at which the growth factor should be calculated norm : boolean, optional If true then normalise the growth factor to z=0 case defaults True cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- float or numpy array The growth factor at a range of redshifts 'z' Raises ------
def growthfactor(z, norm=True, **cosmo): """ Returns linear growth factor at a given redshift, normalised to z=0 by default, for a given cosmology Parameters ---------- z : float or numpy array The redshift at which the growth factor should be calculated norm : boolean, optional If true then normalise the growth factor to z=0 case defaults True cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- float or numpy array The growth factor at a range of redshifts 'z' Raises ------ """ H = np.sqrt(cosmo['omega_M_0'] * (1 + z)**3 + cosmo['omega_lambda_0']) growthval = H * _int_growth(z, **cosmo) if norm: growthval /= _int_growth(0, **cosmo) return(growthval)
[ "def _deriv_growth(z, **cosmo):\n \"\"\" Returns derivative of the linear growth factor at z\n for a given cosmology **cosmo \"\"\"\n\n inv_h = (cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(-0.5)\n fz = (1 + z) * inv_h**3\n\n deriv_g = growthfactor(z, norm=True, **cosmo)*(inv_h**2) ...
[ 0.7684199213981628, 0.74662846326828, 0.6595988869667053, 0.6529549360275269, 0.6396779417991638, 0.6359613537788391, 0.6332837343215942, 0.6323447823524475, 0.6304025650024414, 0.6291844248771667, 0.6244160532951355, 0.6230838894844055 ]
Trial function to solve 2 eqns (17 and 18) from Correa et al. (2015c) for 1 unknown, i.e. concentration, returned by a minimisation call
def _minimize_c(c, z=0, a_tilde=1, b_tilde=-1, Ascaling=900, omega_M_0=0.25, omega_lambda_0=0.75): """ Trial function to solve 2 eqns (17 and 18) from Correa et al. (2015c) for 1 unknown, i.e. concentration, returned by a minimisation call """ # Fn 1 (LHS of Eqn 18) Y1 = np.log(2) - 0.5 Yc = np.log(1+c) - c/(1+c) f1 = Y1/Yc # Fn 2 (RHS of Eqn 18) # Eqn 14 - Define the mean inner density rho_2 = 200 * c**3 * Y1 / Yc # Eqn 17 rearranged to solve for Formation Redshift # essentially when universe had rho_2 density zf = (((1 + z)**3 + omega_lambda_0/omega_M_0) * (rho_2/Ascaling) - omega_lambda_0/omega_M_0)**(1/3) - 1 # RHS of Eqn 19 f2 = ((1 + zf - z)**a_tilde) * np.exp((zf - z) * b_tilde) # LHS - RHS should be zero for the correct concentration return(f1-f2)
[ "def pressision_try(orbitals, U, beta, step):\n \"\"\"perform a better initial guess of lambda\n no improvement\"\"\"\n mu, lam = main(orbitals, U, beta, step)\n mu2, lam2 = linspace(0, U*orbitals, step), zeros(step)\n for i in range(99):\n lam2[i+1] = fsolve(restriction, lam2[i], (mu2[i+1]...
[ 0.6632798910140991, 0.6630605459213257, 0.6583905220031738, 0.6583086848258972, 0.6556440591812134, 0.6548488140106201, 0.6548237800598145, 0.6544963717460632, 0.6540391445159912, 0.653718113899231, 0.6535154581069946, 0.6519917845726013 ]
Rearrange eqn 18 from Correa et al (2015c) to return formation redshift for a concentration at a given redshift Parameters ---------- c : float / numpy array Concentration of halo z : float / numpy array Redshift of halo with concentration c Ascaling : float Cosmological dependent scaling between densities, use function getAscaling('WMAP5') if unsure. Default is 900. omega_M_0 : float Mass density of the universe. Default is 0.25 omega_lambda_0 : float Dark Energy density of the universe. Default is 0.75 Returns ------- zf : float / numpy array Formation redshift for halo of concentration 'c' at redshift 'z'
def formationz(c, z, Ascaling=900, omega_M_0=0.25, omega_lambda_0=0.75): """ Rearrange eqn 18 from Correa et al (2015c) to return formation redshift for a concentration at a given redshift Parameters ---------- c : float / numpy array Concentration of halo z : float / numpy array Redshift of halo with concentration c Ascaling : float Cosmological dependent scaling between densities, use function getAscaling('WMAP5') if unsure. Default is 900. omega_M_0 : float Mass density of the universe. Default is 0.25 omega_lambda_0 : float Dark Energy density of the universe. Default is 0.75 Returns ------- zf : float / numpy array Formation redshift for halo of concentration 'c' at redshift 'z' """ Y1 = np.log(2) - 0.5 Yc = np.log(1+c) - c/(1+c) rho_2 = 200*(c**3)*Y1/Yc zf = (((1+z)**3 + omega_lambda_0/omega_M_0) * (rho_2/Ascaling) - omega_lambda_0/omega_M_0)**(1/3) - 1 return(zf)
[ "def _minimize_c(c, z=0, a_tilde=1, b_tilde=-1,\n Ascaling=900, omega_M_0=0.25, omega_lambda_0=0.75):\n \"\"\" Trial function to solve 2 eqns (17 and 18) from Correa et al. (2015c)\n for 1 unknown, i.e. concentration, returned by a minimisation call \"\"\"\n\n # Fn 1 (LHS of Eqn 18)\n\n ...
[ 0.7827358245849609, 0.7338221073150635, 0.6758645176887512, 0.6744975447654724, 0.6709538102149963, 0.6624672412872314, 0.6606255173683167, 0.6586936712265015, 0.6488917469978333, 0.6486613750457764, 0.6458823084831238, 0.6458626389503479 ]
Calculate growth rate indices a_tilde and b_tilde Parameters ---------- zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- (a_tilde, b_tilde) : float
def calc_ab(zi, Mi, **cosmo): """ Calculate growth rate indices a_tilde and b_tilde Parameters ---------- zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- (a_tilde, b_tilde) : float """ # When zi = 0, the a_tilde becomes alpha and b_tilde becomes beta # Eqn 23 of Correa et al 2015a (analytically solve from Eqn 16 and 17) # Arbitray formation redshift, z_-2 in COM is more physically motivated zf = -0.0064 * (np.log10(Mi))**2 + 0.0237 * (np.log10(Mi)) + 1.8837 # Eqn 22 of Correa et al 2015a q = 4.137 * zf**(-0.9476) # Radius of a mass Mi R_Mass = cp.perturbation.mass_to_radius(Mi, **cosmo) # [Mpc] # Radius of a mass Mi/q Rq_Mass = cp.perturbation.mass_to_radius(Mi/q, **cosmo) # [Mpc] # Mass variance 'sigma' evaluate at z=0 to a good approximation sig, err_sig = cp.perturbation.sigma_r(R_Mass, 0, **cosmo) # [Mpc] sigq, err_sigq = cp.perturbation.sigma_r(Rq_Mass, 0, **cosmo) # [Mpc] f = (sigq**2 - sig**2)**(-0.5) # Eqn 9 and 10 from Correa et al 2015c # (generalised to zi from Correa et al 2015a's z=0 special case) # a_tilde is power law growth rate a_tilde = (np.sqrt(2/np.pi) * 1.686 * _deriv_growth(zi, **cosmo) / growthfactor(zi, norm=True, **cosmo)**2 + 1)*f # b_tilde is exponential growth rate b_tilde = -f return(a_tilde, b_tilde)
[ "def _deriv_growth(z, **cosmo):\n \"\"\" Returns derivative of the linear growth factor at z\n for a given cosmology **cosmo \"\"\"\n\n inv_h = (cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(-0.5)\n fz = (1 + z) * inv_h**3\n\n deriv_g = growthfactor(z, norm=True, **cosmo)*(inv_h**2) ...
[ 0.6879026889801025, 0.6802611947059631, 0.6461231708526611, 0.6325393915176392, 0.6288246512413025, 0.6253081560134888, 0.6240700483322144, 0.6204337477684021, 0.6187481880187988, 0.6157792210578918, 0.6153101325035095, 0.613068163394928 ]
Calculate accretion rate and mass history of a halo at any redshift 'z' with mass 'Mi' at a lower redshift 'z' Parameters ---------- z : float Redshift to solve acc_rate / mass history. Note zi<z zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- (dMdt, Mz) : float Accretion rate [Msol/yr], halo mass [Msol] at redshift 'z'
def acc_rate(z, zi, Mi, **cosmo): """ Calculate accretion rate and mass history of a halo at any redshift 'z' with mass 'Mi' at a lower redshift 'z' Parameters ---------- z : float Redshift to solve acc_rate / mass history. Note zi<z zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- (dMdt, Mz) : float Accretion rate [Msol/yr], halo mass [Msol] at redshift 'z' """ # Find parameters a_tilde and b_tilde for initial redshift # use Eqn 9 and 10 of Correa et al. (2015c) a_tilde, b_tilde = calc_ab(zi, Mi, **cosmo) # Halo mass at z, in Msol # use Eqn 8 in Correa et al. (2015c) Mz = Mi * ((1 + z - zi)**a_tilde) * (np.exp(b_tilde * (z - zi))) # Accretion rate at z, Msol yr^-1 # use Eqn 11 from Correa et al. (2015c) dMdt = 71.6 * (Mz/1e12) * (cosmo['h']/0.7) *\ (-a_tilde / (1 + z - zi) - b_tilde) * (1 + z) *\ np.sqrt(cosmo['omega_M_0']*(1 + z)**3+cosmo['omega_lambda_0']) return(dMdt, Mz)
[ "def MAH(z, zi, Mi, **cosmo):\n \"\"\" Calculate mass accretion history by looping function acc_rate\n over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi'\n\n Parameters\n ----------\n z : float / numpy array\n Redshift to output MAH over. Note zi<z always\n zi : float\n ...
[ 0.744875967502594, 0.6870329976081848, 0.6793551445007324, 0.668692946434021, 0.6536861658096313, 0.6517687439918518, 0.6454139947891235, 0.63826584815979, 0.6368201971054077, 0.6361081600189209, 0.6345521211624146, 0.6290093064308167 ]
Calculate mass accretion history by looping function acc_rate over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi' Parameters ---------- z : float / numpy array Redshift to output MAH over. Note zi<z always zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- (dMdt, Mz) : float / numpy arrays of equivalent size to 'z' Accretion rate [Msol/yr], halo mass [Msol] at redshift 'z'
def MAH(z, zi, Mi, **cosmo): """ Calculate mass accretion history by looping function acc_rate over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi' Parameters ---------- z : float / numpy array Redshift to output MAH over. Note zi<z always zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- (dMdt, Mz) : float / numpy arrays of equivalent size to 'z' Accretion rate [Msol/yr], halo mass [Msol] at redshift 'z' """ # Ensure that z is a 1D NumPy array z = np.array(z, ndmin=1, dtype=float) # Create a full array dMdt_array = np.empty_like(z) Mz_array = np.empty_like(z) for i_ind, zval in enumerate(z): # Solve the accretion rate and halo mass at each redshift step dMdt, Mz = acc_rate(zval, zi, Mi, **cosmo) dMdt_array[i_ind] = dMdt Mz_array[i_ind] = Mz return(dMdt_array, Mz_array)
[ "def acc_rate(z, zi, Mi, **cosmo):\n \"\"\" Calculate accretion rate and mass history of a halo at any\n redshift 'z' with mass 'Mi' at a lower redshift 'z'\n\n Parameters\n ----------\n z : float\n Redshift to solve acc_rate / mass history. Note zi<z\n zi : float\n Redshift\n ...
[ 0.6949988007545471, 0.6794018149375916, 0.6675459742546082, 0.6660123467445374, 0.6598291397094727, 0.6488460302352905, 0.646306037902832, 0.6451810002326965, 0.6433944702148438, 0.639427661895752, 0.6363394856452942, 0.63124018907547 ]
Calculate concentration for halo of mass 'M' at redshift 'z' Parameters ---------- z : float / numpy array Redshift to find concentration of halo M : float / numpy array Halo mass at redshift 'z'. Must be same size as 'z' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- (c_array, sig_array, nu_array, zf_array) : float / numpy arrays of equivalent size to 'z' and 'M'. Variables are Concentration, Mass Variance 'sigma' this corresponds too, the dimnesionless fluctuation this represents and formation redshift
def COM(z, M, **cosmo): """ Calculate concentration for halo of mass 'M' at redshift 'z' Parameters ---------- z : float / numpy array Redshift to find concentration of halo M : float / numpy array Halo mass at redshift 'z'. Must be same size as 'z' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} Returns ------- (c_array, sig_array, nu_array, zf_array) : float / numpy arrays of equivalent size to 'z' and 'M'. Variables are Concentration, Mass Variance 'sigma' this corresponds too, the dimnesionless fluctuation this represents and formation redshift """ # Check that z and M are arrays z = np.array(z, ndmin=1, dtype=float) M = np.array(M, ndmin=1, dtype=float) # Create array c_array = np.empty_like(z) sig_array = np.empty_like(z) nu_array = np.empty_like(z) zf_array = np.empty_like(z) for i_ind, (zval, Mval) in enumerate(_izip(z, M)): # Evaluate the indices at each redshift and mass combination # that you want a concentration for, different to MAH which # uses one a_tilde and b_tilde at the starting redshift only a_tilde, b_tilde = calc_ab(zval, Mval, **cosmo) # Minimize equation to solve for 1 unknown, 'c' c = scipy.optimize.brentq(_minimize_c, 2, 1000, args=(zval, a_tilde, b_tilde, cosmo['A_scaling'], cosmo['omega_M_0'], cosmo['omega_lambda_0'])) if np.isclose(c, 0): print("Error solving for concentration with given redshift and " "(probably) too small a mass") c = -1 sig = -1 nu = -1 zf = -1 else: # Calculate formation redshift for this concentration, # redshift at which the scale radius = virial radius: z_-2 zf = formationz(c, zval, Ascaling=cosmo['A_scaling'], omega_M_0=cosmo['omega_M_0'], omega_lambda_0=cosmo['omega_lambda_0']) R_Mass = cp.perturbation.mass_to_radius(Mval, **cosmo) sig, err_sig = cp.perturbation.sigma_r(R_Mass, 0, **cosmo) nu = 1.686/(sig*growthfactor(zval, norm=True, **cosmo)) c_array[i_ind] = c sig_array[i_ind] = sig nu_array[i_ind] = nu zf_array[i_ind] = zf return(c_array, sig_array, nu_array, zf_array)
[ "def c_M_z(self, M, z):\n \"\"\"\n fitting function of http://moriond.in2p3.fr/J08/proceedings/duffy.pdf for the mass and redshift dependence of the concentration parameter\n\n :param M: halo mass in M_sun/h\n :type M: float or numpy array\n :param z: redshift\n :type z: fl...
[ 0.8011312484741211, 0.7321945428848267, 0.7050241827964783, 0.6927163600921631, 0.6824684739112854, 0.681324303150177, 0.6761322617530823, 0.669061541557312, 0.6628347039222717, 0.6624162793159485, 0.6606134176254272, 0.6575406193733215 ]
Run commah code on halo of mass 'Mi' at redshift 'zi' with accretion and profile history at higher redshifts 'z' This is based on Correa et al. (2015a,b,c) Parameters ---------- cosmology : str or dict Can be named cosmology, default WMAP7 (aka DRAGONS), or DRAGONS, WMAP1, WMAP3, WMAP5, WMAP7, WMAP9, Planck13, Planck15 or dictionary similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} zi : float / numpy array, optional Redshift at which halo has mass 'Mi'. If float then all halo masses 'Mi' are assumed to be at this redshift. If array but Mi is float, then this halo mass is used across all starting redshifts. If both Mi and zi are arrays then they have to be the same size for one - to - one correspondence between halo mass and the redshift at which it has that mass. Default is 0. Mi : float / numpy array, optional Halo mass 'Mi' at a redshift 'zi'. If float then all redshifts 'zi' are solved for this halo mass. If array but zi is float, then this redshift is applied to all halo masses. If both Mi and zi are arrays then they have to be the same size for one - to - one correspondence between halo mass and the redshift at which it has that mass. Default is 1e12 Msol. z : float / numpy array, optional Redshift to solve commah code at. Must have zi<z else these steps are skipped. Default is False, meaning commah is solved at z=zi com : bool, optional If true then solve for concentration-mass, default is True. mah : bool, optional If true then solve for accretion rate and halo mass history, default is True. filename : bool / str, optional If str is passed this is used as a filename for output of commah verbose : bool, optional If true then give comments, default is None. retcosmo : bool, optional Return cosmological parameters used as a dict if retcosmo = True, default is None. Returns ------- dataset : structured dataset dataset contains structured columns of size (size(Mi) > size(z)) by size(z) If mah = True and com = False then columns are ('zi',float),('Mi',float),('z',float),('dMdt',float),('Mz',float) where 'zi' is the starting redshift, 'Mi' is halo mass at zi 'z' is output redshift (NB z>zi), 'dMdt' is accretion rate [Msol/yr] and 'Mz' is the halo mass at 'z' for a halo which was 'Mi' massive at starting redshift 'zi' If mah = False and com = True then columns are ('zi',float),('Mi',float),('z',float),('c',float),('sig',float),('nu',float),('zf',float) where 'zi' is the starting redshift, 'Mi' is halo mass at zi 'z' is output redshift (NB z>zi), 'c' is NFW concentration of halo at the redshift 'z', 'sig' is the mass variance 'sigma', 'nu' is the dimensionless fluctuation for halo mass 'Mi' at 'zi', 'zf' is the formation redshift for a halo of mass 'Mi' at redshift 'zi' If mah = True and com = True then columns are: ('zi',float),('Mi',float),('z',float),('dMdt',float),('Mz',float), ('c',float),('sig',float),('nu',float),('zf',float) file : structured dataset with name 'filename' if passed Raises ------ Output -1 If com = False and mah = False as user has to select something. Output -1 If 'zi' and 'Mi' are arrays of unequal size. Impossible to match corresponding masses and redshifts of output. Examples -------- Examples should be written in doctest format, and should illustrate how to use the function. >>> import examples >>> examples.runcommands() # A series of ways to query structured dataset >>> examples.plotcommands() # Examples to plot data
def run(cosmology, zi=0, Mi=1e12, z=False, com=True, mah=True, filename=None, verbose=None, retcosmo=None): """ Run commah code on halo of mass 'Mi' at redshift 'zi' with accretion and profile history at higher redshifts 'z' This is based on Correa et al. (2015a,b,c) Parameters ---------- cosmology : str or dict Can be named cosmology, default WMAP7 (aka DRAGONS), or DRAGONS, WMAP1, WMAP3, WMAP5, WMAP7, WMAP9, Planck13, Planck15 or dictionary similar in format to: {'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0': 0.275, 'omega_b_0': 0.0458,'omega_lambda_0': 0.725,'omega_n_0': 0.0, 'sigma_8': 0.816, 't_0': 13.76, 'tau': 0.088,'z_reion': 10.6} zi : float / numpy array, optional Redshift at which halo has mass 'Mi'. If float then all halo masses 'Mi' are assumed to be at this redshift. If array but Mi is float, then this halo mass is used across all starting redshifts. If both Mi and zi are arrays then they have to be the same size for one - to - one correspondence between halo mass and the redshift at which it has that mass. Default is 0. Mi : float / numpy array, optional Halo mass 'Mi' at a redshift 'zi'. If float then all redshifts 'zi' are solved for this halo mass. If array but zi is float, then this redshift is applied to all halo masses. If both Mi and zi are arrays then they have to be the same size for one - to - one correspondence between halo mass and the redshift at which it has that mass. Default is 1e12 Msol. z : float / numpy array, optional Redshift to solve commah code at. Must have zi<z else these steps are skipped. Default is False, meaning commah is solved at z=zi com : bool, optional If true then solve for concentration-mass, default is True. mah : bool, optional If true then solve for accretion rate and halo mass history, default is True. filename : bool / str, optional If str is passed this is used as a filename for output of commah verbose : bool, optional If true then give comments, default is None. retcosmo : bool, optional Return cosmological parameters used as a dict if retcosmo = True, default is None. Returns ------- dataset : structured dataset dataset contains structured columns of size (size(Mi) > size(z)) by size(z) If mah = True and com = False then columns are ('zi',float),('Mi',float),('z',float),('dMdt',float),('Mz',float) where 'zi' is the starting redshift, 'Mi' is halo mass at zi 'z' is output redshift (NB z>zi), 'dMdt' is accretion rate [Msol/yr] and 'Mz' is the halo mass at 'z' for a halo which was 'Mi' massive at starting redshift 'zi' If mah = False and com = True then columns are ('zi',float),('Mi',float),('z',float),('c',float),('sig',float),('nu',float),('zf',float) where 'zi' is the starting redshift, 'Mi' is halo mass at zi 'z' is output redshift (NB z>zi), 'c' is NFW concentration of halo at the redshift 'z', 'sig' is the mass variance 'sigma', 'nu' is the dimensionless fluctuation for halo mass 'Mi' at 'zi', 'zf' is the formation redshift for a halo of mass 'Mi' at redshift 'zi' If mah = True and com = True then columns are: ('zi',float),('Mi',float),('z',float),('dMdt',float),('Mz',float), ('c',float),('sig',float),('nu',float),('zf',float) file : structured dataset with name 'filename' if passed Raises ------ Output -1 If com = False and mah = False as user has to select something. Output -1 If 'zi' and 'Mi' are arrays of unequal size. Impossible to match corresponding masses and redshifts of output. Examples -------- Examples should be written in doctest format, and should illustrate how to use the function. >>> import examples >>> examples.runcommands() # A series of ways to query structured dataset >>> examples.plotcommands() # Examples to plot data """ # Check user choices... if not com and not mah: print("User has to choose com=True and / or mah=True ") return(-1) # Convert arrays / lists to np.array # and inflate redshift / mass axis # to match each other for later loop results = _checkinput(zi, Mi, z=z, verbose=verbose) # Return if results is -1 if(results == -1): return(-1) # If not, unpack the returned iterable else: zi, Mi, z, lenz, lenm, lenzout = results # At this point we will have lenm objects to iterate over # Get the cosmological parameters for the given cosmology cosmo = getcosmo(cosmology) # Create output file if desired if filename: print("Output to file %r" % (filename)) fout = open(filename, 'wb') # Create the structured dataset try: if mah and com: if verbose: print("Output requested is zi, Mi, z, dMdt, Mz, c, sig, nu, " "zf") if filename: fout.write(_getcosmoheader(cosmo)+'\n') fout.write("# Initial z - Initial Halo - Output z - " " Accretion - Final Halo - concentration - " " Mass - Peak - Formation z "+'\n') fout.write("# - mass - -" " rate - mass - - " " Variance - Height - "+'\n') fout.write("# - (M200) - - " " (dM/dt) - (M200) - - " " (sigma) - (nu) - "+'\n') fout.write("# - [Msol] - - " " [Msol/yr] - [Msol] - - " " - - "+'\n') dataset = np.zeros((lenm, lenzout), dtype=[('zi', float), ('Mi', float), ('z', float), ('dMdt', float), ('Mz', float), ('c', float), ('sig', float), ('nu', float), ('zf', float)]) elif mah: if verbose: print("Output requested is zi, Mi, z, dMdt, Mz") if filename: fout.write(_getcosmoheader(cosmo)+'\n') fout.write("# Initial z - Initial Halo - Output z -" " Accretion - Final Halo "+'\n') fout.write("# - mass - -" " rate - mass "+'\n') fout.write("# - (M200) - -" " (dm/dt) - (M200) "+'\n') fout.write("# - [Msol] - -" " [Msol/yr] - [Msol] "+'\n') dataset = np.zeros((lenm, lenzout), dtype=[('zi', float), ('Mi', float), ('z', float), ('dMdt', float), ('Mz', float)]) else: if verbose: print("Output requested is zi, Mi, z, c, sig, nu, zf") if filename: fout.write(_getcosmoheader(cosmo)+'\n') fout.write("# Initial z - Initial Halo - Output z - " " concentration - " " Mass - Peak - Formation z "+'\n') fout.write("# - mass - -" " -" " Variance - Height - "+'\n') fout.write("# - (M200) - - " " - " " (sigma) - (nu) - "+'\n') fout.write("# - [Msol] - - " " - " " - - "+'\n') dataset = np.zeros((lenm, lenzout), dtype=[('zi', float), ('Mi', float), ('z', float), ('c', float), ('sig', float), ('nu', float), ('zf', float)]) # Now loop over the combination of initial redshift and halo mamss for i_ind, (zval, Mval) in enumerate(_izip(zi, Mi)): if verbose: print("Output Halo of Mass Mi=%s at zi=%s" % (Mval, zval)) # For a given halo mass Mi at redshift zi need to know # output redshifts 'z' # Check that all requested redshifts are greater than # input redshift, except if z is False, in which case # only solve z at zi, i.e. remove a loop if z is False: ztemp = np.array(zval, ndmin=1, dtype=float) else: ztemp = np.array(z[z >= zval], dtype=float) # Loop over the output redshifts if ztemp.size: # Return accretion rates and halo mass progenitors at # redshifts 'z' for object of mass Mi at zi dMdt, Mz = MAH(ztemp, zval, Mval, **cosmo) if mah and com: # More expensive to return concentrations c, sig, nu, zf = COM(ztemp, Mz, **cosmo) # Save all arrays for j_ind, j_val in enumerate(ztemp): dataset[i_ind, j_ind] =\ (zval, Mval, ztemp[j_ind], dMdt[j_ind], Mz[j_ind], c[j_ind], sig[j_ind], nu[j_ind], zf[j_ind]) if filename: fout.write( "{}, {}, {}, {}, {}, {}, {}, {}, {} \n".format( zval, Mval, ztemp[j_ind], dMdt[j_ind], Mz[j_ind], c[j_ind], sig[j_ind], nu[j_ind], zf[j_ind])) elif mah: # Save only MAH arrays for j_ind, j_val in enumerate(ztemp): dataset[i_ind, j_ind] =\ (zval, Mval, ztemp[j_ind], dMdt[j_ind], Mz[j_ind]) if filename: fout.write("{}, {}, {}, {}, {} \n".format( zval, Mval, ztemp[j_ind], dMdt[j_ind], Mz[j_ind])) else: # Output only COM arrays c, sig, nu, zf = COM(ztemp, Mz, **cosmo) # For any halo mass Mi at redshift zi # solve for c, sig, nu and zf for j_ind, j_val in enumerate(ztemp): dataset[i_ind, j_ind] =\ (zval, Mval, ztemp[j_ind], c[j_ind], sig[j_ind], nu[j_ind], zf[j_ind]) if filename: fout.write("{}, {}, {}, {}, {}, {}, {} \n".format( zval, Mval, ztemp[j_ind], c[j_ind], sig[j_ind], nu[j_ind], zf[j_ind])) # Make sure to close the file if it was opened finally: fout.close() if filename else None if retcosmo: return(dataset, cosmo) else: return(dataset)
[ "def runcommand(cosmology='WMAP5'):\n \"\"\" Example interface commands \"\"\"\n\n # Return the WMAP5 cosmology concentration predicted for\n # z=0 range of masses\n Mi = [1e8, 1e9, 1e10]\n zi = 0\n print(\"Concentrations for haloes of mass %s at z=%s\" % (Mi, zi))\n output = commah.run(cosmolo...
[ 0.7582313418388367, 0.7539766430854797, 0.7074388265609741, 0.7062006592750549, 0.6907287240028381, 0.6845294833183289, 0.6767992377281189, 0.6750814318656921, 0.6739107966423035, 0.6689210534095764, 0.665745198726654, 0.6627588272094727 ]
Load a configuration and keep it alive for the given context :param config_path: path to a configuration file
def load(config_path: str): """ Load a configuration and keep it alive for the given context :param config_path: path to a configuration file """ # we bind the config to _ to keep it alive if os.path.splitext(config_path)[1] in ('.yaml', '.yml'): _ = load_yaml_configuration(config_path, translator=PipelineTranslator()) elif os.path.splitext(config_path)[1] == '.py': _ = load_python_configuration(config_path) else: raise ValueError('Unknown configuration extension: %r' % os.path.splitext(config_path)[1]) yield
[ "def load(self, config_file=None, path=None):\n \"\"\"Loads the configuration from a specific file\n\n :param config_file: the name of the config file\n :param path: the path to the config file\n \"\"\"\n if config_file is None:\n if path is None:\n path,...
[ 0.7743517160415649, 0.7668439149856567, 0.7407531142234802, 0.7327948808670044, 0.7264970541000366, 0.7258405089378357, 0.7225270867347717, 0.7186398506164551, 0.7185409665107727, 0.715469479560852, 0.7152398228645325, 0.7120245695114136 ]
Replaces instances of repeat n: by for __VAR_i in range(n): where __VAR_i is a string that does not appear elsewhere in the code sample.
def transform_source(text): '''Replaces instances of repeat n: by for __VAR_i in range(n): where __VAR_i is a string that does not appear elsewhere in the code sample. ''' loop_keyword = 'repeat' nb = text.count(loop_keyword) if nb == 0: return text var_names = get_unique_variable_names(text, nb) toks = tokenize.generate_tokens(StringIO(text).readline) result = [] replacing_keyword = False for toktype, tokvalue, _, _, _ in toks: if toktype == tokenize.NAME and tokvalue == loop_keyword: result.extend([ (tokenize.NAME, 'for'), (tokenize.NAME, var_names.pop()), (tokenize.NAME, 'in'), (tokenize.NAME, 'range'), (tokenize.OP, '(') ]) replacing_keyword = True elif replacing_keyword and tokvalue == ':': result.extend([ (tokenize.OP, ')'), (tokenize.OP, ':') ]) replacing_keyword = False else: result.append((toktype, tokvalue)) return tokenize.untokenize(result)
[ "def varReplace(basedir, raw, vars, lookup_fatal=True, depth=0, expand_lists=False):\n ''' Perform variable replacement of $variables in string raw using vars dictionary '''\n # this code originally from yum\n\n if (depth > 20):\n raise errors.AnsibleError(\"template recursion depth exceeded\")\n\n ...
[ 0.7174105644226074, 0.706699550151825, 0.6893872618675232, 0.6843791604042053, 0.6755014657974243, 0.6703273057937622, 0.6679925918579102, 0.665018618106842, 0.6648368239402771, 0.6638390421867371, 0.6626368165016174, 0.6604301333427429 ]
returns a list of possible variables names that are not found in the original text.
def get_unique_variable_names(text, nb): '''returns a list of possible variables names that are not found in the original text.''' base_name = '__VAR_' var_names = [] i = 0 j = 0 while j < nb: tentative_name = base_name + str(i) if text.count(tentative_name) == 0 and tentative_name not in ALL_NAMES: var_names.append(tentative_name) ALL_NAMES.append(tentative_name) j += 1 i += 1 return var_names
[ "def get_variables(text):\n \"\"\"Extracts variables that can be used in templating engines.\n\n Each variable is defined on a single line in the following way:\n\n ~ var: text\n\n The ~ must be at the start of a newline, followed by at least one\n space. var can be any sequence of characters tha...
[ 0.7655473351478577, 0.7517821192741394, 0.7387765645980835, 0.737966775894165, 0.7293704152107239, 0.7250773906707764, 0.7249011397361755, 0.722808301448822, 0.7225084900856018, 0.7214174270629883, 0.719914436340332, 0.7185519933700562 ]
Get a release by tag
def tag(self, tag): """Get a release by tag """ url = '%s/tags/%s' % (self, tag) response = self.http.get(url, auth=self.auth) response.raise_for_status() return response.json()
[ "public static function get_release_by_tag(\n\t\t$project,\n\t\t$tag,\n\t\t$args = []\n\t) {\n\t\t$request_url = sprintf(\n\t\t\tself::API_ROOT . 'repos/%s/releases/tags/%s',\n\t\t\t$project,\n\t\t\t$tag\n\t\t);\n\n\t\t$args['per_page'] = 100;\n\n\t\tlist( $body, $headers ) = self::request( $request_url, $args );\n...
[ 0.8034539818763733, 0.7926703095436096, 0.7689692378044128, 0.7525080442428589, 0.749724268913269, 0.7357184886932373, 0.7194510698318481, 0.7184587121009827, 0.716830849647522, 0.7133541107177734, 0.7089478373527527, 0.70732581615448 ]
Assets for a given release
def release_assets(self, release): """Assets for a given release """ release = self.as_id(release) return self.get_list(url='%s/%s/assets' % (self, release))
[ "def asset(self, id):\n \"\"\"Returns a single Asset.\n\n :param int id: (required), id of the asset\n :returns: :class:`Asset <github3.repos.release.Asset>`\n \"\"\"\n data = None\n if int(id) > 0:\n url = self._build_url('releases', 'assets', str(id),\n ...
[ 0.7340524792671204, 0.7329351902008057, 0.7163358926773071, 0.6988852024078369, 0.6982651948928833, 0.6958836317062378, 0.6937362551689148, 0.6861414313316345, 0.6811293959617615, 0.6800277829170227, 0.6789299249649048, 0.6773079633712769 ]
Upload a file to a release :param filename: filename to upload :param content_type: optional content type :return: json object from github
def upload(self, release, filename, content_type=None): """Upload a file to a release :param filename: filename to upload :param content_type: optional content type :return: json object from github """ release = self.as_id(release) name = os.path.basename(filename) if not content_type: content_type, _ = mimetypes.guess_type(name) if not content_type: raise ValueError('content_type not known') inputs = {'name': name} url = '%s%s/%s/assets' % (self.uploads_url, urlsplit(self.api_url).path, release) info = os.stat(filename) size = info[stat.ST_SIZE] response = self.http.post( url, data=stream_upload(filename), auth=self.auth, params=inputs, headers={'content-type': content_type, 'content-length': str(size)}) response.raise_for_status() return response.json()
[ "def upload_asset(self, content_type, name, asset):\n \"\"\"Upload an asset to this release.\n\n All parameters are required.\n\n :param str content_type: The content type of the asset. Wikipedia has\n a list of common media types\n :param str name: The name of the file\n ...
[ 0.802365243434906, 0.7317085266113281, 0.7304291129112244, 0.729613184928894, 0.7226841449737549, 0.7197074890136719, 0.7160930037498474, 0.7031177282333374, 0.7029310464859009, 0.6901597380638123, 0.6828121542930603, 0.6824163794517517 ]
Validate ``tag_name`` with the latest tag from github If ``tag_name`` is a valid candidate, return the latest tag from github
def validate_tag(self, tag_name, prefix=None): """Validate ``tag_name`` with the latest tag from github If ``tag_name`` is a valid candidate, return the latest tag from github """ new_version = semantic_version(tag_name) current = self.latest() if current: tag_name = current['tag_name'] if prefix: tag_name = tag_name[len(prefix):] tag_name = semantic_version(tag_name) if tag_name >= new_version: what = 'equal to' if tag_name == new_version else 'older than' raise GithubException( 'Your local version "%s" is %s ' 'the current github version "%s".\n' 'Bump the local version to ' 'continue.' % ( str(new_version), what, str(tag_name) ) ) return current
[ "def get_version_from_tag(tag_name: str) -> Optional[str]:\n \"\"\"Get git hash from tag\n\n :param tag_name: Name of the git tag (i.e. 'v1.0.0')\n :return: sha1 hash of the commit\n \"\"\"\n\n debug('get_version_from_tag({})'.format(tag_name))\n check_repo()\n for i in repo.tags:\n if i...
[ 0.724653959274292, 0.7182732820510864, 0.7106755375862122, 0.7020395398139954, 0.6872637867927551, 0.680760383605957, 0.6798170208930969, 0.6793562769889832, 0.6791114211082458, 0.6761107444763184, 0.6759423613548279, 0.6710719466209412 ]
Return the full reddit URL associated with the usernote. Arguments: subreddit: the subreddit name for the note (PRAW Subreddit object)
def full_url(self): """Return the full reddit URL associated with the usernote. Arguments: subreddit: the subreddit name for the note (PRAW Subreddit object) """ if self.link == '': return None else: return Note._expand_url(self.link, self.subreddit)
[ "def _expand_url(short_link, subreddit=None):\n \"\"\"Convert a usernote's URL short-hand into a full reddit URL.\n\n Arguments:\n subreddit: the subreddit the URL is for (PRAW Subreddit object or str)\n short_link: the compressed link from a usernote (str)\n\n Returns a S...
[ 0.7570649981498718, 0.730120837688446, 0.690046489238739, 0.6770223379135132, 0.6761775612831116, 0.6745516061782837, 0.669142484664917, 0.6685365438461304, 0.6644787788391113, 0.6626833081245422, 0.6609413623809814, 0.6605386734008789 ]
Convert a reddit URL into the short-hand used by usernotes. Arguments: link: a link to a comment, submission, or message (str) Returns a String of the shorthand URL
def _compress_url(link): """Convert a reddit URL into the short-hand used by usernotes. Arguments: link: a link to a comment, submission, or message (str) Returns a String of the shorthand URL """ comment_re = re.compile(r'/comments/([A-Za-z\d]{2,})(?:/[^\s]+/([A-Za-z\d]+))?') message_re = re.compile(r'/message/messages/([A-Za-z\d]+)') matches = re.findall(comment_re, link) if len(matches) == 0: matches = re.findall(message_re, link) if len(matches) == 0: return None else: return 'm,' + matches[0] else: if matches[0][1] == '': return 'l,' + matches[0][0] else: return 'l,' + matches[0][0] + ',' + matches[0][1]
[ "def _expand_url(short_link, subreddit=None):\n \"\"\"Convert a usernote's URL short-hand into a full reddit URL.\n\n Arguments:\n subreddit: the subreddit the URL is for (PRAW Subreddit object or str)\n short_link: the compressed link from a usernote (str)\n\n Returns a S...
[ 0.7899641990661621, 0.7254191040992737, 0.7252077460289001, 0.710456371307373, 0.6831409335136414, 0.680858314037323, 0.6777580976486206, 0.6740667819976807, 0.6739614605903625, 0.6738519072532654, 0.672898530960083, 0.6724253296852112 ]
Convert a usernote's URL short-hand into a full reddit URL. Arguments: subreddit: the subreddit the URL is for (PRAW Subreddit object or str) short_link: the compressed link from a usernote (str) Returns a String of the full URL.
def _expand_url(short_link, subreddit=None): """Convert a usernote's URL short-hand into a full reddit URL. Arguments: subreddit: the subreddit the URL is for (PRAW Subreddit object or str) short_link: the compressed link from a usernote (str) Returns a String of the full URL. """ # Some URL structures for notes message_scheme = 'https://reddit.com/message/messages/{}' comment_scheme = 'https://reddit.com/r/{}/comments/{}/-/{}' post_scheme = 'https://reddit.com/r/{}/comments/{}/' if short_link == '': return None else: parts = short_link.split(',') if parts[0] == 'm': return message_scheme.format(parts[1]) if parts[0] == 'l' and subreddit: if len(parts) > 2: return comment_scheme.format(subreddit, parts[1], parts[2]) else: return post_scheme.format(subreddit, parts[1]) elif not subreddit: raise ValueError('Subreddit name must be provided') else: return None
[ "def _compress_url(link):\n \"\"\"Convert a reddit URL into the short-hand used by usernotes.\n\n Arguments:\n link: a link to a comment, submission, or message (str)\n\n Returns a String of the shorthand URL\n \"\"\"\n comment_re = re.compile(r'/comments/([A-Za-z\\d]{2...
[ 0.7953359484672546, 0.7889899015426636, 0.7214460968971252, 0.7140364646911621, 0.6838879585266113, 0.6834974884986877, 0.6769272685050964, 0.6733359098434448, 0.670393168926239, 0.6687145233154297, 0.6640609502792358, 0.6619897484779358 ]
Get the JSON stored on the usernotes wiki page. Returns a dict representation of the usernotes (with the notes BLOB decoded). Raises: RuntimeError if the usernotes version is incompatible with this version of puni.
def get_json(self): """Get the JSON stored on the usernotes wiki page. Returns a dict representation of the usernotes (with the notes BLOB decoded). Raises: RuntimeError if the usernotes version is incompatible with this version of puni. """ try: usernotes = self.subreddit.wiki[self.page_name].content_md notes = json.loads(usernotes) except NotFound: self._init_notes() else: if notes['ver'] != self.schema: raise RuntimeError( 'Usernotes schema is v{0}, puni requires v{1}'. format(notes['ver'], self.schema) ) self.cached_json = self._expand_json(notes) return self.cached_json
[ "def _expand_json(self, j):\n \"\"\"Decompress the BLOB portion of the usernotes.\n\n Arguments:\n j: the JSON returned from the wiki page (dict)\n\n Returns a Dict with the 'blob' key removed and a 'users' key added\n \"\"\"\n decompressed_json = copy.copy(j)\n ...
[ 0.7596529722213745, 0.7476683855056763, 0.7053613066673279, 0.7012403607368469, 0.7008568048477173, 0.6941919326782227, 0.6872028708457947, 0.6803351640701294, 0.6761101484298706, 0.6668883562088013, 0.6591576933860779, 0.6588183641433716 ]
Set up the UserNotes page with the initial JSON schema.
def _init_notes(self): """Set up the UserNotes page with the initial JSON schema.""" self.cached_json = { 'ver': self.schema, 'users': {}, 'constants': { 'users': [x.name for x in self.subreddit.moderator()], 'warnings': Note.warnings } } self.set_json('Initializing JSON via puni', True)
[ "public function up()\n {\n Schema::table('user_settings', function (Blueprint $table) {\n $table->longText('notes')->nullable()->default(null)->comment('User notes')->change();\n });\n }", "def set_json(self, reason='', new_page=False):\n \"\"\"Send the JSON from the cache t...
[ 0.7966107130050659, 0.7526082992553711, 0.7520560026168823, 0.7177902460098267, 0.7156883478164673, 0.7048381567001343, 0.7048107981681824, 0.700613796710968, 0.700387179851532, 0.689842939376831, 0.6890769600868225, 0.6837928295135498 ]
Send the JSON from the cache to the usernotes wiki page. Arguments: reason: the change reason that will be posted to the wiki changelog (str) Raises: OverflowError if the new JSON data is greater than max_page_size
def set_json(self, reason='', new_page=False): """Send the JSON from the cache to the usernotes wiki page. Arguments: reason: the change reason that will be posted to the wiki changelog (str) Raises: OverflowError if the new JSON data is greater than max_page_size """ compressed_json = json.dumps(self._compress_json(self.cached_json)) if len(compressed_json) > self.max_page_size: raise OverflowError( 'Usernotes page is too large (>{0} characters)'. format(self.max_page_size) ) if new_page: self.subreddit.wiki.create( self.page_name, compressed_json, reason ) # Set the page as hidden and available to moderators only self.subreddit.wiki[self.page_name].mod.update(False, permlevel=2) else: self.subreddit.wiki[self.page_name].edit( compressed_json, reason )
[ "def get_json(self):\n \"\"\"Get the JSON stored on the usernotes wiki page.\n\n Returns a dict representation of the usernotes (with the notes BLOB\n decoded).\n\n Raises:\n RuntimeError if the usernotes version is incompatible with this\n version of puni.\n ...
[ 0.7193440198898315, 0.6912767291069031, 0.6646159291267395, 0.6640122532844543, 0.6605554223060608, 0.6513100862503052, 0.6420649290084839, 0.6415596604347229, 0.6386433243751526, 0.6373923420906067, 0.6370277404785156, 0.6363284587860107 ]
Return a list of Note objects for the given user. Return an empty list if no notes are found. Arguments: user: the user to search for in the usernotes (str)
def get_notes(self, user): """Return a list of Note objects for the given user. Return an empty list if no notes are found. Arguments: user: the user to search for in the usernotes (str) """ # Try to search for all notes on a user, return an empty list if none # are found. try: users_notes = [] for note in self.cached_json['users'][user]['ns']: users_notes.append(Note( user=user, note=note['n'], subreddit=self.subreddit, mod=self._mod_from_index(note['m']), link=note['l'], warning=self._warning_from_index(note['w']), note_time=note['t'] )) return users_notes except KeyError: # User not found return []
[ "def get_notes(self):\n \"\"\"Return a list of all of the project's notes.\n\n :return: A list of notes.\n :rtype: list of :class:`pytodoist.todoist.Note`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user...
[ 0.7208589911460876, 0.7078884840011597, 0.7056156992912292, 0.7021738290786743, 0.6830140948295593, 0.6799189448356628, 0.6790181994438171, 0.6784870028495789, 0.6749463081359863, 0.6740153431892395, 0.6733935475349426, 0.6706024408340454 ]
Decompress the BLOB portion of the usernotes. Arguments: j: the JSON returned from the wiki page (dict) Returns a Dict with the 'blob' key removed and a 'users' key added
def _expand_json(self, j): """Decompress the BLOB portion of the usernotes. Arguments: j: the JSON returned from the wiki page (dict) Returns a Dict with the 'blob' key removed and a 'users' key added """ decompressed_json = copy.copy(j) decompressed_json.pop('blob', None) # Remove BLOB portion of JSON # Decode and decompress JSON compressed_data = base64.b64decode(j['blob']) original_json = zlib.decompress(compressed_data).decode('utf-8') decompressed_json['users'] = json.loads(original_json) # Insert users return decompressed_json
[ "def _compress_json(self, j):\n \"\"\"Compress the BLOB data portion of the usernotes.\n\n Arguments:\n j: the JSON in Schema v5 format (dict)\n\n Returns a dict with the 'users' key removed and 'blob' key added\n \"\"\"\n compressed_json = copy.copy(j)\n compres...
[ 0.8413234949111938, 0.6811477541923523, 0.676547646522522, 0.638260006904602, 0.6341983079910278, 0.6279118061065674, 0.6271971464157104, 0.6196523904800415, 0.6192101240158081, 0.6188784837722778, 0.6174898743629456, 0.6166394352912903 ]
Compress the BLOB data portion of the usernotes. Arguments: j: the JSON in Schema v5 format (dict) Returns a dict with the 'users' key removed and 'blob' key added
def _compress_json(self, j): """Compress the BLOB data portion of the usernotes. Arguments: j: the JSON in Schema v5 format (dict) Returns a dict with the 'users' key removed and 'blob' key added """ compressed_json = copy.copy(j) compressed_json.pop('users', None) compressed_data = zlib.compress( json.dumps(j['users']).encode('utf-8'), self.zlib_compression_strength ) b64_data = base64.b64encode(compressed_data).decode('utf-8') compressed_json['blob'] = b64_data return compressed_json
[ "def _expand_json(self, j):\n \"\"\"Decompress the BLOB portion of the usernotes.\n\n Arguments:\n j: the JSON returned from the wiki page (dict)\n\n Returns a Dict with the 'blob' key removed and a 'users' key added\n \"\"\"\n decompressed_json = copy.copy(j)\n ...
[ 0.8370488286018372, 0.6714560389518738, 0.6385548710823059, 0.6376365423202515, 0.6277602314949036, 0.6251710653305054, 0.6193103194236755, 0.6173309683799744, 0.6137800812721252, 0.6126267313957214, 0.6081791520118713, 0.6060118675231934 ]
Add a note to the usernotes wiki page. Arguments: note: the note to be added (Note) Returns the update message for the usernotes wiki Raises: ValueError when the warning type of the note can not be found in the stored list of warnings.
def add_note(self, note): """Add a note to the usernotes wiki page. Arguments: note: the note to be added (Note) Returns the update message for the usernotes wiki Raises: ValueError when the warning type of the note can not be found in the stored list of warnings. """ notes = self.cached_json if not note.moderator: note.moderator = self.r.user.me().name # Get index of moderator in mod list from usernotes # Add moderator to list if not already there try: mod_index = notes['constants']['users'].index(note.moderator) except ValueError: notes['constants']['users'].append(note.moderator) mod_index = notes['constants']['users'].index(note.moderator) # Get index of warning type from warnings list # Add warning type to list if not already there try: warn_index = notes['constants']['warnings'].index(note.warning) except ValueError: if note.warning in Note.warnings: notes['constants']['warnings'].append(note.warning) warn_index = notes['constants']['warnings'].index(note.warning) else: raise ValueError('Warning type not valid: ' + note.warning) new_note = { 'n': note.note, 't': note.time, 'm': mod_index, 'l': note.link, 'w': warn_index } try: notes['users'][note.username]['ns'].insert(0, new_note) except KeyError: notes['users'][note.username] = {'ns': [new_note]} return '"create new note on user {}" via puni'.format(note.username)
[ "def add_note(\n self,\n note):\n \"\"\"*Add a note to this taskpaper object*\n\n **Key Arguments:**\n - ``note`` -- the note (string)\n\n **Return:**\n - None\n\n **Usage:**\n\n To add a note to a document, project or task object:\n...
[ 0.7897244691848755, 0.7732542753219604, 0.7531960606575012, 0.7384588122367859, 0.7375184893608093, 0.7352802753448486, 0.7301070690155029, 0.7237897515296936, 0.7206209897994995, 0.7201989889144897, 0.7145036458969116, 0.7100257277488708 ]
Remove a single usernote from the usernotes. Arguments: username: the user that for whom you're removing a note (str) index: the index of the note which is to be removed (int) Returns the update message for the usernotes wiki
def remove_note(self, username, index): """Remove a single usernote from the usernotes. Arguments: username: the user that for whom you're removing a note (str) index: the index of the note which is to be removed (int) Returns the update message for the usernotes wiki """ self.cached_json['users'][username]['ns'].pop(index) # Go ahead and remove the user's entry if they have no more notes left if len(self.cached_json['users'][username]['ns']) == 0: del self.cached_json['users'][username] return '"delete note #{} on user {}" via puni'.format(index, username)
[ "def add_note(self, note):\n \"\"\"Add a note to the usernotes wiki page.\n\n Arguments:\n note: the note to be added (Note)\n\n Returns the update message for the usernotes wiki\n\n Raises:\n ValueError when the warning type of the note can not be found in the\n ...
[ 0.6919499635696411, 0.6796944737434387, 0.6752998232841492, 0.6715428233146667, 0.6680077314376831, 0.666473388671875, 0.6651005148887634, 0.6631077527999878, 0.6554504632949829, 0.6528965830802917, 0.6489867568016052, 0.647257924079895 ]
Function load Get the list of all objects @return RETURN: A ForemanItem list
def load(self): """ Function load Get the list of all objects @return RETURN: A ForemanItem list """ cl_tmp = self.api.list(self.objName, limit=self.searchLimit).values() cl = [] for i in cl_tmp: cl.extend(i) return {x[self.index]: ItemPuppetClass(self.api, x['id'], self.objName, self.payloadObj, x) for x in cl}
[ "def load(self):\n \"\"\" Function load\n Get the list of all objects\n\n @return RETURN: A ForemanItem list\n \"\"\"\n return {x[self.index]: self.itemType(self.api, x['id'],\n self.objName, self.payloadObj,\n ...
[ 0.9007964730262756, 0.8018741607666016, 0.7024894952774048, 0.6753305196762085, 0.6598423719406128, 0.6597557663917542, 0.655421257019043, 0.653819739818573, 0.6532294154167175, 0.6501277089118958, 0.648154616355896, 0.6473885774612427 ]
Return True if the item relates to the given app_id (and app_ver, if passed).
def is_related_to(item, app_id, app_ver=None): """Return True if the item relates to the given app_id (and app_ver, if passed).""" versionRange = item.get('versionRange') if not versionRange: return True for vR in versionRange: if not vR.get('targetApplication'): return True if get_related_targetApplication(vR, app_id, app_ver) is not None: return True return False
[ "def get_app_relations(app_id, num=20, kind='1'):\n '''\n The the related infors.\n '''\n info_tag = MInfor2Catalog.get_first_category(app_id)\n if info_tag:\n return TabPost2Tag.select(\n TabPost2Tag,\n TabPost.title.alias('post_title'),\n...
[ 0.7099787592887878, 0.6942530870437622, 0.6856756806373596, 0.6784685850143433, 0.6681079268455505, 0.6609764695167542, 0.6578934788703918, 0.6472867131233215, 0.6428728103637695, 0.6427755951881409, 0.6412286162376404, 0.637650191783905 ]
Return the first matching target application in this version range. Returns None if there are no target applications or no matching ones.
def get_related_targetApplication(vR, app_id, app_ver): """Return the first matching target application in this version range. Returns None if there are no target applications or no matching ones.""" targetApplication = vR.get('targetApplication') if not targetApplication: return None for tA in targetApplication: guid = tA.get('guid') if not guid or guid == app_id: if not app_ver: return tA # We purposefully use maxVersion only, so that the blocklist contains items # whose minimum version is ahead of the version we get passed. This means # the blocklist we serve is "future-proof" for app upgrades. if between(version_int(app_ver), '0', tA.get('maxVersion', '*')): return tA return None
[ "def target_app(self):\n \"\"\"Defer target app retrieval until requested\"\"\"\n if self.__target_app is None:\n self.__target_app = self._swimlane.apps.get(id=self.__target_app_id)\n\n return self.__target_app", "def get_app(self, reference_app=None):\n \"\"\"Helper method...
[ 0.7042108774185181, 0.6782410740852356, 0.6733211874961853, 0.6708325743675232, 0.6686870455741882, 0.6660854816436768, 0.6612887978553772, 0.6568704843521118, 0.6525574326515198, 0.6496841907501221, 0.6484965085983276, 0.6481257677078247 ]
Generate the addons blocklists. <emItem blockID="i372" id="5nc3QHFgcb@r06Ws9gvNNVRfH.com"> <versionRange minVersion="0" maxVersion="*" severity="3"> <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"> <versionRange minVersion="39.0a1" maxVersion="*"/> </targetApplication> </versionRange> <prefs> <pref>browser.startup.homepage</pref> <pref>browser.search.defaultenginename</pref> </prefs> </emItem>
def write_addons_items(xml_tree, records, app_id, api_ver=3, app_ver=None): """Generate the addons blocklists. <emItem blockID="i372" id="5nc3QHFgcb@r06Ws9gvNNVRfH.com"> <versionRange minVersion="0" maxVersion="*" severity="3"> <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"> <versionRange minVersion="39.0a1" maxVersion="*"/> </targetApplication> </versionRange> <prefs> <pref>browser.startup.homepage</pref> <pref>browser.search.defaultenginename</pref> </prefs> </emItem> """ if not records: return emItems = etree.SubElement(xml_tree, 'emItems') groupby = {} for item in records: if is_related_to(item, app_id, app_ver): if item['guid'] in groupby: emItem = groupby[item['guid']] # When creating new records from the Kinto Admin we don't have proper blockID. if 'blockID' in item: # Remove the first caracter which is the letter i to # compare the numeric value i45 < i356. current_blockID = int(item['blockID'][1:]) previous_blockID = int(emItem.attrib['blockID'][1:]) # Group by and keep the biggest blockID in the XML file. if current_blockID > previous_blockID: emItem.attrib['blockID'] = item['blockID'] else: # If the latest entry does not have any blockID attribute, its # ID should be used. (the list of records is sorted by ascending # last_modified). # See https://bugzilla.mozilla.org/show_bug.cgi?id=1473194 emItem.attrib['blockID'] = item['id'] else: emItem = etree.SubElement(emItems, 'emItem', blockID=item.get('blockID', item['id'])) groupby[item['guid']] = emItem prefs = etree.SubElement(emItem, 'prefs') for p in item['prefs']: pref = etree.SubElement(prefs, 'pref') pref.text = p # Set the add-on ID emItem.set('id', item['guid']) for field in ['name', 'os']: if field in item: emItem.set(field, item[field]) build_version_range(emItem, item, app_id)
[ "def write_plugin_items(xml_tree, records, app_id, api_ver=3, app_ver=None):\n \"\"\"Generate the plugin blocklists.\n\n <pluginItem blockID=\"p422\">\n <match name=\"filename\" exp=\"JavaAppletPlugin\\\\.plugin\"/>\n <versionRange minVersion=\"Java 7 Update 16\"\n maxVersio...
[ 0.6949023604393005, 0.6635684370994568, 0.6583225131034851, 0.6570259928703308, 0.6558802723884583, 0.6533246636390686, 0.6520910263061523, 0.6436138153076172, 0.6408869028091431, 0.6392215490341187, 0.6388567686080933, 0.6378030180931091 ]
Generate the plugin blocklists. <pluginItem blockID="p422"> <match name="filename" exp="JavaAppletPlugin\\.plugin"/> <versionRange minVersion="Java 7 Update 16" maxVersion="Java 7 Update 24" severity="0" vulnerabilitystatus="1"> <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"> <versionRange minVersion="17.0" maxVersion="*"/> </targetApplication> </versionRange> </pluginItem>
def write_plugin_items(xml_tree, records, app_id, api_ver=3, app_ver=None): """Generate the plugin blocklists. <pluginItem blockID="p422"> <match name="filename" exp="JavaAppletPlugin\\.plugin"/> <versionRange minVersion="Java 7 Update 16" maxVersion="Java 7 Update 24" severity="0" vulnerabilitystatus="1"> <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"> <versionRange minVersion="17.0" maxVersion="*"/> </targetApplication> </versionRange> </pluginItem> """ if not records: return pluginItems = etree.SubElement(xml_tree, 'pluginItems') for item in records: for versionRange in item.get('versionRange', []): if not versionRange.get('targetApplication'): add_plugin_item(pluginItems, item, versionRange, app_id=app_id, api_ver=api_ver, app_ver=app_ver) else: targetApplication = get_related_targetApplication(versionRange, app_id, app_ver) if targetApplication is not None: add_plugin_item(pluginItems, item, versionRange, targetApplication, app_id=app_id, api_ver=api_ver, app_ver=app_ver)
[ "def write_addons_items(xml_tree, records, app_id, api_ver=3, app_ver=None):\n \"\"\"Generate the addons blocklists.\n\n <emItem blockID=\"i372\" id=\"5nc3QHFgcb@r06Ws9gvNNVRfH.com\">\n <versionRange minVersion=\"0\" maxVersion=\"*\" severity=\"3\">\n <targetApplication id=\"{ec8030f7-c20a-464f-9b...
[ 0.6678083539009094, 0.6628898978233337, 0.660322904586792, 0.659954845905304, 0.6570162773132324, 0.6534080505371094, 0.6514649391174316, 0.6495108008384705, 0.6472249627113342, 0.6460555791854858, 0.6452942490577698, 0.6452105641365051 ]
Generate the gfxBlacklistEntry. <gfxBlacklistEntry blockID="g35"> <os>WINNT 6.1</os> <vendor>0x10de</vendor> <devices> <device>0x0a6c</device> </devices> <feature>DIRECT2D</feature> <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus> <driverVersion>8.17.12.5896</driverVersion> <driverVersionComparator>LESS_THAN_OR_EQUAL</driverVersionComparator> <versionRange minVersion="3.2" maxVersion="3.4" /> </gfxBlacklistEntry>
def write_gfx_items(xml_tree, records, app_id, api_ver=3): """Generate the gfxBlacklistEntry. <gfxBlacklistEntry blockID="g35"> <os>WINNT 6.1</os> <vendor>0x10de</vendor> <devices> <device>0x0a6c</device> </devices> <feature>DIRECT2D</feature> <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus> <driverVersion>8.17.12.5896</driverVersion> <driverVersionComparator>LESS_THAN_OR_EQUAL</driverVersionComparator> <versionRange minVersion="3.2" maxVersion="3.4" /> </gfxBlacklistEntry> """ if not records: return gfxItems = etree.SubElement(xml_tree, 'gfxItems') for item in records: is_record_related = ('guid' not in item or item['guid'] == app_id) if is_record_related: entry = etree.SubElement(gfxItems, 'gfxBlacklistEntry', blockID=item.get('blockID', item['id'])) fields = ['os', 'vendor', 'feature', 'featureStatus', 'driverVersion', 'driverVersionComparator'] for field in fields: if field in item: node = etree.SubElement(entry, field) node.text = item[field] # Devices if item['devices']: devices = etree.SubElement(entry, 'devices') for d in item['devices']: device = etree.SubElement(devices, 'device') device.text = d if 'versionRange' in item: version = item['versionRange'] versionRange = etree.SubElement(entry, 'versionRange') for field in ['minVersion', 'maxVersion']: value = version.get(field) if value: versionRange.set(field, str(value))
[ "public Blacklist generateBlacklist(Model model)\n\t{\n\t\tChemicalNameNormalizer normalizer = new ChemicalNameNormalizer(model);\n\t\tSIFSearcher searcher = new SIFSearcher(new Fetcher(normalizer), SIFEnum.USED_TO_PRODUCE);\n\n\t\tSet<SIFInteraction> sifs = searcher.searchSIF(model);\n\n\t\t// read interactions in...
[ 0.6555547118186951, 0.6552377343177795, 0.6530686616897583, 0.6528235077857971, 0.6493707895278931, 0.6475033164024353, 0.644248366355896, 0.6430034041404724, 0.638952374458313, 0.6351384520530701, 0.6331576108932495, 0.6322445869445801 ]
Generate the certificate blocklists. <certItem issuerName="MIGQMQswCQYD...IENB"> <serialNumber>UoRGnb96CUDTxIqVry6LBg==</serialNumber> </certItem> or <certItem subject='MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQtZW50aXR5' pubKeyHash='VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8='> </certItem>
def write_cert_items(xml_tree, records, api_ver=3, app_id=None, app_ver=None): """Generate the certificate blocklists. <certItem issuerName="MIGQMQswCQYD...IENB"> <serialNumber>UoRGnb96CUDTxIqVry6LBg==</serialNumber> </certItem> or <certItem subject='MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQtZW50aXR5' pubKeyHash='VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8='> </certItem> """ if not records or not should_include_certs(app_id, app_ver): return certItems = etree.SubElement(xml_tree, 'certItems') for item in records: if item.get('subject') and item.get('pubKeyHash'): cert = etree.SubElement(certItems, 'certItem', subject=item['subject'], pubKeyHash=item['pubKeyHash']) else: cert = etree.SubElement(certItems, 'certItem', issuerName=item['issuerName']) serialNumber = etree.SubElement(cert, 'serialNumber') serialNumber.text = item['serialNumber']
[ "def _possible_issuers(self, cert):\n \"\"\"\n Returns a generator that will list all possible issuers for the cert\n\n :param cert:\n An asn1crypto.x509.Certificate object to find the issuer of\n \"\"\"\n\n issuer_hashable = cert.issuer.hashable\n if issuer_hash...
[ 0.6695551872253418, 0.6681156158447266, 0.6666167378425598, 0.664018988609314, 0.6620565056800842, 0.6599345207214355, 0.6576005816459656, 0.6559449434280396, 0.6530895233154297, 0.6477333307266235, 0.6466966271400452, 0.6456843614578247 ]
Create or update a label
def label(self, name, color, update=True): """Create or update a label """ url = '%s/labels' % self data = dict(name=name, color=color) response = self.http.post( url, json=data, auth=self.auth, headers=self.headers ) if response.status_code == 201: return True elif response.status_code == 422 and update: url = '%s/%s' % (url, name) response = self.http.patch( url, json=data, auth=self.auth, headers=self.headers ) response.raise_for_status() return False
[ "def create_label(self, label, doc=None, callback=dummy_progress_cb):\n \"\"\"\n Create a new label\n\n Arguments:\n doc --- first document on which the label must be added (required\n for now)\n \"\"\"\n if doc:\n clone = doc.clone() # ma...
[ 0.7641974091529846, 0.7632727026939392, 0.7598841786384583, 0.7563969492912292, 0.7557106018066406, 0.7523928880691528, 0.7517892122268677, 0.7472151517868042, 0.7379534244537354, 0.7373034954071045, 0.7370362877845764, 0.735865592956543 ]
A dictionary with a one-to-one translation of keywords is used to provide the transformation.
def translate(source, dictionary): '''A dictionary with a one-to-one translation of keywords is used to provide the transformation. ''' toks = tokenize.generate_tokens(StringIO(source).readline) result = [] for toktype, tokvalue, _, _, _ in toks: if toktype == tokenize.NAME and tokvalue in dictionary: result.append((toktype, dictionary[tokvalue])) else: result.append((toktype, tokvalue)) return tokenize.untokenize(result)
[ "def transform(matches, framework, namespace, static_endpoint):\n \"\"\"\n The actual transformation occurs here.\n\n flask example: images/staticfy.jpg', ==>\n \"{{ url_for('static', filename='images/staticfy.jpg') }}\"\n \"\"\"\n transformed = []\n namespace = namespace + '/' if namespace...
[ 0.717033326625824, 0.7130061984062195, 0.7078253030776978, 0.707695484161377, 0.7022884488105774, 0.6966860294342041, 0.6933697462081909, 0.6905336380004883, 0.6890057921409607, 0.6862103939056396, 0.6845335364341736, 0.6836443543434143 ]
Function enhance Enhance the object with new item or enhanced items
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'images': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemImages)})
[ "def enhance(self):\n \"\"\" Function enhance\n Enhance the object with new item or enhanced items\n \"\"\"\n self.update({'os_default_templates':\n SubDict(self.api, self.objName,\n self.payloadObj, self.key,\n ...
[ 0.8752948045730591, 0.8729672431945801, 0.8695272207260132, 0.8679497838020325, 0.8630505800247192, 0.8407313823699951, 0.7447202205657959, 0.7079142928123474, 0.707258939743042, 0.6839107275009155, 0.6810131072998047, 0.6799886226654053 ]
Async component of _run
async def _run_payloads(self): """Async component of _run""" delay = 0.0 try: while self.running.is_set(): await self._start_payloads() await self._reap_payloads() await asyncio.sleep(delay) delay = min(delay + 0.1, 1.0) except Exception: await self._cancel_payloads() raise
[ "function doRun() {\n if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening\n Module['calledRun'] = true;\n\n if (ABORT) return;\n\n ensureInitRuntime();\n\n preMain();\n\n\n if (Module['onRuntimeInitialized']) Module['onRuntimeInitial...
[ 0.7492655515670776, 0.7317105531692505, 0.7314708232879639, 0.7230328917503357, 0.7164127826690674, 0.7092439532279968, 0.708595871925354, 0.7068096399307251, 0.7048815488815308, 0.7021708488464355, 0.701999306678772, 0.7010310292243958 ]
Start all queued payloads
async def _start_payloads(self): """Start all queued payloads""" with self._lock: for coroutine in self._payloads: task = self.event_loop.create_task(coroutine()) self._tasks.add(task) self._payloads.clear() await asyncio.sleep(0)
[ "async def _start_payloads(self, nursery):\n \"\"\"Start all queued payloads\"\"\"\n with self._lock:\n for coroutine in self._payloads:\n nursery.start_soon(coroutine)\n self._payloads.clear()\n await trio.sleep(0)", "def _start_payloads(self):\n \...
[ 0.88545161485672, 0.8552003502845764, 0.7891626954078674, 0.7770432233810425, 0.7561456561088562, 0.7468627095222473, 0.7409204840660095, 0.7305784225463867, 0.7299909591674805, 0.7234981060028076, 0.7174237966537476, 0.70259028673172 ]
Clean up all finished payloads
async def _reap_payloads(self): """Clean up all finished payloads""" for task in self._tasks.copy(): if task.done(): self._tasks.remove(task) if task.exception() is not None: raise task.exception() await asyncio.sleep(0)
[ "def _reap_payloads(self):\n \"\"\"Clean up all finished payloads\"\"\"\n for thread in self._threads.copy():\n # CapturingThread.join will throw\n if thread.join(timeout=0):\n self._threads.remove(thread)\n self._logger.debug('reaped thread %s', thr...
[ 0.8029473423957825, 0.7866622805595398, 0.7357620596885681, 0.7221269011497498, 0.7220130562782288, 0.7094706892967224, 0.7041050791740417, 0.7006880640983582, 0.6978424191474915, 0.6969825029373169, 0.6950753331184387, 0.6941037774085999 ]
Cancel all remaining payloads
async def _cancel_payloads(self): """Cancel all remaining payloads""" for task in self._tasks: task.cancel() await asyncio.sleep(0) for task in self._tasks: while not task.done(): await asyncio.sleep(0.1) task.cancel()
[ "private void cancelFutures() {\r\n cancelFuture();\r\n for (Future<PartETag> f : futures) {\r\n f.cancel(true);\r\n }\r\n multipartUploadCallable.getFutures().clear();\r\n futures.clear();\r\n }", "public void cancelAll() {\n if (DBG) Log.v(TAG, \"prepare t...
[ 0.7676242589950562, 0.7511706948280334, 0.7398670315742493, 0.734765350818634, 0.7277913689613342, 0.7266598343849182, 0.7244936227798462, 0.7222749590873718, 0.7204983830451965, 0.7172811627388, 0.7171241641044617, 0.7121745944023132 ]
Check a plaintext password against a hashed password.
def check_password(password: str, encrypted: str) -> bool: """ Check a plaintext password against a hashed password. """ # some old passwords have {crypt} in lower case, and passlib wants it to be # in upper case. if encrypted.startswith("{crypt}"): encrypted = "{CRYPT}" + encrypted[7:] return pwd_context.verify(password, encrypted)
[ "def check_password(self, hashed_password, plain_password):\n \"\"\"Encode the plain_password with the salt of the hashed_password.\n\n Return the comparison with the encrypted_password.\n \"\"\"\n salt, encrypted_password = hashed_password.split('$')\n re_encrypted_password = sel...
[ 0.8291040658950806, 0.8201819062232971, 0.8061956167221069, 0.7911700010299683, 0.7780253291130066, 0.771220326423645, 0.7709529995918274, 0.7700600028038025, 0.7697321772575378, 0.7653699517250061, 0.760883092880249, 0.7587486505508423 ]
Check if version of repository is semantic
def validate(ctx, sandbox): """Check if version of repository is semantic """ m = RepoManager(ctx.obj['agile']) if not sandbox or m.can_release('sandbox'): click.echo(m.validate_version())
[ "def isValidSemver(version):\n \"\"\"Semantic version number - determines whether the version is qualified. The format is MAJOR.Minor.PATCH, more with https://semver.org/\"\"\"\n if version and isinstance(version, string_types):\n try:\n semver.parse(version)\n except (TypeError,Value...
[ 0.7900662422180176, 0.7560533881187439, 0.7444041967391968, 0.734630823135376, 0.7325699925422668, 0.7256373763084412, 0.7142989039421082, 0.7010870575904846, 0.700447142124176, 0.6989374756813049, 0.6981353759765625, 0.6979355812072754 ]
Reset transaction back to original state, discarding all uncompleted transactions.
def reset(self, force_flush_cache: bool = False) -> None: """ Reset transaction back to original state, discarding all uncompleted transactions. """ super(LDAPwrapper, self).reset() if len(self._transactions) == 0: raise RuntimeError("reset called outside a transaction.") self._transactions[-1] = []
[ "protected function resetTransactionNesting()\n {\n // Check whether to use a connector's built-in transaction methods\n if ($this->connector instanceof TransactionalDBConnector) {\n if ($this->transactionNesting > 0) {\n $this->connector->transactionRollback();\n ...
[ 0.743079423904419, 0.7369043231010437, 0.7288176417350769, 0.7235282063484192, 0.717767059803009, 0.7141973376274109, 0.7109276056289673, 0.7049008011817932, 0.7026885747909546, 0.7019297480583191, 0.6986315846443176, 0.6958999633789062 ]
Object state is cached. When an update is required the update will be simulated on this cache, so that rollback information can be correct. This function retrieves the cached data.
def _cache_get_for_dn(self, dn: str) -> Dict[str, bytes]: """ Object state is cached. When an update is required the update will be simulated on this cache, so that rollback information can be correct. This function retrieves the cached data. """ # no cached item, retrieve from ldap self._do_with_retry( lambda obj: obj.search( dn, '(objectclass=*)', ldap3.BASE, attributes=['*', '+'])) results = self._obj.response if len(results) < 1: raise NoSuchObject("No results finding current value") if len(results) > 1: raise RuntimeError("Too many results finding current value") return results[0]['raw_attributes']
[ "def cache(self, bank, key, fun, loop_fun=None, **kwargs):\n '''\n Check cache for the data. If it is there, check to see if it needs to\n be refreshed.\n\n If the data is not there, or it needs to be refreshed, then call the\n callback function (``fun``) with any given ``**kwargs...
[ 0.7165476679801941, 0.6867960691452026, 0.681489884853363, 0.6709518432617188, 0.670445442199707, 0.6700876951217651, 0.6654559969902039, 0.6644994020462036, 0.664233386516571, 0.6624510288238525, 0.6611480712890625, 0.6602258682250977 ]
Are there uncommitted changes?
def is_dirty(self) -> bool: """ Are there uncommitted changes? """ if len(self._transactions) == 0: raise RuntimeError("is_dirty called outside a transaction.") if len(self._transactions[-1]) > 0: return True return False
[ "def is_changed():\n \"\"\" Checks if current project has any noncommited changes. \"\"\"\n executed, changed_lines = execute_git('status --porcelain', output=False)\n merge_not_finished = mod_path.exists('.git/MERGE_HEAD')\n return changed_lines.strip() or merge_not_finished", "public function hasUnp...
[ 0.7411776781082153, 0.7345345616340637, 0.7306894063949585, 0.722993791103363, 0.7170324921607971, 0.7102890610694885, 0.7102832794189453, 0.7063295245170593, 0.7046818733215332, 0.7036717534065247, 0.7031397819519043, 0.7016614079475403 ]
End a transaction. Must not be dirty when doing so. ie. commit() or rollback() must be called if changes made. If dirty, changes will be discarded.
def leave_transaction_management(self) -> None: """ End a transaction. Must not be dirty when doing so. ie. commit() or rollback() must be called if changes made. If dirty, changes will be discarded. """ if len(self._transactions) == 0: raise RuntimeError("leave_transaction_management called outside transaction") elif len(self._transactions[-1]) > 0: raise RuntimeError("leave_transaction_management called with uncommited rollbacks") else: self._transactions.pop()
[ "def end_transaction\n case @transaction_stack.length\n when 0\n PEROBS.log.fatal 'No ongoing transaction to end'\n when 1\n # All transactions completed successfully. Write all modified objects\n # into the backend storage.\n @transaction_stack.pop.each { |id| @transactio...
[ 0.7613028883934021, 0.7468214631080627, 0.7365153431892395, 0.7276989221572876, 0.7214362621307373, 0.7120302319526672, 0.7110478281974792, 0.7089458107948303, 0.7019887566566467, 0.701962411403656, 0.6976029276847839, 0.6961627006530762 ]
Attempt to commit all changes to LDAP database. i.e. forget all rollbacks. However stay inside transaction management.
def commit(self) -> None: """ Attempt to commit all changes to LDAP database. i.e. forget all rollbacks. However stay inside transaction management. """ if len(self._transactions) == 0: raise RuntimeError("commit called outside transaction") # If we have nested transactions, we don't actually commit, but push # rollbacks up to previous transaction. if len(self._transactions) > 1: for on_rollback in reversed(self._transactions[-1]): self._transactions[-2].insert(0, on_rollback) _debug("commit") self.reset()
[ "def commit(using=None):\n \"\"\"\n Does the commit itself and resets the dirty flag.\n \"\"\"\n if using is None:\n for using in tldap.backend.connections:\n connection = tldap.backend.connections[using]\n connection.commit()\n return\n connection = tldap.backend....
[ 0.753044068813324, 0.7456525564193726, 0.7398972511291504, 0.7347856760025024, 0.7339320182800293, 0.7309517860412598, 0.7281948924064636, 0.7263627052307129, 0.726161777973175, 0.7256393432617188, 0.7246240973472595, 0.7228472232818604 ]
Roll back to previous database state. However stay inside transaction management.
def rollback(self) -> None: """ Roll back to previous database state. However stay inside transaction management. """ if len(self._transactions) == 0: raise RuntimeError("rollback called outside transaction") _debug("rollback:", self._transactions[-1]) # if something goes wrong here, nothing we can do about it, leave # database as is. try: # for every rollback action ... for on_rollback in self._transactions[-1]: # execute it _debug("--> rolling back", on_rollback) self._do_with_retry(on_rollback) except: # noqa: E722 _debug("--> rollback failed") exc_class, exc, tb = sys.exc_info() raise tldap.exceptions.RollbackError( "FATAL Unrecoverable rollback error: %r" % exc) finally: # reset everything to clean state _debug("--> rollback success") self.reset()
[ "def rollback(self):\n \"\"\"\n Rolls back changes to this database.\n \"\"\"\n with self.native(writeAccess=True) as conn:\n return self._rollback(conn)", "def rollback(self, sql=None):\n \"\"\"Rollback the current transaction.\"\"\"\n self._transaction = Fals...
[ 0.8180977702140808, 0.7944473028182983, 0.7880658507347107, 0.7859667539596558, 0.7858035564422607, 0.7817387580871582, 0.7748211622238159, 0.7712699174880981, 0.7701363563537598, 0.7673389911651611, 0.7662378549575806, 0.7652589678764343 ]
Process action. oncommit is a callback to execute action, onrollback is a callback to execute if the oncommit() has been called and a rollback is required
def _process(self, on_commit: UpdateCallable, on_rollback: UpdateCallable) -> Any: """ Process action. oncommit is a callback to execute action, onrollback is a callback to execute if the oncommit() has been called and a rollback is required """ _debug("---> commiting", on_commit) result = self._do_with_retry(on_commit) if len(self._transactions) > 0: # add statement to rollback log in case something goes wrong self._transactions[-1].insert(0, on_rollback) return result
[ "def process_remove_action(processors, action, argument):\n \"\"\"Process action removals.\"\"\"\n for processor in processors:\n processor(action, argument)\n db.session.commit()", "def process_action(self):\n \"\"\"\n Process the action and update the related object, returns a bool...
[ 0.7157956957817078, 0.7037403583526611, 0.6952687501907349, 0.6922255754470825, 0.6873927712440491, 0.6869584321975708, 0.6860842704772949, 0.6845464110374451, 0.674855649471283, 0.674591064453125, 0.6743784546852112, 0.6739253401756287 ]
Add a DN to the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
def add(self, dn: str, mod_list: dict) -> None: """ Add a DN to the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ _debug("add", self, dn, mod_list) # if rollback of add required, delete it def on_commit(obj): obj.add(dn, None, mod_list) def on_rollback(obj): obj.delete(dn) # process this action return self._process(on_commit, on_rollback)
[ "def add(self, dn: str, mod_list: dict) -> None:\n \"\"\"\n Add a DN to the LDAP database; See ldap module. Doesn't return a result\n if transactions enabled.\n \"\"\"\n\n return self._do_with_retry(lambda obj: obj.add_s(dn, mod_list))", "def modify(self, dn: str, mod_list: dict...
[ 0.8631446361541748, 0.7442304491996765, 0.7425011992454529, 0.7303652167320251, 0.7275208830833435, 0.7104989886283875, 0.7049483060836792, 0.7048552632331848, 0.704656183719635, 0.7016550898551941, 0.7011139392852783, 0.7001202702522278 ]
Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
def modify(self, dn: str, mod_list: dict) -> None: """ Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ _debug("modify", self, dn, mod_list) # need to work out how to reverse changes in mod_list; result in revlist revlist = {} # get the current cached attributes result = self._cache_get_for_dn(dn) # find the how to reverse mod_list (for rollback) and put result in # revlist. Also simulate actions on cache. for mod_type, l in six.iteritems(mod_list): for mod_op, mod_vals in l: _debug("attribute:", mod_type) if mod_type in result: _debug("attribute cache:", result[mod_type]) else: _debug("attribute cache is empty") _debug("attribute modify:", (mod_op, mod_vals)) if mod_vals is not None: if not isinstance(mod_vals, list): mod_vals = [mod_vals] if mod_op == ldap3.MODIFY_ADD: # reverse of MODIFY_ADD is MODIFY_DELETE reverse = (ldap3.MODIFY_DELETE, mod_vals) elif mod_op == ldap3.MODIFY_DELETE and len(mod_vals) > 0: # Reverse of MODIFY_DELETE is MODIFY_ADD, but only if value # is given if mod_vals is None, this means all values where # deleted. reverse = (ldap3.MODIFY_ADD, mod_vals) elif mod_op == ldap3.MODIFY_DELETE \ or mod_op == ldap3.MODIFY_REPLACE: if mod_type in result: # If MODIFY_DELETE with no values or MODIFY_REPLACE # then we have to replace all attributes with cached # state reverse = ( ldap3.MODIFY_REPLACE, tldap.modlist.escape_list(result[mod_type]) ) else: # except if we have no cached state for this DN, in # which case we delete it. reverse = (ldap3.MODIFY_DELETE, []) else: raise RuntimeError("mod_op of %d not supported" % mod_op) reverse = [reverse] _debug("attribute reverse:", reverse) if mod_type in result: _debug("attribute cache:", result[mod_type]) else: _debug("attribute cache is empty") revlist[mod_type] = reverse _debug("--") _debug("mod_list:", mod_list) _debug("revlist:", revlist) _debug("--") # now the hard stuff is over, we get to the easy stuff def on_commit(obj): obj.modify(dn, mod_list) def on_rollback(obj): obj.modify(dn, revlist) return self._process(on_commit, on_rollback)
[ "def modify(self, dn: str, mod_list: dict) -> None:\n \"\"\"\n Modify a DN in the LDAP database; See ldap module. Doesn't return a\n result if transactions enabled.\n \"\"\"\n\n return self._do_with_retry(lambda obj: obj.modify_s(dn, mod_list))", "def modify_no_rollback(self, dn...
[ 0.8853018879890442, 0.844825029373169, 0.782258152961731, 0.7694916725158691, 0.7637309432029724, 0.7588505148887634, 0.7512859106063843, 0.7361394762992859, 0.7337108254432678, 0.7156156301498413, 0.7155494093894958, 0.713196337223053 ]
Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
def modify_no_rollback(self, dn: str, mod_list: dict): """ Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled. """ _debug("modify_no_rollback", self, dn, mod_list) result = self._do_with_retry(lambda obj: obj.modify_s(dn, mod_list)) _debug("--") return result
[ "def modify(self, dn: str, mod_list: dict) -> None:\n \"\"\"\n Modify a DN in the LDAP database; See ldap module. Doesn't return a\n result if transactions enabled.\n \"\"\"\n\n return self._do_with_retry(lambda obj: obj.modify_s(dn, mod_list))", "def modify(self, dn: str, mod_l...
[ 0.8853018879890442, 0.8312879800796509, 0.782258152961731, 0.7694916725158691, 0.7637309432029724, 0.7588505148887634, 0.7512859106063843, 0.7361394762992859, 0.7337108254432678, 0.7156156301498413, 0.7155494093894958, 0.713196337223053 ]
delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled.
def delete(self, dn: str) -> None: """ delete a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ _debug("delete", self) # get copy of cache result = self._cache_get_for_dn(dn) # remove special values that can't be added def delete_attribute(name): if name in result: del result[name] delete_attribute('entryUUID') delete_attribute('structuralObjectClass') delete_attribute('modifiersName') delete_attribute('subschemaSubentry') delete_attribute('entryDN') delete_attribute('modifyTimestamp') delete_attribute('entryCSN') delete_attribute('createTimestamp') delete_attribute('creatorsName') delete_attribute('hasSubordinates') delete_attribute('pwdFailureTime') delete_attribute('pwdChangedTime') # turn into mod_list list. mod_list = tldap.modlist.addModlist(result) _debug("revlist:", mod_list) # on commit carry out action; on rollback restore cached state def on_commit(obj): obj.delete(dn) def on_rollback(obj): obj.add(dn, None, mod_list) return self._process(on_commit, on_rollback)
[ "def delete(self, dn: str) -> None:\n \"\"\"\n delete a dn in the ldap database; see ldap module. doesn't return a\n result if transactions enabled.\n \"\"\"\n\n return self._do_with_retry(lambda obj: obj.delete_s(dn))", "def delete(connect_spec, dn):\n '''Delete an entry fro...
[ 0.8880426287651062, 0.7907469868659973, 0.7566363215446472, 0.754315197467804, 0.7537108659744263, 0.7459157705307007, 0.7336453795433044, 0.7319474816322327, 0.7308675050735474, 0.7284370064735413, 0.7258713841438293, 0.7221714854240417 ]
rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled.
def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None: """ rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ _debug("rename", self, dn, new_rdn, new_base_dn) # split up the parameters split_dn = tldap.dn.str2dn(dn) split_newrdn = tldap.dn.str2dn(new_rdn) assert(len(split_newrdn) == 1) # make dn unqualified rdn = tldap.dn.dn2str(split_dn[0:1]) # make newrdn fully qualified dn tmplist = [split_newrdn[0]] if new_base_dn is not None: tmplist.extend(tldap.dn.str2dn(new_base_dn)) old_base_dn = tldap.dn.dn2str(split_dn[1:]) else: tmplist.extend(split_dn[1:]) old_base_dn = None newdn = tldap.dn.dn2str(tmplist) _debug("--> commit ", self, dn, new_rdn, new_base_dn) _debug("--> rollback", self, newdn, rdn, old_base_dn) # on commit carry out action; on rollback reverse rename def on_commit(obj): obj.modify_dn(dn, new_rdn, new_superior=new_base_dn) def on_rollback(obj): obj.modify_dn(newdn, rdn, new_superior=old_base_dn) return self._process(on_commit, on_rollback)
[ "def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None:\n \"\"\"\n rename a dn in the ldap database; see ldap module. doesn't return a\n result if transactions enabled.\n \"\"\"\n raise NotImplementedError()", "def rename(self, dn: str, new_rdn: str,...
[ 0.9035313725471497, 0.8929044604301453, 0.8117704391479492, 0.790888786315918, 0.7474083304405212, 0.7388917207717896, 0.7381210923194885, 0.7348619699478149, 0.7344306111335754, 0.7342362999916077, 0.7287878394126892, 0.7264547348022461 ]
for testing purposes only. always fail in commit
def fail(self) -> None: """ for testing purposes only. always fail in commit """ _debug("fail") # on commit carry out action; on rollback reverse rename def on_commit(_obj): raise_testfailure("commit") def on_rollback(_obj): raise_testfailure("rollback") return self._process(on_commit, on_rollback)
[ "BlockInfo[] setReplication(String src,\n short replication,\n int[] oldReplication\n ) throws IOException {\n waitForReady();\n BlockInfo[] fileBlocks = unprotectedSetReplication(src, replication, oldReplication);\n if (fileBlocks != ...
[ 0.7161982655525208, 0.7137223482131958, 0.7107377648353577, 0.7037357687950134, 0.7004218101501465, 0.6989426612854004, 0.698544979095459, 0.6984926462173462, 0.6982054710388184, 0.6975885033607483, 0.6955729722976685, 0.6953396797180176 ]
Utility function made to reproduce range() with unit integer step but with the added possibility of specifying a condition on the looping variable (e.g. var % 2 == 0)
def __experimental_range(start, stop, var, cond, loc={}): '''Utility function made to reproduce range() with unit integer step but with the added possibility of specifying a condition on the looping variable (e.g. var % 2 == 0) ''' locals().update(loc) if start < stop: for __ in range(start, stop): locals()[var] = __ if eval(cond, globals(), locals()): yield __ else: for __ in range(start, stop, -1): locals()[var] = __ if eval(cond, globals(), locals()): yield __
[ "function(n, num, step, everyFn) {\n return rangeEvery(new Range(n, num), step, false, everyFn);\n }", "def range(start, finish, step):\n \"\"\"Like built-in :func:`~builtins.range`, but with float support\"\"\"\n value = start\n while value <= finish:\n yield value\n ...
[ 0.7309202551841736, 0.7157431244850159, 0.7096465229988098, 0.6999817490577698, 0.6988758444786072, 0.6909863352775574, 0.6883873343467712, 0.6878114342689514, 0.6876500248908997, 0.6873431205749512, 0.6870449781417847, 0.6841531991958618 ]
Create a new "for loop" line as a replacement for the original code.
def create_for(line, search_result): '''Create a new "for loop" line as a replacement for the original code. ''' try: return line.format(search_result.group("indented_for"), search_result.group("var"), search_result.group("start"), search_result.group("stop"), search_result.group("cond")) except IndexError: return line.format(search_result.group("indented_for"), search_result.group("var"), search_result.group("start"), search_result.group("stop"))
[ "private void forLoop(Env env, Scope scope, Writer writer) {\r\n\t\tCtrl ctrl = scope.getCtrl();\r\n\t\tObject outer = scope.get(\"for\");\r\n\t\tForLoopStatus forLoopStatus = new ForLoopStatus(outer);\r\n\t\tscope.setLocal(\"for\", forLoopStatus);\r\n\t\t\r\n\t\tExpr init = forCtrl.getInit();\r\n\t\tExpr cond = fo...
[ 0.7122229933738708, 0.7033212780952454, 0.6984545588493347, 0.6954953074455261, 0.691508948802948, 0.6905860304832458, 0.6879541873931885, 0.6808813214302063, 0.6780126690864563, 0.6776462197303772, 0.6738662123680115, 0.672441840171814 ]
Function __setitem__ Set a parameter of a foreman object as a dict @param key: The key to modify @param attribute: The data @return RETURN: The API result
def setOverrideValue(self, attributes, hostName): """ Function __setitem__ Set a parameter of a foreman object as a dict @param key: The key to modify @param attribute: The data @return RETURN: The API result """ self['override'] = True attrType = type(attributes) if attrType is dict: self['parameter_type'] = 'hash' elif attrType is list: self['parameter_type'] = 'array' else: self['parameter_type'] = 'string' orv = self.getOverrideValueForHost(hostName) if orv: orv['value'] = attributes return True else: return self.api.create('{}/{}/{}'.format(self.objName, self.key, 'override_values'), {"override_value": {"match": "fqdn={}".format(hostName), "value": attributes}})
[ "def set(self, key, value, **kwargs):\n \"\"\"Create or update the object.\n\n Args:\n key (str): The key of the object to create/update\n value (str): The value to set for the object\n **kwargs: Extra options to send to the server (e.g. sudo)\n\n Raises:\n ...
[ 0.6773245930671692, 0.6657776832580566, 0.6655950546264648, 0.6570065021514893, 0.6535754799842834, 0.6526169180870056, 0.6494777202606201, 0.646148145198822, 0.6444801092147827, 0.642432689666748, 0.6374896168708801, 0.6358796954154968 ]
Spits out the timedelta in days.
def get_interval_timedelta(self): """ Spits out the timedelta in days. """ now_datetime = timezone.now() current_month_days = monthrange(now_datetime.year, now_datetime.month)[1] # Two weeks if self.interval == reminders_choices.INTERVAL_2_WEEKS: interval_timedelta = datetime.timedelta(days=14) # One month elif self.interval == reminders_choices.INTERVAL_ONE_MONTH: interval_timedelta = datetime.timedelta(days=current_month_days) # Three months elif self.interval == reminders_choices.INTERVAL_THREE_MONTHS: three_months = now_datetime + relativedelta(months=+3) interval_timedelta = three_months - now_datetime # Six months elif self.interval == reminders_choices.INTERVAL_SIX_MONTHS: six_months = now_datetime + relativedelta(months=+6) interval_timedelta = six_months - now_datetime # One year elif self.interval == reminders_choices.INTERVAL_ONE_YEAR: one_year = now_datetime + relativedelta(years=+1) interval_timedelta = one_year - now_datetime return interval_timedelta
[ "def timedelta_days(days: int) -> timedelta64:\n \"\"\"\n Convert a duration in days to a NumPy ``timedelta64`` object.\n \"\"\"\n int_days = int(days)\n if int_days != days:\n raise ValueError(\"Fractional days passed to timedelta_days: \"\n \"{!r}\".format(days))\n ...
[ 0.7762075066566467, 0.7667632102966309, 0.7661012411117554, 0.7383315563201904, 0.7279061675071716, 0.7184981107711792, 0.7174055576324463, 0.7161235213279724, 0.7108481526374817, 0.7064957618713379, 0.7033786773681641, 0.7020765542984009 ]
Execute a runner without blocking the event loop
async def awaitable_runner(runner: BaseRunner): """Execute a runner without blocking the event loop""" runner_thread = CapturingThread(target=runner.run) runner_thread.start() delay = 0.0 while not runner_thread.join(timeout=0): await asyncio.sleep(delay) delay = min(delay + 0.1, 1.0)
[ "def _run_runner(self):\n '''\n Actually execute specific runner\n :return:\n '''\n import salt.minion\n ret = {}\n low = {'fun': self.opts['fun']}\n try:\n # Allocate a jid\n async_pub = self._gen_async_pub()\n self.jid = asyn...
[ 0.7569867372512817, 0.7517397999763489, 0.7422463297843933, 0.731895923614502, 0.7290554046630859, 0.7282692193984985, 0.728164553642273, 0.726593017578125, 0.7192322611808777, 0.7190721035003662, 0.7166314721107483, 0.716503381729126 ]
Create an ``asyncio`` event loop running in the main thread and watching runners Using ``asyncio`` to handle suprocesses requires a specific loop type to run in the main thread. This function sets up and runs the correct loop in a portable way. In addition, it runs a single :py:class:`~.BaseRunner` until completion or failure. .. seealso:: The `issue #8 <https://github.com/MatterMiners/cobald/issues/8>`_ for details.
def asyncio_main_run(root_runner: BaseRunner): """ Create an ``asyncio`` event loop running in the main thread and watching runners Using ``asyncio`` to handle suprocesses requires a specific loop type to run in the main thread. This function sets up and runs the correct loop in a portable way. In addition, it runs a single :py:class:`~.BaseRunner` until completion or failure. .. seealso:: The `issue #8 <https://github.com/MatterMiners/cobald/issues/8>`_ for details. """ assert threading.current_thread() == threading.main_thread(), 'only main thread can accept asyncio subprocesses' if sys.platform == 'win32': event_loop = asyncio.ProactorEventLoop() asyncio.set_event_loop(event_loop) else: event_loop = asyncio.get_event_loop() asyncio.get_child_watcher().attach_loop(event_loop) event_loop.run_until_complete(awaitable_runner(root_runner))
[ "def event_loop(self):\n \"\"\"asyncio.BaseEventLoop: the running event loop.\n\n This fixture mainly exists to allow for overrides during unit tests.\n\n \"\"\"\n if not self._event_loop:\n self._event_loop = asyncio.get_event_loop()\n return self._event_loop", "def ...
[ 0.7763006091117859, 0.7691020965576172, 0.7420839071273804, 0.742028534412384, 0.7414741516113281, 0.7392086982727051, 0.728949248790741, 0.7274221181869507, 0.726391077041626, 0.7239053249359131, 0.7224150896072388, 0.7181748747825623 ]
Function enhance Enhance the object with new item or enhanced items
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'os_default_templates': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemOsDefaultTemplate)}) self.update({'operatingsystems': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemOperatingSystem)})
[ "def enhance(self):\n \"\"\" Function enhance\n Enhance the object with new item or enhanced items\n \"\"\"\n self.update({'os_default_templates':\n SubDict(self.api, self.objName,\n self.payloadObj, self.key,\n ...
[ 0.8752948045730591, 0.8729672431945801, 0.8696154356002808, 0.8679497838020325, 0.8630505800247192, 0.8407313823699951, 0.7447202205657959, 0.7079142928123474, 0.707258939743042, 0.6839107275009155, 0.6810131072998047, 0.6799886226654053 ]
Retry "tries" times, with initial "delay", increasing delay "delay*backoff" each time. Without exception success means when function returns valid object. With exception success when no exceptions
def retry(tries=10, delay=1, backoff=2, retry_exception=None): """ Retry "tries" times, with initial "delay", increasing delay "delay*backoff" each time. Without exception success means when function returns valid object. With exception success when no exceptions """ assert tries > 0, "tries must be 1 or greater" catching_mode = bool(retry_exception) def deco_retry(f): @functools.wraps(f) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay while mtries > 0: time.sleep(mdelay) mdelay *= backoff try: rv = f(*args, **kwargs) if not catching_mode and rv: return rv except retry_exception: pass else: if catching_mode: return rv mtries -= 1 if mtries is 0 and not catching_mode: return False if mtries is 0 and catching_mode: return f(*args, **kwargs) # extra try, to avoid except-raise syntax log.debug("{0} try, sleeping for {1} sec".format(tries-mtries, mdelay)) raise Exception("unreachable code") return f_retry return deco_retry
[ "def retry(tries, delay=0, back_off=1, raise_msg=''):\n \"\"\"Retries a function or method until it got True.\n\n - ``delay`` sets the initial delay in seconds\n - ``back_off`` sets the factor by which\n - ``raise_msg`` if not '', it'll raise an Exception\n \"\"\"\n\n if back_off < 1:\n rai...
[ 0.8513075113296509, 0.8424427509307861, 0.8363626003265381, 0.8320958614349365, 0.829943060874939, 0.828590452671051, 0.8209466338157654, 0.8207831382751465, 0.8187723755836487, 0.8158443570137024, 0.8038476705551147, 0.7988787889480591 ]
Dump initialized object structure to yaml
def dump(node): """ Dump initialized object structure to yaml """ from qubell.api.private.platform import Auth, QubellPlatform from qubell.api.private.organization import Organization from qubell.api.private.application import Application from qubell.api.private.instance import Instance from qubell.api.private.revision import Revision from qubell.api.private.environment import Environment from qubell.api.private.zone import Zone from qubell.api.private.manifest import Manifest # Exclude keys from dump # Format: { 'ClassName': ['fields', 'to', 'exclude']} exclusion_list = { Auth: ['cookies'], QubellPlatform:['auth', ], Organization: ['auth', 'organizationId', 'zone'], Application: ['auth', 'applicationId', 'organization'], Instance: ['auth', 'instanceId', 'application'], Manifest: ['name', 'content'], Revision: ['auth', 'revisionId'], Environment: ['auth', 'environmentId', 'organization'], Zone: ['auth', 'zoneId', 'organization'], } def obj_presenter(dumper, obj): for x in exclusion_list.keys(): if isinstance(obj, x): # Find class fields = obj.__dict__.copy() for excl_item in exclusion_list[x]: try: fields.pop(excl_item) except: log.warn('No item %s in object %s' % (excl_item, x)) return dumper.represent_mapping('tag:yaml.org,2002:map', fields) return dumper.represent_mapping('tag:yaml.org,2002:map', obj.__dict__) noalias_dumper = yaml.dumper.Dumper noalias_dumper.ignore_aliases = lambda self, data: True yaml.add_representer(unicode, lambda dumper, value: dumper.represent_scalar(u'tag:yaml.org,2002:str', value)) yaml.add_multi_representer(object, obj_presenter) serialized = yaml.dump(node, default_flow_style=False, Dumper=noalias_dumper) return serialized
[ "def dump\n out = \"\\#<#{self.class}:0x#{format('%08x', object_id)}>\\n\"\n out << \"Magic number : #{format('%0x', @sb['magic_num'])}\\n\"\n out << \"Block size : #{@sb['block_size']} (#{@block_size} bytes)\\n\"\n out << \"Number of blocks : #{@sb['data_blocks']}...
[ 0.7340636253356934, 0.7310830950737, 0.7280782461166382, 0.7258572578430176, 0.7238344550132751, 0.7223688960075378, 0.7212656736373901, 0.7188830375671387, 0.7150736451148987, 0.7141214609146118, 0.7138819098472595, 0.713685929775238 ]
Generate environment used for 'org.restore' method :param file: env file :return: env
def load_env(file): """ Generate environment used for 'org.restore' method :param file: env file :return: env """ env = yaml.load(open(file)) for org in env.get('organizations', []): if not org.get('applications'): org['applications'] = [] if org.get('starter-kit'): kit_meta = get_starter_kit_meta(org.get('starter-kit')) for meta_app in get_applications_from_metadata(kit_meta): org['applications'].append(meta_app) if org.get('meta'): for meta_app in get_applications_from_metadata(org.get('meta')): org['applications'].append(meta_app) for app in org.get('applications', []): if app.get('file'): app['file'] = os.path.realpath(os.path.join(os.path.dirname(file), app['file'])) return env
[ "def generate_env(fname=None):\n \"\"\"Generate file with exports. \n\n By default this is in .config/genomepy/exports.txt.\n\n Parameters\n ----------\n fname: strs, optional\n Name of the output file.\n \"\"\"\n config_dir = user_config_dir(\"genomepy\")\n if os.path.exists(config_d...
[ 0.7047730684280396, 0.7017318606376648, 0.6866380572319031, 0.6833397150039673, 0.6820922493934631, 0.6766843199729919, 0.6760852932929993, 0.6714118123054504, 0.6713417768478394, 0.6699016690254211, 0.6695418953895569, 0.6689802408218384 ]