code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_get_genome(self): <NEW_LINE> <INDENT> genome = "sacCer3" <NEW_LINE> fadir = tempfile.mkdtemp(prefix="gimme.") <NEW_LINE> genome_dir = os.path.join(fadir, genome) <NEW_LINE> index_dir = tempfile.mkdtemp(prefix="gimme.") <NEW_LINE> get_genome(genome, fadir, index_dir) <NEW_LINE> self.assertEquals(17, len(glob(os.path.join(genome_dir, "*.fa*")))) <NEW_LINE> for d in fadir, index_dir: <NEW_LINE> <INDENT> rmtree(d)
test automatic install of genome
625941c0aad79263cf3909a4
def getCodes(self, active=True): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for (insname, d) in insinfo.items(): <NEW_LINE> <INDENT> if active: <NEW_LINE> <INDENT> if d['active']: <NEW_LINE> <INDENT> res.append( self.nameMap[insname]['code'] ) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> res.append( self.nameMap[insname]['code'] ) <NEW_LINE> <DEDENT> <DEDENT> res.sort() <NEW_LINE> return res
Returns all the known instrument codes.
625941c066673b3332b91ff7
def __init__(self, regionId, backupId, ): <NEW_LINE> <INDENT> self.regionId = regionId <NEW_LINE> self.backupId = backupId
:param regionId: 地域代码,取值范围参见[《各地域及可用区对照表》](../Enum-Definitions/Regions-AZ.md) :param backupId: 备份ID
625941c02eb69b55b151c813
@register.inclusion_tag('social/_activity_item.html') <NEW_LINE> def activity_item(action, **kwargs): <NEW_LINE> <INDENT> actor = action.actor <NEW_LINE> activity_class = 'activity' <NEW_LINE> verb = action.verb <NEW_LINE> username = actor.username if actor else "someone" <NEW_LINE> target = action.target <NEW_LINE> object_type = None <NEW_LINE> object = action.action_object <NEW_LINE> raw_action = get_data(action, 'raw_action') <NEW_LINE> object_name = get_data(action, 'object_name') <NEW_LINE> preposition = _("to") <NEW_LINE> fragment = None <NEW_LINE> if object: <NEW_LINE> <INDENT> object_type = object.__class__._meta.object_name.lower() <NEW_LINE> <DEDENT> if target: <NEW_LINE> <INDENT> target_type = target.__class__._meta.object_name.lower() <NEW_LINE> <DEDENT> if object: <NEW_LINE> <INDENT> if object_type == 'comment': <NEW_LINE> <INDENT> activity_class = 'comment' <NEW_LINE> preposition = _("on") <NEW_LINE> object = None <NEW_LINE> fragment = "comments" <NEW_LINE> <DEDENT> if object_type == 'map': <NEW_LINE> <INDENT> activity_class = 'map' <NEW_LINE> <DEDENT> if object_type == 'layer': <NEW_LINE> <INDENT> activity_class = 'layer' <NEW_LINE> <DEDENT> if object_type == 'document': <NEW_LINE> <INDENT> activity_class = 'document' <NEW_LINE> <DEDENT> <DEDENT> if raw_action == 'deleted': <NEW_LINE> <INDENT> activity_class = 'delete' <NEW_LINE> <DEDENT> if raw_action == 'created' and object_type in ('layer', 'document'): <NEW_LINE> <INDENT> activity_class = 'upload' <NEW_LINE> <DEDENT> ctx = dict( activity_class=activity_class, action=action, actor=actor, object=object, object_name=object_name, preposition=preposition, target=target, timestamp=action.timestamp, username=username, verb=verb, fragment=fragment ) <NEW_LINE> return ctx
Provides a location to manipulate an action in preparation for display.
625941c00fa83653e4656f23
@merge(threePrimeBias, "qc.dir/qc_three_prime_bias.load") <NEW_LINE> def loadThreePrimeBias(infiles, outfile): <NEW_LINE> <INDENT> P.concatenate_and_load(infiles, outfile, regex_filename=".*/.*/(.*).three.prime.bias", cat="sample_id", options='-i "sample_id"')
Load the metrics in the project database.
625941c0046cf37aa974ccb0
def setUp(self): <NEW_LINE> <INDENT> if not self.prepared: <NEW_LINE> <INDENT> Object.objects.all().delete() <NEW_LINE> self.group, created = Group.objects.get_or_create(name='test') <NEW_LINE> duser, created = DjangoUser.objects.get_or_create( username=self.username) <NEW_LINE> duser.set_password(self.password) <NEW_LINE> duser.save() <NEW_LINE> self.user, created = User.objects.get_or_create(user=duser) <NEW_LINE> self.user.save() <NEW_LINE> perspective, created = Perspective.objects.get_or_create( name='default') <NEW_LINE> perspective.set_default_user() <NEW_LINE> perspective.save() <NEW_LINE> ModuleSetting.set('default_perspective', perspective.id) <NEW_LINE> self.perspective = Perspective(name='test') <NEW_LINE> self.perspective.set_default_user() <NEW_LINE> self.perspective.save() <NEW_LINE> self.group = Group(name='test') <NEW_LINE> self.group.save() <NEW_LINE> self.client = Client() <NEW_LINE> self.prepared = True
Initial Setup
625941c02c8b7c6e89b35729
def _SaveInstanceStash(self, instance_name, data): <NEW_LINE> <INDENT> stash_file = self._InstanceStashFilePath(instance_name) <NEW_LINE> serialized = serializer.Dump(data) <NEW_LINE> try: <NEW_LINE> <INDENT> utils.WriteFile(stash_file, data=serialized, mode=constants.SECURE_FILE_MODE) <NEW_LINE> <DEDENT> except EnvironmentError as err: <NEW_LINE> <INDENT> raise HypervisorError("Failed to save instance stash file %s : %s" % (stash_file, err))
Save data to the instance stash file in serialized format.
625941c0be8e80087fb20bad
def ex_write(tag, value): <NEW_LINE> <INDENT> comm.Write(tag, value)
simple tag write
625941c091f36d47f21ac457
def test_burst_selection_ranges(data): <NEW_LINE> <INDENT> d = data <NEW_LINE> d.burst_search() <NEW_LINE> d.calc_max_rate(m=10, ph_sel=Ph_sel(Dex='DAem')) <NEW_LINE> Range = namedtuple('Range', ['min', 'max', 'getter']) <NEW_LINE> sel_functions = dict( E=Range(0.5, 1, None), nd=Range(30, 40, None), na=Range(30, 40, None), time=Range(1, 61, lambda d, ich: d.mburst[ich].start * d.clk_p), width=Range(0.5, 1.5, lambda d, ich: d.mburst[ich].width * d.clk_p*1e3), peak_phrate=Range(50e3, 150e3, lambda d, ich: d.max_rate[ich])) <NEW_LINE> if d.alternated: <NEW_LINE> <INDENT> sel_functions.update(naa=Range(30, 40, None), S=Range(0.3, 0.7, None)) <NEW_LINE> <DEDENT> for func_name, range_ in sel_functions.items(): <NEW_LINE> <INDENT> func = getattr(select_bursts, func_name) <NEW_LINE> getter = range_.getter <NEW_LINE> if getter is None: <NEW_LINE> <INDENT> getter = lambda d, ich: d[func_name][ich] <NEW_LINE> <DEDENT> ds = d.select_bursts(func, args=(range_.min, range_.max)) <NEW_LINE> for ich in range(d.nch): <NEW_LINE> <INDENT> selected = getter(ds, ich) <NEW_LINE> assert ((selected >= range_.min) * (selected <= range_.max)).all()
Test selection functions having a min-max range.
625941c063f4b57ef0001086
def getProbabilityForDifferential(Xi, Yi): <NEW_LINE> <INDENT> return self.DDT[Xi][Yi] <NEW_LINE> return
Returns the probability of a differential according to a given input/output difference
625941c05fc7496912cc38e5
def predict(self, X): <NEW_LINE> <INDENT> if self.method == 'primal': <NEW_LINE> <INDENT> return np.where(X.dot(self.w) + self.w_0 > 0, 1, -1) <NEW_LINE> <DEDENT> elif self.method == 'dual': <NEW_LINE> <INDENT> if self.kernel == 'linear': <NEW_LINE> <INDENT> Gramm = X.dot(self.sv.T) <NEW_LINE> <DEDENT> elif self.kernel == 'polynomial': <NEW_LINE> <INDENT> Gramm = self.poly_kernel(X1=X, X2=self.sv, d=self.d) <NEW_LINE> <DEDENT> elif self.kernel == 'rbf': <NEW_LINE> <INDENT> Gramm = self.rbf_kernel(X1=X, X2=self.sv, gamma=self.gamma) <NEW_LINE> <DEDENT> return np.where((self.lambdas[self.lambdas > 0] * self.sv_y * Gramm).sum(axis=1) + self.w_0 > 0, 1, -1)
Метод для получения предсказаний на данных X - переменная типа numpy.array, признаковые описания объектов из обучающей выборки
625941c04a966d76dd550f74
def test_simple(self): <NEW_LINE> <INDENT> with open('list', 'w') as fh: <NEW_LINE> <INDENT> fh.write("foo\nbar\n") <NEW_LINE> <DEDENT> for t in ['script', 'moderate_cm', 'moderate_cm_simulation', 'fast_cm', 'fast_cm_simulation', 'moderate_am']: <NEW_LINE> <INDENT> check_output(['allosmod', 'make_pm_script', '--', 'target', 'list', '-333', '4.0', t, '300.0']) <NEW_LINE> <DEDENT> for f in ('model_run.py', 'list'): <NEW_LINE> <INDENT> os.unlink(f)
Simple complete run of make_pm_script
625941c007d97122c41787ed
def __init__(self, name="", info="", bind=None): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._info = info <NEW_LINE> self._bind = bind <NEW_LINE> self._parent_set = False
@brief Creates an option within a menu @var name: The value the user sees in the menu. @var info: What the menu option's suppose to do. @var bind: The method/function bound to a click-event on that option.
625941c0ac7a0e7691ed4037
def generate(self, numRows): <NEW_LINE> <INDENT> yh = [] <NEW_LINE> for i in range(numRows): <NEW_LINE> <INDENT> tlist = [] <NEW_LINE> for j in range(i+1): <NEW_LINE> <INDENT> if j==0 or j==i: <NEW_LINE> <INDENT> tlist.append(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tlist.append(yh[i-1][j-1]+yh[i-1][j]) <NEW_LINE> <DEDENT> <DEDENT> yh.append(tlist) <NEW_LINE> <DEDENT> return yh
:type numRows: int :rtype: List[List[int]]
625941c0bd1bec0571d90595
def finalize(self): <NEW_LINE> <INDENT> common.replace_in_file(self.lua_file, 'local out_file = "' + self.results_file + '"', 'local out_file = ""') <NEW_LINE> for stack_name in self.neighbor_stack_names: <NEW_LINE> <INDENT> common.DEPLOYMENT_UNIT.destroy_heat_template(stack_name) <NEW_LINE> <DEDENT> self.neighbor_stack_names = list()
Finalizes the benchmark return: None
625941c0d99f1b3c44c674fb
def finish_research(self): <NEW_LINE> <INDENT> self.building_id = 0 <NEW_LINE> self.cost_money = 0 <NEW_LINE> self.cost_food = 0 <NEW_LINE> self.consume_time = 0 <NEW_LINE> self.start_time = 0 <NEW_LINE> self.is_upgrade = False <NEW_LINE> return True
结束研究
625941c09f2886367277a7f6
def filter_keys(key_list, args, sign="="): <NEW_LINE> <INDENT> return [s+sign for s in key_list if any_startswith(args, s+sign) is None]
Return list item which not be completed yet
625941c01d351010ab855a83
def set_ID(self, value): <NEW_LINE> <INDENT> super(GetRecordInputSet, self)._set_input('ID', value)
Set the value of the ID input for this Choreo. ((required, string) The id of the object that you want to retrieve.)
625941c0be7bc26dc91cd56b
def write_files(self, cache_files: CacheFiles, *args, **kwargs) -> None: <NEW_LINE> <INDENT> writers = [ tf.io.TFRecordWriter(path) for path in cache_files.tfrecord_files ] <NEW_LINE> ann_json_dict = {'images': [], 'annotations': [], 'categories': []} <NEW_LINE> for class_id, class_name in self.label_map.items(): <NEW_LINE> <INDENT> c = {'supercategory': 'none', 'id': class_id, 'name': class_name} <NEW_LINE> ann_json_dict['categories'].append(c) <NEW_LINE> <DEDENT> size = 0 <NEW_LINE> for idx, xml_dict in enumerate(self._get_xml_dict(*args, **kwargs)): <NEW_LINE> <INDENT> if self.max_num_images and idx >= self.max_num_images: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if idx % 100 == 0: <NEW_LINE> <INDENT> tf.compat.v1.logging.info('On image %d' % idx) <NEW_LINE> <DEDENT> tf_example = create_pascal_tfrecord.dict_to_tf_example( xml_dict, self.images_dir, self.label_name2id_dict, self.unique_id, ignore_difficult_instances=self.ignore_difficult_instances, ann_json_dict=ann_json_dict) <NEW_LINE> writers[idx % self.num_shards].write(tf_example.SerializeToString()) <NEW_LINE> size = idx + 1 <NEW_LINE> <DEDENT> for writer in writers: <NEW_LINE> <INDENT> writer.close() <NEW_LINE> <DEDENT> meta_data = {'size': size, 'label_map': self.label_map} <NEW_LINE> with tf.io.gfile.GFile(cache_files.meta_data_file, 'w') as f: <NEW_LINE> <INDENT> yaml.dump(meta_data, f) <NEW_LINE> <DEDENT> with tf.io.gfile.GFile(cache_files.annotations_json_file, 'w') as f: <NEW_LINE> <INDENT> json.dump(ann_json_dict, f, indent=2)
Writes TFRecord, meta_data and annotations json files. Args: cache_files: CacheFiles object including a list of TFRecord files, the annotations json file with COCO data format containing golden bounding boxes and the meda data yaml file to save the meta_data including data size and label_map. *args: Non-keyword of parameters used in the `_get_xml_dict` method. **kwargs: Keyword parameters used in the `_get_xml_dict` method.
625941c0aad79263cf3909a5
@pytest.mark.xfail <NEW_LINE> def test_targetlist_table_roundtrip(targetlist): <NEW_LINE> <INDENT> tl = TargetList.from_table(targetlist.table()) <NEW_LINE> assert tl.names == targetlist.names
Round trip via table.
625941c05166f23b2e1a50c0
def make_critic(self, obs, reuse=False, scope="qf"): <NEW_LINE> <INDENT> if self.model_params["model_type"] == "conv": <NEW_LINE> <INDENT> vf_h = create_conv( obs=obs, image_height=self.model_params["image_height"], image_width=self.model_params["image_width"], image_channels=self.model_params["image_channels"], ignore_flat_channels=self.model_params["ignore_flat_channels"], ignore_image=self.model_params["ignore_image"], filters=self.model_params["filters"], kernel_sizes=self.model_params["kernel_sizes"], strides=self.model_params["strides"], act_fun=self.model_params["act_fun"], layer_norm=self.model_params["layer_norm"], batch_norm=self.model_params["batch_norm"], phase=self.phase_ph, dropout=self.model_params["dropout"], rate=self.rate_ph, scope=scope, reuse=reuse, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> vf_h = obs <NEW_LINE> <DEDENT> return create_fcnet( obs=vf_h, layers=self.model_params["layers"], num_output=1, stochastic=False, act_fun=self.model_params["act_fun"], layer_norm=self.model_params["layer_norm"], batch_norm=self.model_params["batch_norm"], phase=self.phase_ph, dropout=self.model_params["dropout"], rate=self.rate_ph, scope=scope, reuse=reuse, )
Create a critic tensor. Parameters ---------- obs : tf.compat.v1.placeholder the input observation placeholder reuse : bool whether or not to reuse parameters scope : str the scope name of the actor Returns ------- tf.Variable the output from the critic
625941c066656f66f7cbc111
def return_loops_with_choices(loops): <NEW_LINE> <INDENT> loops_with_choices = [] <NEW_LINE> for loop in loops: <NEW_LINE> <INDENT> for child in loop.get_children()[:2]: <NEW_LINE> <INDENT> if child.name == 'choice': <NEW_LINE> <INDENT> loops_with_choices.append(loop) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return loops_with_choices
returns all the loop nodes that have a choice as the first or second child
625941c04f6381625f1149a4
def _set_handle(self, handle: Any, prior_ref_count: int = 0): <NEW_LINE> <INDENT> if not self._is_valid_handle(handle): <NEW_LINE> <INDENT> raise Exception("The handle argument is not a valid handle") <NEW_LINE> <DEDENT> self._handle = handle <NEW_LINE> self._ref_count = prior_ref_count + 1
Sets a handle, after performing checks on its suitability as a handle for this object. Args: handle (object): The handle (e.g. cffi pointer) to the native resource. prior_ref_count (int): the initial reference count. Default 0 if this NativeHandle is sole responsible for the lifecycle of the resource. Exceptions: error message when a handle is not a valid object.
625941c08c0ade5d55d3e920
def allsentimentAnalysis(folderName,value=['Subject','Date','To', 'From','Body'],all_sent=['sent','_sent_mail','sent_items','_sent'],start_date='1 1 1998',end_date='31 12 2002'): <NEW_LINE> <INDENT> file=os.listdir(folderName) <NEW_LINE> allsentimentAnalysis.scores=defaultdict(list) <NEW_LINE> body=[] <NEW_LINE> subject=[] <NEW_LINE> i=0 <NEW_LINE> if(type(all_sent) is not list): <NEW_LINE> <INDENT> all_sent=[all_sent] <NEW_LINE> <DEDENT> for item in file: <NEW_LINE> <INDENT> if os.name == 'posix' : <NEW_LINE> <INDENT> sentForUser = userSentAnalysis(folderName+'/'+item,value,all_sent,start_date,end_date) <NEW_LINE> allsentimentAnalysis.scores['Body'].append(sentForUser['Body']) <NEW_LINE> allsentimentAnalysis.scores['Subject'].append(sentForUser['Subject']) <NEW_LINE> print(userSentAnalysis(folderName+'/'+item,value,all_sent,start_date,end_date)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Checking for user"+item) <NEW_LINE> print(i+1) <NEW_LINE> sentForUser = userSentAnalysis(folderName+'\\'+item,value,all_sent,start_date,end_date) <NEW_LINE> body.append(sentForUser['Body']) <NEW_LINE> subject.append(sentForUser['Subject']) <NEW_LINE> <DEDENT> <DEDENT> allsentimentAnalysis.scores['Body']= body [0] <NEW_LINE> for i in range ( 1, len(body)): <NEW_LINE> <INDENT> allsentimentAnalysis.scores['Body']=allsentimentAnalysis.scores['Body']+body[i] <NEW_LINE> <DEDENT> for i in range ( 1, len(subject)): <NEW_LINE> <INDENT> allsentimentAnalysis.scores['Subject']=allsentimentAnalysis.scores['Subject']+subject[i] <NEW_LINE> <DEDENT> return allsentimentAnalysis.scores
Return a list of sentiment analysis for all the emails value: the different section of the email can be user specified default to ['Subject','Date','To', 'From','Body'] all_sent:contains the directory to all the sent emails can be user specified default to ['sent','_sent_mail','sent_items','_sent'] start_date: the minimum date that an email can have to be considered. It has a format of 'month day year' Default to '1 1 1998' end_date: The maximum email date that an email can have to be considered. It has a format of 'month day year' Default '31 12 2002' Returned type: a list
625941c015fb5d323cde0a73
def test_single_post(self): <NEW_LINE> <INDENT> category = create_category("General") <NEW_LINE> sample_user = create_user("user1","password") <NEW_LINE> create_post("Test Post 1", "test-post-1", "Test Post 1 Text", category, sample_user) <NEW_LINE> response = self.client.get(reverse('blog:index')) <NEW_LINE> self.assertQuerysetEqual( response.context['post_list'], ['<Post: Test Post 1>'] )
A single post is visible from the index page
625941c0d53ae8145f87a1db
def alternate_payment_types_guid_get(self, toast_restaurant_external_id, guid, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.alternate_payment_types_guid_get_with_http_info(toast_restaurant_external_id, guid, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.alternate_payment_types_guid_get_with_http_info(toast_restaurant_external_id, guid, **kwargs) <NEW_LINE> return data
Returns information about an alternative form of payment configured for a restaurant. Returns an <a href="#/definitions/AlternatePaymentType">`AlternatePaymentType`</a> object containing information about an alternative form of payment configured for a restaurant. Alternate payment types are forms of payment that are not standard in the Toast POS and that are configured for a particular restaurant. For example, a third-party service that processes payments might be configured as an alternate payment type. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.alternate_payment_types_guid_get(toast_restaurant_external_id, guid, callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) :param str toast_restaurant_external_id: The Toast POS GUID of the restaurant that the alternate payment type is configured for. (required) :param str guid: The Toast POS GUID of the alternative form of payment. (required) :return: AlternatePaymentType If the method is called asynchronously, returns the request thread.
625941c01d351010ab855a84
def after(*params): <NEW_LINE> <INDENT> def decorator(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def decorated_func(self, *args, **kwargs): <NEW_LINE> <INDENT> return f(self, *args, **kwargs) <NEW_LINE> <DEDENT> ctx.callbacks.append_to_after_actions( _get_caller_id_by_frame(inspect.currentframe().f_back), decorated_func) <NEW_LINE> return decorated_func <NEW_LINE> <DEDENT> return decorator
to specify the action will be executed after task.
625941c0796e427e537b052b
def set_file_logger(self, log_level, path, logger_name='internetarchive'): <NEW_LINE> <INDENT> _log_level = { 'CRITICAL': 50, 'ERROR': 40, 'WARNING': 30, 'INFO': 20, 'DEBUG': 10, 'NOTSET': 0, } <NEW_LINE> log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' <NEW_LINE> _log = logging.getLogger(logger_name) <NEW_LINE> _log.setLevel(logging.DEBUG) <NEW_LINE> fh = logging.FileHandler(path) <NEW_LINE> fh.setLevel(_log_level[log_level]) <NEW_LINE> formatter = logging.Formatter(log_format) <NEW_LINE> fh.setFormatter(formatter) <NEW_LINE> _log.addHandler(fh)
Convenience function to quickly configure any level of logging to a file. :type log_level: str :param log_level: A log level as specified in the `logging` module. :type path: string :param path: Path to the log file. The file will be created if it doesn't already exist. :type logger_name: str :param logger_name: (optional) The name of the logger.
625941c0dd821e528d63b112
def list_length(self): <NEW_LINE> <INDENT> return len(self.input_list);
Returns an int of the input_list
625941c0ff9c53063f47c15c
def f3(x): <NEW_LINE> <INDENT> if x%2 == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Sprawdza, czy liczba jest parzysta
625941c0167d2b6e31218afd
def _get_parameters(self): <NEW_LINE> <INDENT> self._resolve_cycles("parameter", Parameter) <NEW_LINE> param_dict = self._get_ordered_filtered_types(Parameter, "variables") <NEW_LINE> param_dict = {k: v for k, v in param_dict.items() if v._iscyclebase is False} <NEW_LINE> return ParameterCollection.from_dict(param_dict)
Sorts by order number and resolves cycles each time it is called.
625941c0e64d504609d747a7
def EmblCdsFeatureIterator(handle, alphabet=generic_protein) : <NEW_LINE> <INDENT> return EmblScanner(debug=0).parse_cds_features(handle, alphabet)
Breaks up a EMBL file into SeqRecord objects for each CDS feature Every section from the LOCUS line to the terminating // can contain many CDS features. These are returned as with the stated amino acid translation sequence (if given).
625941c0baa26c4b54cb1089
def is_active(self, when = None): <NEW_LINE> <INDENT> if not when: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.begin_date > when: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.end_date < when: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Return True if the individual was active with the collaboration on the given date (a datetime object). If no date is given, then active is always True
625941c0293b9510aa2c3200
def eval_module(input): <NEW_LINE> <INDENT> halp_lines = [] <NEW_LINE> halp_linenos = [] <NEW_LINE> for i, line in enumerate(input): <NEW_LINE> <INDENT> if line.startswith('/// '): <NEW_LINE> <INDENT> halp_lines.append(line[len('/// '):]) <NEW_LINE> halp_linenos.append(i+1) <NEW_LINE> <DEDENT> <DEDENT> result_string = call_v8halp('\n'.join(input), halp_lines) <NEW_LINE> result_lines = result_string.split('\n') <NEW_LINE> result_chunks = [] <NEW_LINE> j = 0 <NEW_LINE> while j < len(result_lines): <NEW_LINE> <INDENT> if result_lines[j] == '': break <NEW_LINE> nlines = int(result_lines[j]) <NEW_LINE> result_chunks.append(result_lines[j+1:j+1+nlines]) <NEW_LINE> j += 1 + nlines <NEW_LINE> <DEDENT> assert len(result_chunks) == len(halp_linenos) <NEW_LINE> output = list(input) <NEW_LINE> for lineno, chunk in reversed(zip(halp_linenos, result_chunks)): <NEW_LINE> <INDENT> output[lineno:lineno] = ['//. ' + line for line in chunk] <NEW_LINE> <DEDENT> return output
Given a module's code as a list of lines, produce the Halp output as a list of lines.
625941c00c0af96317bb8150
def enabled(self): <NEW_LINE> <INDENT> return len(self.settings) >= 1
Whether this Collector is enabled for this run. Here, collectors can check whether services are installed, or relevant settings are present in the config, etc. RETURN: : boolean whether this collector is enabled for this run
625941c0090684286d50ec4b
def lose_position(self, axes): <NEW_LINE> <INDENT> self._log.info('{"event":"gcode_state_change", "change":"lose_position"}') <NEW_LINE> for axis in axes: <NEW_LINE> <INDENT> setattr(self.position, axis, None)
Given a set of axes, loses the position of those axes. @param list axes: A list of axes to lose
625941c0d10714528d5ffc48
@typecheck <NEW_LINE> def getValues(name: str, positions: (tuple, list)): <NEW_LINE> <INDENT> if len(positions) == 0: <NEW_LINE> <INDENT> return RetVal(False, '<setValues> received no arguments', None) <NEW_LINE> <DEDENT> ret = getGridDB(name) <NEW_LINE> if not ret.ok: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> db, admin = ret.data <NEW_LINE> gran, vecDim = admin['gran'], admin['vecDim'] <NEW_LINE> del admin, ret <NEW_LINE> strPositions = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for pos in positions: <NEW_LINE> <INDENT> assert isinstance(pos, (tuple, list, np.ndarray)) <NEW_LINE> assert len(pos) == 3 <NEW_LINE> px, py, pz, strPos = _encodePosition(pos, gran) <NEW_LINE> strPositions.append(strPos) <NEW_LINE> <DEDENT> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> return RetVal(False, '<getValues> received invalid positions', None) <NEW_LINE> <DEDENT> values = {_['strPos']: _['val'] for _ in db.find({'strPos': {'$in': strPositions}})} <NEW_LINE> out = np.zeros((len(strPositions), vecDim), np.float64) <NEW_LINE> for idx, pos in enumerate(strPositions): <NEW_LINE> <INDENT> if pos in values: <NEW_LINE> <INDENT> out[idx, :] = np.array(values[pos], np.float64) <NEW_LINE> <DEDENT> <DEDENT> return RetVal(True, None, out)
Return the value at ``positions`` in a tuple of NumPy arrays. :param str name: grid name :param list positions: grid positions (in string format) :return: list of grid values at ``positions``.
625941c08c3a87329515831f
def get_total(self): <NEW_LINE> <INDENT> _return = 0 <NEW_LINE> if (self.get_type() & MpEntry.TYPE_CDS_ITEM == MpEntry.TYPE_CDS_ITEM): <NEW_LINE> <INDENT> _return = Abstract.get_total(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with self: <NEW_LINE> <INDENT> if (self.is_supported("content_list_where_condition")): <NEW_LINE> <INDENT> db_query = self.local.db_instance.rel_mp_upnp_resource_children.join(_DbMpUpnpResource.rel_meta) <NEW_LINE> db_query = self._apply_content_list_where_condition(db_query) <NEW_LINE> _return = db_query.from_self(sql_count(_DbMpUpnpResource.id)).scalar() <NEW_LINE> <DEDENT> else: _return = self.local.db_instance.rel_meta.sub_entries <NEW_LINE> <DEDENT> <DEDENT> return _return
Returns the content resources total. :return: (int) Content resources total :since: v0.2.00
625941c08da39b475bd64ed9
def index_list(self, req): <NEW_LINE> <INDENT> import mapproxy.version <NEW_LINE> html = "<html><body><h1>Welcome to MapProxy %s</h1>" % mapproxy.version.version <NEW_LINE> url = req.script_url <NEW_LINE> if self.list_apps: <NEW_LINE> <INDENT> html += "<h2>available instances:</h2><ul>" <NEW_LINE> html += '\n'.join('<li><a href="%(url)s/%(name)s/">%(name)s</a></li>' % {'url': url, 'name': app} for app in self.loader.available_apps()) <NEW_LINE> html += '</ul>' <NEW_LINE> <DEDENT> html += '</body></html>' <NEW_LINE> return Response(html, content_type='text/html')
Return greeting response with a list of available apps (if enabled with list_apps).
625941c0be383301e01b53f1
def test_attributes_filter_by_product_type_with_unsupported_field(customer_user): <NEW_LINE> <INDENT> qs = Attribute.objects.all() <NEW_LINE> with pytest.raises(NotImplementedError) as exc: <NEW_LINE> <INDENT> filter_attributes_by_product_types(qs, "in_space", "a-value", customer_user) <NEW_LINE> <DEDENT> assert exc.value.args == ("Filtering by in_space is unsupported",)
Ensure using an unknown field to filter attributes by raises a NotImplemented exception.
625941c0498bea3a759b9a18
def write(self, fp): <NEW_LINE> <INDENT> self._get_valid(self._configuration) <NEW_LINE> config_parser = self._dict_to_configparser(self._configuration) <NEW_LINE> config_parser.write(fp)
Persists the config to a file pointer :param fp: The file pointer into which the config should be persisted :type fp: file :raises MultipleInvalid: If the stored configuration is not valid in the embedded schema
625941c0566aa707497f44d4
def hood_compare(self, message, args): <NEW_LINE> <INDENT> hood_a = {'query': args['location_a']} <NEW_LINE> hood_b = {'query': args['location_b']} <NEW_LINE> for hood in (hood_a, hood_b): <NEW_LINE> <INDENT> location = self.attempt_to_get_one_location(message, hood['query']) <NEW_LINE> if location: <NEW_LINE> <INDENT> name, latlng = location <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> hood_response = self.attempt_to_get_neighbourhood(message, latlng, name) <NEW_LINE> if not hood_response: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> hood_api = self.hood({ 'force': hood_response['force'], 'neighbourhood': hood_response['neighbourhood'] }) <NEW_LINE> hood['worst'] = sorted_list_of_crime_types(hood_api) <NEW_LINE> hood['api'] = hood_api <NEW_LINE> hood['name'] = name <NEW_LINE> <DEDENT> strings = [ '\x02%s\x02 vs. \x02%s\x02' % ( hood_a['name'], hood_b['name'] ), 'crime rate \x03#:\x03 \x02%s\x02 (%s) vs. \x02%s\x02 (%s)' % ( hood_a['api']['all-crime']['crime_rate'], hood_a['api']['all-crime']['crime_level'].replace('_', ' '), hood_b['api']['all-crime']['crime_rate'], hood_b['api']['all-crime']['crime_level'].replace('_', ' '), ), 'commonest crime \x03#:\x03 \x02%s\x02 (%s) vs. \x02%s\x02 (%s)' % ( hood_a['worst'][0]['crime_type'], hood_a['worst'][0]['stats']['crime_rate'], hood_b['worst'][0]['crime_type'], hood_b['worst'][0]['stats']['crime_rate'], ), 'rarest crime \x03#:\x03 \x02%s\x02 (%s) vs. \x02%s\x02 (%s)' % ( hood_a['worst'][-1]['crime_type'], hood_a['worst'][-1]['stats']['crime_rate'], hood_b['worst'][-1]['crime_type'], hood_b['worst'][-1]['stats']['crime_rate'], ), ] <NEW_LINE> self.irc.privmsg(message.source, ' \x03#|\x03 '.join(strings))
Compare two neighbourhoods. $<comchar>cr c leicester vs london >Leicester, UK vs. London, UK #| crime rate #: 17.61 (above average) vs. 207.71 (high) #| commonest crime #: anti social behaviour (3.54) vs. other theft (92.56) #| rarest crime #: robbery (0.00) vs. vehicle crime (1.33)
625941c03cc13d1c6d3c72e3
def remove(): <NEW_LINE> <INDENT> common.remove(sales_file)
Remove a record with a given id from the table. Args: table (list): table to remove a record from id_ (str): id of a record to be removed Returns: list: Table without specified record.
625941c094891a1f4081ba10
def read_index(db): <NEW_LINE> <INDENT> if exists(db): <NEW_LINE> <INDENT> with open(db) as f: <NEW_LINE> <INDENT> data = json.load(f) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> data = {} <NEW_LINE> <DEDENT> return data
Read the index and return the data. Returns an empty dictionary if no index exists.
625941c05f7d997b871749fd
def unmapListeningPort(self, listeningPort): <NEW_LINE> <INDENT> def cb(address): <NEW_LINE> <INDENT> return self.unmapAddress(address) <NEW_LINE> <DEDENT> return self.ensureInternalAddress( listeningPort.getHost()).addCallback(cb)
Unmap listening port. @type listeningPort: L{IListeningPort} provider.
625941c0f9cc0f698b140565
def MakeGPTableView(self, catalogPath, pDataType): <NEW_LINE> <INDENT> return super(IGPUtilities3, self).MakeGPTableView(catalogPath, pDataType)
Method IGPUtilities.MakeGPTableView (from IGPUtilities) INPUTS catalogPath : BSTR pDataType : IGPDataType* OUTPUT ppGPTableView : IGPTableView**
625941c08c3a873295158320
def imerge( iterables: Iterable[Iterable[T]], key: Callable[[T], Any] = lambda x: x, ) -> Iterator[T]: <NEW_LINE> <INDENT> if not callable(key): <NEW_LINE> <INDENT> raise TypeError("Key must be callable") <NEW_LINE> <DEDENT> heap: List[Tuple[Any, int, T, Iterator[T]]] = [] <NEW_LINE> for i, iterable in enumerate(iterables): <NEW_LINE> <INDENT> iterator = iter(iterable) <NEW_LINE> try: <NEW_LINE> <INDENT> v = next(iterator) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> k = key(v) <NEW_LINE> heapq.heappush(heap, (k, i, v, iterator)) <NEW_LINE> <DEDENT> while heap: <NEW_LINE> <INDENT> k, i, v, iterator = heapq.heappop(heap) <NEW_LINE> yield v <NEW_LINE> try: <NEW_LINE> <INDENT> v = next(iterator) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> k = key(v) <NEW_LINE> heapq.heappush(heap, (k, i, v, iterator))
Merge individually sorted iterables to a single sorted iterator. This is similar to the merge step in merge-sort except * it handles an arbitrary number of iterators, and * eagerly consumes only one item from each iterator. If the laziness is not needed, it is probably better to concatenate and sort. **Sorted normally** >>> list(imerge([[1, 4], [2, 3]])) [1, 2, 3, 4] **Key changes order (Note that the sorted order of inputs is different)s** >>> list(imerge([[4, 1], [2, 3]], key=lambda x: (x%2, x))) [2, 4, 1, 3]
625941c057b8e32f52483401
def get_action(self, state, possible_actions): <NEW_LINE> <INDENT> raise NotImplementedError()
The Agent receives a GameState and must return an action from one of `possible_actions`.
625941c0b830903b967e9875
def identity_handler(self, callback): <NEW_LINE> <INDENT> self.identity_callback = callback <NEW_LINE> return callback
Registers the callback function that receives identity information after a successful login. If the callback returns a value, it is expected to be a valid return value for a Flask view function such as a redirect. In this case the target page should do whatever it needs to do (like showing an account creation form) and then use :meth:`redirect_success` to redirect to the destination page. See :meth:`login_finished` for a description of the parameters.
625941c0fb3f5b602dac35f9
def create_sequences(tokenizer, smiles, image, max_length): <NEW_LINE> <INDENT> X_images, X_seq, y = [],[],[] <NEW_LINE> vocab_size = len(tokenizer.word_index) + 1 <NEW_LINE> seq = tokenizer.texts_to_sequences([smiles])[0] <NEW_LINE> for i in range(1, len(seq)): <NEW_LINE> <INDENT> in_seq, out_seq = seq[:i], seq[i] <NEW_LINE> in_seq = pad_sequences([in_seq], maxlen= max_length)[0] <NEW_LINE> out_seq = to_categorical([out_seq], num_classes=vocab_size)[0] <NEW_LINE> X_images.append(image) <NEW_LINE> X_seq.append(in_seq) <NEW_LINE> y.append(out_seq) <NEW_LINE> <DEDENT> return [X_images, X_seq, y]
Arguments: ---------- tokenizer: keras tokenizer fitted on the cleaned_smiles smiles: STRING of cleaned smiles image: photo_id? max_length: max_length to allow the model to build seq Returns: -------- list of lists of X_images, X_seq, y
625941c031939e2706e4cdd5
def test_follow_with_no_kwargs(self): <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> zhihu = Zhihu() <NEW_LINE> self.assertRaises(ZhihuError, zhihu.unfollow)
不带关键字参数,抛出异常 :return:
625941c0b545ff76a8913d7e
def get(self, request): <NEW_LINE> <INDENT> value, is_default = self.get_value_and_info( request ) <NEW_LINE> return value
Handles params banded together with AND
625941c00a50d4780f666df8
def test_stack(self): <NEW_LINE> <INDENT> self._test_many(( { 'in': '1 2 3 .s', 'out': '1 2 3\n', }, { 'in': '1 2 dup .s', 'out': '1 2 2\n', }, { 'in': '1 2 drop .s', 'out': '1\n', }, { 'in': '1 2 3 swap .s', 'out': '1 3 2\n', }, { 'in': '1 2 3 over .s', 'out': '1 2 3 2\n', }, { 'in': '1 2 3 rot .s', 'out': '2 3 1\n', }, ))
Test basic stack functions
625941c057b8e32f52483402
def _patch_v6(self, request, scan_id): <NEW_LINE> <INDENT> title = rest_util.parse_string(request, 'title', required=False) <NEW_LINE> description = rest_util.parse_string(request, 'description', required=False) <NEW_LINE> configuration = rest_util.parse_dict(request, 'configuration', required=False) <NEW_LINE> config = None <NEW_LINE> try: <NEW_LINE> <INDENT> if configuration: <NEW_LINE> <INDENT> config = ScanConfigurationV6(configuration, do_validate=True).get_configuration() <NEW_LINE> <DEDENT> <DEDENT> except InvalidScanConfiguration as ex: <NEW_LINE> <INDENT> raise BadParameter('Scan configuration invalid: %s' % unicode(ex)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> Scan.objects.edit_scan(scan_id, title, description, config) <NEW_LINE> <DEDENT> except Scan.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> except InvalidScanConfiguration as ex: <NEW_LINE> <INDENT> logger.exception('Unable to edit Scan process: %s', scan_id) <NEW_LINE> raise BadParameter(unicode(ex)) <NEW_LINE> <DEDENT> return Response(status=status.HTTP_204_NO_CONTENT)
Edits an existing Scan process and returns the updated details :param request: the HTTP GET request :type request: :class:`rest_framework.request.Request` :param scan_id: The ID of the Scan process :type scan_id: int encoded as a str :rtype: :class:`rest_framework.response.Response` :returns: the HTTP response to send back to the user
625941c0c432627299f04bac
def insert(self, word: str) -> None: <NEW_LINE> <INDENT> root = self <NEW_LINE> for c in word: <NEW_LINE> <INDENT> if c not in root.children: <NEW_LINE> <INDENT> root.children[c] = Trie() <NEW_LINE> <DEDENT> root = root.children[c] <NEW_LINE> <DEDENT> root.isWord = True
Inserts a word into the trie.
625941c007f4c71912b113e9
def segmentation_precision(predictions, targets): <NEW_LINE> <INDENT> if not predictions.shape == targets.shape: <NEW_LINE> <INDENT> raise ValueError('Shape of targets {0} does not match shape of predictions {1}'.format( targets.shape, predictions.shape)) <NEW_LINE> <DEDENT> n, _, _, _ = predictions.shape <NEW_LINE> TP = ((targets == 1) * (predictions == 1)).reshape(n, -1).sum(1) <NEW_LINE> FP = ((targets == 0) * (predictions == 1)).reshape(n, -1).sum(1) <NEW_LINE> res = TP / (TP + FP) <NEW_LINE> res = np.nan_to_num(res) <NEW_LINE> return res
[summary] Arguments: predictions {[type]} -- [description] targets {[type]} -- [description] Raises: ValueError -- [description] ValueError -- [description] Returns: [type] -- [description]
625941c071ff763f4b5495ef
def test_empty_array(self): <NEW_LINE> <INDENT> a = [9, 3, 9, 3, 9, 7, 9] <NEW_LINE> self.assertEqual(7, improved_solution(a))
should return None
625941c03eb6a72ae02ec43f
def get_peak_2(heatmap_one): <NEW_LINE> <INDENT> h, w = heatmap_one.shape <NEW_LINE> idx = torch.argsort(heatmap_one.view(-1), descending=True) <NEW_LINE> top1 = (idx[0].item() // h, idx[0].item() % w) <NEW_LINE> top2 = (idx[1].item() // h, idx[1].item() % w) <NEW_LINE> return top1, top2
heatmap_one: 32 * 32
625941c076d4e153a657ea98
def DeletePolicy(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DeletePolicy", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.DeletePolicyResponse() <NEW_LINE> model._deserialize(response["Response"]) <NEW_LINE> return model <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> code = response["Response"]["Error"]["Code"] <NEW_LINE> message = response["Response"]["Error"]["Message"] <NEW_LINE> reqid = response["Response"]["RequestId"] <NEW_LINE> raise TencentCloudSDKException(code, message, reqid) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if isinstance(e, TencentCloudSDKException): <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TencentCloudSDKException(e.message, e.message)
本接口(DeletePolicy)可用于删除策略。 :param request: Request instance for DeletePolicy. :type request: :class:`tencentcloud.cam.v20190116.models.DeletePolicyRequest` :rtype: :class:`tencentcloud.cam.v20190116.models.DeletePolicyResponse`
625941c021bff66bcd6848bd
def test_generate_headers__custom_headers(self): <NEW_LINE> <INDENT> custom_headers = { 'foo': 'bar' } <NEW_LINE> syn = Synapse(skip_checks=True) <NEW_LINE> headers = syn._generate_headers(headers=custom_headers) <NEW_LINE> expected = {} <NEW_LINE> expected.update(custom_headers) <NEW_LINE> expected.update(synapseclient.USER_AGENT) <NEW_LINE> assert expected == headers
Verify that custom headers override default headers
625941c001c39578d7e74da3
def main(*args): <NEW_LINE> <INDENT> options = {'end': date.today() - timedelta(days=1)} <NEW_LINE> local_args = pywikibot.handle_args(args) <NEW_LINE> site = pywikibot.Site() <NEW_LINE> site.login() <NEW_LINE> for arg in local_args: <NEW_LINE> <INDENT> arg, _, value = arg.partition(':') <NEW_LINE> arg = arg[1:] <NEW_LINE> if arg in 'end' 'page' 'start': <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> value = pywikibot.input( 'Please enter a value for {}'.format(arg), default=None ) <NEW_LINE> <DEDENT> options[arg] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> options[arg] = True <NEW_LINE> <DEDENT> <DEDENT> if not validate_options(options, site): <NEW_LINE> <INDENT> pywikibot.error('Invalid options.') <NEW_LINE> return False <NEW_LINE> <DEDENT> output_move_log( page=options['page'], start=datetime.datetime.combine(options['start'], datetime.time.min), end=datetime.datetime.combine(options['end'], datetime.time.max), ) <NEW_LINE> return True
Process command line arguments and invoke bot. @param args: command line arguments @type args: list of unicode
625941c04f88993c3716bfd2
def postorder(self, root): <NEW_LINE> <INDENT> self._levelorder(root) <NEW_LINE> res = [] <NEW_LINE> if self.arr: <NEW_LINE> <INDENT> for lvl in self.arr[::-1]: <NEW_LINE> <INDENT> res += lvl <NEW_LINE> <DEDENT> <DEDENT> return res
:type root: Node :rtype: List[int]
625941c0a8ecb033257d3036
def err_str(err): <NEW_LINE> <INDENT> return "".join(format_exception_only(type(err), err))
Utility function to get a nice str of an Exception for display purposes
625941c0e1aae11d1e749c1d
def load_tensorflow_graph(s): <NEW_LINE> <INDENT> import tensorflow as tf <NEW_LINE> if not isinstance(s, bytes): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s = s.encode() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print("Please supply a file opened in binary mode, open(model, 'rb')") <NEW_LINE> <DEDENT> <DEDENT> dest = tempfile.mkdtemp(suffix="_yhat") <NEW_LINE> s = base64.decodestring(s) <NEW_LINE> f = BytesIO(s) <NEW_LINE> tar = tarfile.open(mode="r:gz", fileobj=f) <NEW_LINE> tar.extractall(path=dest) <NEW_LINE> checkpoint_file = _find_file("session.checkpoint", dest) <NEW_LINE> sess = tf.InteractiveSession() <NEW_LINE> saver = tf.train.Saver() <NEW_LINE> saver.restore(sess, checkpoint_file) <NEW_LINE> return sess, None
load_tensorflow_graph will load a tensorflow session from a base64 encoded string
625941c05fc7496912cc38e6
def get_join_date(self): <NEW_LINE> <INDENT> if self._join_date is None: <NEW_LINE> <INDENT> table = self._html.select('#bio')[0].find_previous_sibling("table") <NEW_LINE> self._join_date = table.select('tr:nth-of-type(3) td span')[0].get_text() <NEW_LINE> <DEDENT> return self._join_date
Returns: Author join date
625941c0e1aae11d1e749c1e
def debug(self, name, component, enable, samplingPercentage): <NEW_LINE> <INDENT> pass
Enable/disable logging the tuples generated in topology via an internal EventLogger bolt. The component name is optional and if null or empty, the debug flag will apply to the entire topology. The 'samplingPercentage' will limit loggging to a percentage of generated tuples. Parameters: - name - component - enable - samplingPercentage
625941c01f5feb6acb0c4abc
def stop(self): <NEW_LINE> <INDENT> self.stop_flag.set()
Stop the server.
625941c0711fe17d825422d8
def GetPlexCollections(mediatype): <NEW_LINE> <INDENT> collections = [] <NEW_LINE> url = "{server}/library/sections" <NEW_LINE> xml = downloadutils.DownloadUtils().downloadUrl(url) <NEW_LINE> try: <NEW_LINE> <INDENT> xml.attrib <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> logMsg(title, 'Could not download PMS sections for %s' % url, -1) <NEW_LINE> return {} <NEW_LINE> <DEDENT> for item in xml: <NEW_LINE> <INDENT> contentType = item['type'] <NEW_LINE> if contentType in mediatype: <NEW_LINE> <INDENT> name = item['title'] <NEW_LINE> contentId = item['key'] <NEW_LINE> uuid = item['uuid'] <NEW_LINE> collections.append({ 'name': name, 'type': contentType, 'id': str(contentId), 'uuid': uuid }) <NEW_LINE> <DEDENT> <DEDENT> return collections
Input: mediatype String or list of strings with possible values 'movie', 'show', 'artist', 'photo' Output: List with an entry of the form: { 'name': xxx Plex title for the media section 'type': xxx Plex type: 'movie', 'show', 'artist', 'photo' 'id': xxx Plex unique key for the section (1, 2, 3...) 'uuid': xxx Other unique Plex key, e.g. 74aec9f2-a312-4723-9436-de2ea43843c1 } Returns an empty list if nothing is found.
625941c0d6c5a10208143fb1
def dict(self): <NEW_LINE> <INDENT> return dict(self.__coeffs)
Return a new copy of the dict of the underlying elements of self. EXAMPLES:: sage: R.<w> = PolynomialRing(Integers(8), sparse=True) sage: f = 5 + w^1997 - w^10000; f 7*w^10000 + w^1997 + 5 sage: d = f.dict(); d {0: 5, 1997: 1, 10000: 7} sage: d[0] = 10 sage: f.dict() {0: 5, 1997: 1, 10000: 7}
625941c0ad47b63b2c509ee8
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ServicePackageQuotaHistoryResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c0ad47b63b2c509ee9
def ws_subscribe(self, channel): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if channel == 1000: <NEW_LINE> <INDENT> nonce = int(time.time()*1000000) <NEW_LINE> self._ws.send(json.dumps({ "command": "subscribe", "channel": 1000, "key": self._API_KEY, "payload": "nonce={}".format(nonce), "sign": self.private_sign_request("nonce={}".format(nonce)) })) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ws.send(json.dumps({"command": "subscribe", "channel": channel})) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print("Failed to subscribe to Poloniex channel ", channel)
Subscibe to a channel The following <channel> values are supported: Channel Type Name 1000 Private Account Notifications (Beta) 1002 Public Ticker Data 1003 Public 24 Hour Exchange Volume 1010 Public Heartbeat <currency pair> Public Price Aggregated Book Debug: ct['Poloniex'].ws_subscribe(1000)
625941c0d268445f265b4dd7
def func(self, n, k): <NEW_LINE> <INDENT> if k == 0: return [[]] <NEW_LINE> if k == 1: return list([i] for i in range(1, n+1)) <NEW_LINE> total = [] <NEW_LINE> for i in range(1, n+1): <NEW_LINE> <INDENT> for pre in self.func(i-1, k-1): <NEW_LINE> <INDENT> total.append(pre+[i]) <NEW_LINE> <DEDENT> <DEDENT> return total
Solution function description
625941c0cc40096d615958ba
def message_for_field(self, field_id): <NEW_LINE> <INDENT> self.wait_for_field(field_id) <NEW_LINE> query = self.q(css='.u-field-{} .u-field-message'.format(field_id)) <NEW_LINE> return query.text[0] if query.present else None
Return the current message in a field.
625941c07d43ff24873a2c07
def lengthOfLongestSubstring(self, s): <NEW_LINE> <INDENT> lookup = defaultdict(int) <NEW_LINE> start = 0 <NEW_LINE> end = 0 <NEW_LINE> max_len = 0 <NEW_LINE> counter = 0 <NEW_LINE> while end < len(s): <NEW_LINE> <INDENT> if lookup[s[end]] > 0: <NEW_LINE> <INDENT> counter += 1 <NEW_LINE> <DEDENT> lookup[s[end]] += 1 <NEW_LINE> end += 1 <NEW_LINE> while counter > 0: <NEW_LINE> <INDENT> if lookup[s[start]] > 1: <NEW_LINE> <INDENT> counter -= 1 <NEW_LINE> <DEDENT> lookup[s[start]] -= 1 <NEW_LINE> start += 1 <NEW_LINE> <DEDENT> max_len = max(max_len, end - start) <NEW_LINE> <DEDENT> return max_len
:type s: str :rtype: int
625941c08e7ae83300e4af35
def parse_get_execute(http_request): <NEW_LINE> <INDENT> version = _get_get_param(http_request, 'version') <NEW_LINE> wpsrequest.check_and_set_version(version) <NEW_LINE> language = _get_get_param(http_request, 'language') <NEW_LINE> wpsrequest.check_and_set_language(language) <NEW_LINE> wpsrequest.identifier = _get_get_param(http_request, 'identifier') <NEW_LINE> wpsrequest.store_execute = _get_get_param( http_request, 'storeExecuteResponse', 'false') <NEW_LINE> wpsrequest.status = _get_get_param(http_request, 'status', 'false') <NEW_LINE> wpsrequest.lineage = _get_get_param( http_request, 'lineage', 'false') <NEW_LINE> wpsrequest.inputs = get_data_from_kvp( _get_get_param(http_request, 'DataInputs'), 'DataInputs') <NEW_LINE> if self.inputs is None: <NEW_LINE> <INDENT> self.inputs = {} <NEW_LINE> <DEDENT> wpsrequest.outputs = {} <NEW_LINE> resp_outputs = get_data_from_kvp( _get_get_param(http_request, 'ResponseDocument')) <NEW_LINE> raw_outputs = get_data_from_kvp( _get_get_param(http_request, 'RawDataOutput')) <NEW_LINE> wpsrequest.raw = False <NEW_LINE> if resp_outputs: <NEW_LINE> <INDENT> wpsrequest.outputs = resp_outputs <NEW_LINE> <DEDENT> elif raw_outputs: <NEW_LINE> <INDENT> wpsrequest.outputs = raw_outputs <NEW_LINE> wpsrequest.raw = True <NEW_LINE> wpsrequest.store_execute = 'false' <NEW_LINE> wpsrequest.status = 'false'
Parse GET Execute request
625941c05f7d997b871749fe
def invalidZipcode(response_code): <NEW_LINE> <INDENT> if response_code == 'InvalidZipcode': <NEW_LINE> <INDENT> print('An invalid zip code was passed') <NEW_LINE> return response_code
Check for InvalidZipcode response
625941c00a50d4780f666df9
@application.route('/connect_foursquare') <NEW_LINE> def connect_foursquare(): <NEW_LINE> <INDENT> foursquare = get_foursquare_service_container() <NEW_LINE> redirect_uri = "http://www.theresameetuphere.com/auth_foursquare" <NEW_LINE> params = {'response_type': 'code', 'redirect_uri': redirect_uri} <NEW_LINE> authorize_url = foursquare.get_authorize_url(**params) <NEW_LINE> return redirect(authorize_url)
Connect the user with foursquare.com.
625941c0283ffb24f3c5586c
@given(bool()) <NEW_LINE> def test_bool_in_range_value_per_default(generated_value): <NEW_LINE> <INDENT> assert generated_value in [False, True]
Verify default value range for bool.
625941c0f548e778e58cd4e5
def getActiveLoans(self): <NEW_LINE> <INDENT> return self.polo.returnActiveLoans()
get my active loans
625941c01b99ca400220aa19
def Plot(self, xmin = None, xmax = None): <NEW_LINE> <INDENT> if not xmin: xmin = self._xmin <NEW_LINE> if not xmax: xmax = self._xmax <NEW_LINE> bins = 100 <NEW_LINE> x = numpy.linspace(xmin, xmax, bins) <NEW_LINE> y = numpy.zeros(bins) <NEW_LINE> for i in xrange(bins): <NEW_LINE> <INDENT> y[i] = self.f(x[i]) <NEW_LINE> <DEDENT> y /= sum(abs(y)) <NEW_LINE> plt.plot(x,y, lw=2, label="y=%s" %self) <NEW_LINE> return (x,y)
Plot will plot the linear function on the interval [xmin, xmax].
625941c056ac1b37e626413c
def delete_many(self, token_ids, raise_if_not_found=True): <NEW_LINE> <INDENT> for token_id in token_ids: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.delete(token_id) <NEW_LINE> log.info("Token %s has been deleted", token_id) <NEW_LINE> <DEDENT> except ClientException as err: <NEW_LINE> <INDENT> if raise_if_not_found: <NEW_LINE> <INDENT> raise err <NEW_LINE> <DEDENT> log.error("%s %s", err, token_id)
Delete few reseller tokens. :param list token_ids: Token id's list :param bool raise_if_not_found: Raise exception if object won't found
625941c02c8b7c6e89b3572b
def run_pythonjs_dart_test_on_node(dummy_filename): <NEW_LINE> <INDENT> return run_if_no_error(run_dart2js_node)
PythonJS (Dart backend - dart2js)
625941c066673b3332b91ffa
def move_to_beam(self, x, y, omega=None): <NEW_LINE> <INDENT> if self.current_phase != "BeamLocation": <NEW_LINE> <INDENT> GenericDiffractometer.move_to_beam(self, x, y, omega) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.getLogger("HWR").debug( "Diffractometer: Move to screen" + " position disabled in BeamLocation phase." )
Creates a new centring point based on all motors positions
625941c007d97122c41787ef
def _get_file_type(self, path): <NEW_LINE> <INDENT> f_postfix = path.split('.')[-1].upper() <NEW_LINE> for k in self._file_types.keys(): <NEW_LINE> <INDENT> if f_postfix in self._file_types[k][0]: <NEW_LINE> <INDENT> return k <NEW_LINE> <DEDENT> <DEDENT> return 'others'
to get the file's type :media ,text, executable, zipped or others :param path: :return:
625941c0adb09d7d5db6c6fa
def set_active_font(self, plot_number, is_active): <NEW_LINE> <INDENT> with QMutexLocker(self.mutex): <NEW_LINE> <INDENT> row, widget = self._get_row_and_widget_from_plot_number(plot_number) <NEW_LINE> font = self.table_widget.item(row, Column.Number).font() <NEW_LINE> font.setBold(is_active) <NEW_LINE> self.table_widget.item(row, Column.Number).setFont(font) <NEW_LINE> self.table_widget.cellWidget(row, Column.Name).line_edit.setFont(font)
Makes the active plot number bold, and makes a previously active bold plot number normal :param plot_number: The unique number in GlobalFigureManager :param is_active: True if plot is the active one or false to make the plot number not bold
625941c0f8510a7c17cf9664
def userProperty(self): <NEW_LINE> <INDENT> return QMetaProperty()
QMetaProperty QMetaObject.userProperty()
625941c0656771135c3eb7d5
def th_c_flatten(x): <NEW_LINE> <INDENT> return x.contiguous().view(x.size(0), -1)
Flatten tensor, leaving channel intact. Assumes CHW format.
625941c094891a1f4081ba11
def loadEncryptionKey(self, key=AES_TEST_VECTOR_KEY): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> return self.sendMyAPDU(cla = 0x00, ins=INS_SET_KEY, p1=0x00, p2=0x00, tx_data=bytearray.fromhex(self.key), recv=0, send_le=0)
Load desired encryption key
625941c0090684286d50ec4c
def _parse_links(self, response, start): <NEW_LINE> <INDENT> links = self.document_date_map[start.date()] <NEW_LINE> for agenda in response.css(".agenda-min-pres .file-link a"): <NEW_LINE> <INDENT> agenda_url = response.urljoin(agenda.xpath("@href").extract_first()) <NEW_LINE> title = agenda.xpath("./text()").extract_first() <NEW_LINE> if title.strip().startswith("Agenda"): <NEW_LINE> <INDENT> title = "Agenda" <NEW_LINE> <DEDENT> links.append( {"title": re.sub(r"\s+", " ", title).strip(), "href": agenda_url} ) <NEW_LINE> <DEDENT> return links
Parse links pulled from documents and the agenda
625941c092d797404e3040f2
def americanOptionMatrix(tree, T, N, r, K, vol, option="call") -> None: <NEW_LINE> <INDENT> dt = T / N <NEW_LINE> u = np.exp(vol * np.sqrt(dt)) <NEW_LINE> d = np.exp(-vol * np.sqrt(dt)) <NEW_LINE> p = (np.exp(r * dt) - d) / (u - d) <NEW_LINE> columns = tree.shape[1] <NEW_LINE> rows = tree.shape[0] <NEW_LINE> try: <NEW_LINE> <INDENT> if option == "call": <NEW_LINE> <INDENT> for c in np.arange(columns): <NEW_LINE> <INDENT> S = tree[rows - 1, c] <NEW_LINE> tree[rows - 1, c] = max(0, S - K) <NEW_LINE> <DEDENT> <DEDENT> elif option == "put": <NEW_LINE> <INDENT> for c in np.arange(columns): <NEW_LINE> <INDENT> S = tree[rows - 1, c] <NEW_LINE> tree[rows - 1, c] = max(0, K - S) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise InputError(option) <NEW_LINE> <DEDENT> <DEDENT> except InputError as e: <NEW_LINE> <INDENT> print(f"{e.expression} is not a valid option. Try call or put.") <NEW_LINE> <DEDENT> for i in np.arange(rows - 1)[::-1]: <NEW_LINE> <INDENT> for j in np.arange(i + 1): <NEW_LINE> <INDENT> down = tree[i + 1, j] <NEW_LINE> up = tree[i + 1, j + 1] <NEW_LINE> S = copy.deepcopy(tree[i, j]) <NEW_LINE> value = np.exp(-r * dt) * (p * up + (1 - p) * down) <NEW_LINE> if option == "call": <NEW_LINE> <INDENT> exercise = S - K <NEW_LINE> <DEDENT> elif option == "put": <NEW_LINE> <INDENT> exercise = K - S <NEW_LINE> <DEDENT> if exercise > value: <NEW_LINE> <INDENT> tree[i, j] = exercise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tree[i, j] = value
Calculates the derivative value with backward induction, starting at the last node for american options :param tree: Binomial tree with N nodes :param T: Timescale. Lower value means higher precision :param N: Number of steps/nodes in the tree :param r: Interest rate :param K: Strike price :param vol: Volatility :return: None
625941c063d6d428bbe44458
def goalie_pull_updater(self, response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> linescore = response.get("liveData").get("linescore") <NEW_LINE> if not linescore: <NEW_LINE> <INDENT> logging.warning("Linescore is empty (???) - try again next time.") <NEW_LINE> return <NEW_LINE> <DEDENT> linescore_home = linescore.get("teams").get("home") <NEW_LINE> linescore_away = linescore.get("teams").get("away") <NEW_LINE> last_tracked_event = self.events[-1] <NEW_LINE> event_filter_list = (models.gameevent.GoalEvent, models.gameevent.PenaltyEvent) <NEW_LINE> home_goalie_current = linescore_home.get("goaliePulled") <NEW_LINE> away_goalie_current = linescore_away.get("goaliePulled") <NEW_LINE> if not self.home_team.goalie_pulled: <NEW_LINE> <INDENT> logging.debug("Home goalie in net - check & update goalie attribute.") <NEW_LINE> home_goalie_pulled = self.home_team.goalie_pulled_setter(home_goalie_current) <NEW_LINE> <DEDENT> elif self.home_team.goalie_pulled and isinstance(last_tracked_event, event_filter_list): <NEW_LINE> <INDENT> logging.info( "Home goalie previously pulled, but important event detected (%s) - update & check.", last_tracked_event, ) <NEW_LINE> home_goalie_pulled = self.home_team.goalie_pulled_setter(home_goalie_current) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.info( "Home goalie is pulled and either no event or a non-important event happened - do nothing." ) <NEW_LINE> return <NEW_LINE> <DEDENT> if not self.away_team.goalie_pulled: <NEW_LINE> <INDENT> logging.debug("Home goalie in net - check & update goalie attribute.") <NEW_LINE> away_goalie_pulled = self.away_team.goalie_pulled_setter(away_goalie_current) <NEW_LINE> <DEDENT> elif self.away_team.goalie_pulled and isinstance(last_tracked_event, event_filter_list): <NEW_LINE> <INDENT> logging.info("Away goalie previously pulled, but important event detected - update & check.") <NEW_LINE> away_goalie_pulled = self.home_team.goalie_pulled_setter(away_goalie_current) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.info( "Away goalie is pulled and either no event or a non-important event happened - do nothing." ) <NEW_LINE> return <NEW_LINE> <DEDENT> if home_goalie_pulled: <NEW_LINE> <INDENT> trailing_score = self.away_team.score - self.home_team.score <NEW_LINE> self.goalie_pull_social(self.home_team.short_name, trailing_score) <NEW_LINE> <DEDENT> elif away_goalie_pulled: <NEW_LINE> <INDENT> trailing_score = self.home_team.score - self.away_team.score <NEW_LINE> self.goalie_pull_social(self.away_team.short_name, trailing_score) <NEW_LINE> <DEDENT> <DEDENT> except IndexError as e: <NEW_LINE> <INDENT> logging.warning( "Tried to update goalie pulled status, but got an error - try again next loop. %s", e, )
Use the livefeed to determine if the goalie of either team has been pulled. And keep the attribute updated in each team object.
625941c0bde94217f3682d5c
@main.route('/briefs/<int:brief_id>/award/<int:brief_response_id>/contract-details', methods=['POST']) <NEW_LINE> def award_brief_details(brief_id, brief_response_id): <NEW_LINE> <INDENT> json_payload = get_json_from_request() <NEW_LINE> json_has_required_keys(json_payload, ['awardDetails']) <NEW_LINE> updater_json = validate_and_return_updater_request() <NEW_LINE> brief = Brief.query.filter( Brief.id == brief_id ).first_or_404() <NEW_LINE> brief_response = BriefResponse.query.filter( BriefResponse.brief_id == brief_id, BriefResponse.id == brief_response_id ).first_or_404() <NEW_LINE> if brief_response.status not in ('pending-awarded', 'awarded'): <NEW_LINE> <INDENT> abort(400, "Cannot update award details for a Brief without a winning supplier") <NEW_LINE> <DEDENT> award_details = purge_nulls_from_data(json_payload['awardDetails']) <NEW_LINE> errors = get_validation_errors( 'brief-awards-{}-{}'.format(brief.framework.slug, brief.lot.slug), award_details ) <NEW_LINE> if errors: <NEW_LINE> <INDENT> abort(400, errors) <NEW_LINE> <DEDENT> brief_response.award_details = award_details <NEW_LINE> if brief_response.status == 'pending-awarded': <NEW_LINE> <INDENT> brief_response.awarded_at = datetime.utcnow() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current_app.logger.info( "Updating previously awarded Brief so awarded_at is not reset. See audit event for details." ) <NEW_LINE> <DEDENT> audit_event = AuditEvent( audit_type=AuditTypes.update_brief_response, user=updater_json['updated_by'], data={ 'briefId': brief.id, 'briefResponseId': brief_response_id, 'briefResponseAwardDetails': award_details }, db_object=brief_response ) <NEW_LINE> db.session.add_all([brief_response, audit_event]) <NEW_LINE> db.session.commit() <NEW_LINE> index_brief(brief) <NEW_LINE> return single_result_response(RESOURCE_NAME, brief), 200
Status changes: Brief: closed -> awarded Brief response: pending-awarded -> awarded
625941c045492302aab5e22a
def test_formatting_exception_without_methods(self): <NEW_LINE> <INDENT> log_records = [ logging.LogRecord(name='error1', level=logging.WARNING, pathname=__file__, lineno=0, msg=Exception('Something happened'), args=None, exc_info=None), logging.LogRecord(name='error2', level=logging.ERROR, pathname=__file__, lineno=0, msg=Exception('Something else happened'), args=None, exc_info=None), ] <NEW_LINE> payloads = [ self.formatter.format(record) for record in log_records ] <NEW_LINE> self.assertEqual(len(payloads), len(log_records)) <NEW_LINE> self.assertEqual(len(payloads[0]['attachments']), 1) <NEW_LINE> self.assertIn('header', payloads[0]) <NEW_LINE> self.assertEqual(payloads[0]['header'], 'Something happened') <NEW_LINE> self.assertEqual(payloads[0]['footer'], 'Some footer') <NEW_LINE> self.assertEqual(payloads[1]['footer'], 'Some footer') <NEW_LINE> self.assertEqual(payloads[0]['footer_url'], 'https://cataas.com/cat') <NEW_LINE> self.assertEqual(payloads[1]['footer_url'], 'https://cataas.com/cat') <NEW_LINE> self.assertEqual(payloads[0]['attachments'][0]['text'], 'Something happened') <NEW_LINE> self.assertEqual(payloads[0]['attachments'][0]['color'], '#D5A021') <NEW_LINE> self.assertEqual(payloads[1]['attachments'][0]['text'], 'Something else happened') <NEW_LINE> self.assertEqual(payloads[1]['attachments'][0]['color'], '#EE6352')
Test that a payload is created out of a normal exception
625941c023849d37ff7b2ff9
def remove_insect(self, insect): <NEW_LINE> <INDENT> if insect.true_queen: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if insect.is_ant: <NEW_LINE> <INDENT> if self.ant is insect: <NEW_LINE> <INDENT> if hasattr(self.ant, 'container') and self.ant.container: <NEW_LINE> <INDENT> self.ant = self.ant.ant <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ant = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if hasattr(self.ant, 'container') and self.ant.container and self.ant.ant is insect: <NEW_LINE> <INDENT> self.ant.ant = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert False, '{0} is not in {1}'.format(insect, self) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.bees.remove(insect) <NEW_LINE> <DEDENT> insect.place = None
Remove an INSECT from this Place. A target Ant may either be directly in the Place, or be contained by a container Ant at this place. The true QueenAnt may not be removed. If remove_insect tries to remove an Ant that is not anywhere in this Place, an AssertionError is raised. A Bee is just removed from the list of Bees.
625941c0ab23a570cc2500ea
def __repr__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return "{0}:{1}{2}{3}={4}".format( self.id, self.callable.__name__, self.args, self.kargs, self.resultValue, ) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return "{0}:{1}{2}{3}={4}".format( self.id, "partial", self.args, self.kargs, self.resultValue, )
Convert future to string.
625941c0097d151d1a222dc4
def liststr(glyphs): <NEW_LINE> <INDENT> return "[%s]" % " ".join(glyphs)
Return string representation of a list of glyph names.
625941c0b5575c28eb68df68
def runTest(self): <NEW_LINE> <INDENT> schema_info = parent_node_dict["schema"][-1] <NEW_LINE> server_id = schema_info["server_id"] <NEW_LINE> db_id = schema_info["db_id"] <NEW_LINE> func_name = "test_event_get_%s" % str(uuid.uuid4())[1:6] <NEW_LINE> db_user = self.server["username"] <NEW_LINE> server_con = server_utils.connect_server(self, server_id) <NEW_LINE> if not server_con["info"] == "Server connected.": <NEW_LINE> <INDENT> raise Exception("Could not connect to server to add resource " "groups.") <NEW_LINE> <DEDENT> server_version = 0 <NEW_LINE> if "type" in server_con["data"]: <NEW_LINE> <INDENT> if server_con["data"]["version"] < 90300: <NEW_LINE> <INDENT> server_version = server_con["data"]["version"] <NEW_LINE> <DEDENT> <DEDENT> self.function_info = trigger_funcs_utils.create_trigger_function( self.server, self.db_name, self.schema_name, func_name, server_version) <NEW_LINE> db_con = database_utils.connect_database(self, utils.SERVER_GROUP, server_id, db_id) <NEW_LINE> if not db_con['data']["connected"]: <NEW_LINE> <INDENT> raise Exception("Could not connect to database to add collation.") <NEW_LINE> <DEDENT> schema_response = schema_utils.verify_schemas(self.server, self.db_name, self.schema_name) <NEW_LINE> if not schema_response: <NEW_LINE> <INDENT> raise Exception("Could not find the schema to add the collation.") <NEW_LINE> <DEDENT> trigger_func_id = self.function_info[0] <NEW_LINE> response = self.tester.get( self.url + str(utils.SERVER_GROUP) + '/' + str(server_id) + '/' + str(db_id) + '/' + str(self.schema_id) + '/' + str(trigger_func_id), content_type='html/json') <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> database_utils.disconnect_database(self, server_id, db_id)
This function will delete trigger function under database node.
625941c076d4e153a657ea99
def change_ring(self, base_ring): <NEW_LINE> <INDENT> generators, filtration = self.presentation() <NEW_LINE> return FilteredVectorSpace(generators, filtration, base_ring=base_ring)
Return the same filtration over a different base ring. INPUT: - ``base_ring`` -- a ring. The new base ring. OUTPUT: This method returns a new filtered vector space whose subspaces are defined by the same generators but over a different base ring. EXAMPLES:: sage: V = FilteredVectorSpace(1, 0); V QQ^1 >= 0 sage: V.change_ring(RDF) RDF^1 >= 0
625941c04f6381625f1149a6
def _exec_cmdv(self, cmdv, procCtrl, stdinFile): <NEW_LINE> <INDENT> if util.get_val(procCtrl, 'nohup'): <NEW_LINE> <INDENT> cmdv[:0] = ['nohup'] <NEW_LINE> <DEDENT> output = tempfile.TemporaryFile() <NEW_LINE> stdin = output <NEW_LINE> if (stdinFile != None): <NEW_LINE> <INDENT> stdin = self.open(stdinFile) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if util.get_val(procCtrl, 'waitForCompletion'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subprocess.check_call(cmdv, stdin=stdin, stdout=output, stderr=output) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError as cpe: <NEW_LINE> <INDENT> if cpe.returncode != util.get_val(procCtrl, 'noRaise', 0): <NEW_LINE> <INDENT> output.seek(0) <NEW_LINE> _logger.error('output='+output.read()) <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> output.seek(0) <NEW_LINE> return output.read() <NEW_LINE> <DEDENT> proc = subprocess.Popen(cmdv, stdin=stdin, stderr=output) <NEW_LINE> if proc.poll() == None and procCtrl.has_key('daemonWait'): <NEW_LINE> <INDENT> _logger.debug('Popen waits {0} sec for {1}'.format(procCtrl['daemonWait'], ' '.join(cmdv))) <NEW_LINE> time.sleep(procCtrl['daemonWait']) <NEW_LINE> <DEDENT> if proc.poll() != None: <NEW_LINE> <INDENT> output.seek(0) <NEW_LINE> raise ExecException(' '.join(cmdv), proc.returncode, output) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> if (stdin != output): <NEW_LINE> <INDENT> stdin.close() <NEW_LINE> <DEDENT> output.close()
Execute an OS command on the local host, using subprocess module. cmdv - complete command vector (argv) of the OS command procCtrl - procCtrl object from message which controls how the process is started (blocking vs non-blocking and output reporting)
625941c0796e427e537b052d
def create_or_update_user(db, username, email, groups): <NEW_LINE> <INDENT> user = db.query(User).filter_by(name=username).first() <NEW_LINE> if not user: <NEW_LINE> <INDENT> user = User(name=username, email=email) <NEW_LINE> db.add(user) <NEW_LINE> db.flush() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if user.email != email: <NEW_LINE> <INDENT> user.email = email <NEW_LINE> db.flush() <NEW_LINE> <DEDENT> <DEDENT> for group_name in groups: <NEW_LINE> <INDENT> if not group_name.strip(): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> group = db.query(Group).filter_by(name=group_name).first() <NEW_LINE> if not group: <NEW_LINE> <INDENT> group = Group(name=group_name) <NEW_LINE> db.add(group) <NEW_LINE> db.flush() <NEW_LINE> <DEDENT> if group not in user.groups: <NEW_LINE> <INDENT> log.info('Adding %s to %s group', user.name, group.name) <NEW_LINE> user.groups.append(group) <NEW_LINE> <DEDENT> <DEDENT> for group in user.groups: <NEW_LINE> <INDENT> if group.name not in groups: <NEW_LINE> <INDENT> log.info('Removing %s from %s group', user.name, group.name) <NEW_LINE> user.groups.remove(group) <NEW_LINE> <DEDENT> <DEDENT> return user
Create or update a user in the database. Args: db (sqlalchemy.orm.session.Session): The database session. username (str): The username to create or update email (str): The user's email address groups (list(str)): A list of group names the user belongs to, that will be synced. Returns: bodhi.server.models.User: The user instance.
625941c0b7558d58953c4e82