code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def fit_new(self, train_x, train_y, test_x, test_y): <NEW_LINE> <INDENT> p_keep_conv = tf.placeholder("float") <NEW_LINE> p_keep_hidden = tf.placeholder("float") <NEW_LINE> X = tf.placeholder("float", [None, 48, 48, 1]) <NEW_LINE> Y = tf.placeholder("float", [None, 10]) <NEW_LINE> out, _ = self._cnn_new(X, p_keep_conv,... | :return: | 625941df21a7993f00bc8061 |
@receiver(pre_delete, sender=MibUpload) <NEW_LINE> def mib_upload_pre_delete(sender, instance=None, **kwargs): <NEW_LINE> <INDENT> if instance: <NEW_LINE> <INDENT> dispatcher.dispatch_job('mib_disintegration', '%s' % instance.pk) | Removes the data objects this mib added to the system | 625941df26238365f5f0f1de |
def straight(ranks): <NEW_LINE> <INDENT> return((max(ranks) - min(ranks) == 4) and (len(set(ranks)) == 5)) | Return True if the ordered ranks from a 5-card straight. | 625941df21bff66bcd684cbb |
def unify(self, quality, confs): <NEW_LINE> <INDENT> confs = [conf for conf in confs if conf] <NEW_LINE> if len(confs) > 0: <NEW_LINE> <INDENT> conf = reduce(Confidence.get_unifier(self.priority), confs) <NEW_LINE> conf = Confidence(conf.applic, conf.valid) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> conf = Confidenc... | Turns the set of confs in the rhses into a single conf for the whole rule.
quality - The quality of this rule
confs - The lists of confidences that we want to compress
Returns : A compressed confidence | 625941df96565a6dacc8fa36 |
def to_list_of_dicts(self) -> List[Dict[str, Any]]: <NEW_LINE> <INDENT> return [this.to_dict() for this in self._elements] | Get the elements in a serialized format that can be stored in MongoDB.
:return: List of dicts | 625941df656771135c3ebbde |
def __init__(self, cfg_i18n, log = None): <NEW_LINE> <INDENT> self.cfg_i18n = cfg_i18n <NEW_LINE> self.log = log | constructor
@param cfg_i18n : a dictionnary of i18n data
{ 'LANG' : ...,
'ERROR_MSG' : ...,
'ERROR_MSG_NONE' : ...,
'ERROR_MSG_NOT_CONFIGURED' : ...,
'ERROR_MSG_CONFIG' : ... } | 625941df82261d6c526ab810 |
def wrap_in_a_tuple(*g): <NEW_LINE> <INDENT> print("wrapped") <NEW_LINE> print(type(g)) <NEW_LINE> print(g) | fan in | 625941df3c8af77a43ae3b0f |
@requires_role(['ADMN', 'FACA']) <NEW_LINE> def salary_summary(request, userid): <NEW_LINE> <INDENT> person, member_units = _get_faculty_or_404(request.units, userid) <NEW_LINE> if request.GET: <NEW_LINE> <INDENT> form = GetSalaryForm(request.GET) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> date = request.GET.ge... | Shows all salary career events at a date | 625941df5fc7496912cc3cea |
def _get_all_words_from_each_resource(self, training): <NEW_LINE> <INDENT> all_words_from_a_resource = {'undefined': []} <NEW_LINE> for task in training: <NEW_LINE> <INDENT> cleaned_label = self._clean_label(task.label) <NEW_LINE> application_name = task.application_type.name if task.application_type else 'undefined' <... | Returns:
dict: for each resource type, the words that are part of the resource type tasks | 625941df24f1403a92600ecf |
def setFscaling(self, x): <NEW_LINE> <INDENT> pyoArgsAssert(self, "b", x) <NEW_LINE> self._fscaling = x <NEW_LINE> x, lmax = convertArgsToLists(x) <NEW_LINE> [obj.setFscaling(wrap(x,i)) for i, obj in enumerate(self._base_objs)] <NEW_LINE> if self.viewFrame != None: <NEW_LINE> <INDENT> self.viewFrame.setFscaling(self._f... | Sets the frequency display to linear or logarithmic.
:Args:
x : boolean
If True, the frequency display is logarithmic. False turns
it back to linear. Defaults to False. | 625941df97e22403b379d307 |
def predict(self, X_predict): <NEW_LINE> <INDENT> assert self.interception_ is not None and self.coef_ is not None, "must fit before predict!" <NEW_LINE> assert X_predict.shape[1] == len(self.coef_), "the feature number of X_predict must be equal to X_train" <NEW_LINE> probability = self.predict_probability(X_predict) ... | 给定带预测数据集 X_predict,返回表示 X_predict 的结果向量
:param X_predict:
:return: | 625941df4527f215b584c7bf |
def add_component(self, component): <NEW_LINE> <INDENT> self.add_child(component) | adds a new component to the command.
Args:
component: The component object which should be added.
Returns:
Nothing is returned
.. note::
This method does not check if the added object is a compatible
component. | 625941df5510c4643540f748 |
def resource_apply_gradient_descent(var, alpha, delta, use_locking=False, name=None): <NEW_LINE> <INDENT> _ctx = _context._context <NEW_LINE> if _ctx is None or not _ctx._eager_context.is_eager: <NEW_LINE> <INDENT> if use_locking is None: <NEW_LINE> <INDENT> use_locking = False <NEW_LINE> <DEDENT> use_locking = _execut... | Update '*var' by subtracting 'alpha' * 'delta' from it.
Args:
var: A `Tensor` of type `resource`. Should be from a Variable().
alpha: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `co... | 625941df8e71fb1e9831db14 |
def get_events(self, stream_id=None, start=0): <NEW_LINE> <INDENT> indices = [] <NEW_LINE> if not stream_id: <NEW_LINE> <INDENT> indices = range(len(self.events)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> indices = self.streams.get(stream_id) or [] <NEW_LINE> <DEDENT> for index in indices[start:]: <NEW_LINE> <INDEN... | Return a generator of events from the optionally supplied stream
Keyword Arguments:
stream_id -- Stream id, if None return all events
start -- Integer, optionally specify a starting position | 625941df627d3e7fe0d691bd |
def get_bedcov_dict(bedcoverage): <NEW_LINE> <INDENT> out_dict = {} <NEW_LINE> if os.path.isfile(bedcoverage): <NEW_LINE> <INDENT> fh = open(bedcoverage) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bedcoverage = bedcoverage.decode('utf-8') <NEW_LINE> fh = bedcoverage.split('\n')[:-1] <NEW_LINE> <DEDENT> for line in f... | Uses the BEDTools genomeCoverageBed histogram output to determine mean
coverage and percentage covered for each contig.
Returns dict with fasta id as key and percentage covered and cov_mean as
keys for the inner dictionary. | 625941df4f88993c3716c3d0 |
def move(self, S, a): <NEW_LINE> <INDENT> if type(S) == str: <NEW_LINE> <INDENT> S = {S} <NEW_LINE> <DEDENT> S_move = set() <NEW_LINE> for s in S: <NEW_LINE> <INDENT> S_move |= self.table[s][a] <NEW_LINE> <DEDENT> return S_move | Performs a transition move.
From the initial state set S, given an input char symbol A, calculates
the destination set that we can go to. For DFA, input can be a single
state string.
Args:
S - set or str, states to start from
a - str , a char symbol in alphabet
Returns:
S_move - set, set of states ... | 625941df23849d37ff7b33f9 |
def check_chi2(): <NEW_LINE> <INDENT> import sherpa.astro.ui as sau <NEW_LINE> chi2 = sau.get_fit_results().statval <NEW_LINE> print('chi2 from fit: {0}'.format(chi2)) <NEW_LINE> data = sau.get_dep() <NEW_LINE> model = sau.get_model_plot().y <NEW_LINE> error = np.where(model > data, sau.get_syserror(), sau.get_staterro... | Execute this function after fitting to see if the
best-fit chi2 reported matches the formula coded here | 625941df6fb2d068a760f40e |
def testMultiplyImage(self): <NEW_LINE> <INDENT> _, coefficients = self.cases[-2] <NEW_LINE> field = lsst.afw.math.ChebyshevBoundedField(self.image.getBBox(), coefficients) <NEW_LINE> expect = multiply(self.image, field) <NEW_LINE> field.multiplyImage(self.image) <NEW_LINE> self.assertImagesAlmostEqual(self.image, expe... | Test Multiplying in place an image.
| 625941df50485f2cf553d107 |
def batch_process_directory(pin, full_key=True): <NEW_LINE> <INDENT> global_annotations = {} <NEW_LINE> d_list = [os.path.join(pin, os.path.join(d, 'saved')) for d in os.listdir(pin) if not '.' in d] <NEW_LINE> for d in d_list: <NEW_LINE> <INDENT> f_list = [os.path.join(d,f) for f in os.listdir(d) if f.endswith('knowta... | Get all annotations from the corpus and store a mapping of file names to
annotations. | 625941df187af65679ca548c |
def event_click_right(self, event, *args): <NEW_LINE> <INDENT> self.field.flag(event.x, event.y) | Manage the right-click event | 625941df1f037a2d8b946569 |
def halGetChromSizes(halfile, genome): <NEW_LINE> <INDENT> return dict(line.rstrip().split("\t") for line in halStats(["--chromSizes", genome, halfile])) | return dict of chromosomes sizes | 625941df15fb5d323cde0e80 |
def run(self, servable_id, data): <NEW_LINE> <INDENT> servable_path = '{service}/servables/{servable_id}/run'.format(service=self.service, servable_id=servable_id) <NEW_LINE> r = requests.post(servable_path, json=data) <NEW_LINE> if r.status_code is not 200: <NEW_LINE> <INDENT> raise Exception(r) <NEW_LINE> <DEDENT> re... | Invoke a DLHub servable
Args:
servable_id (string): UUID of the servable
data (dict): Dictionary of the data to send to the servable
Returns:
(pd.DataFrame): Reply from the service | 625941df9f2886367277abf7 |
def SetInput1(self, *args): <NEW_LINE> <INDENT> return _itkLabelStatisticsOpeningImageFilterPython.itkLabelStatisticsOpeningImageFilterIUL3ID3_SetInput1(self, *args) | SetInput1(self, itkImageUL3 input) | 625941dfc4546d3d9de72da3 |
def test_unknown_boto3_errors_cause_no_processing(self): <NEW_LINE> <INDENT> self.stubber.add_client_error( 'describe_security_groups', service_error_code='FooBar.Error' ) <NEW_LINE> with self.stubber: <NEW_LINE> <INDENT> result = main.get_or_create_secgroups( [f'vpc-{self.managed_id}'], self.default_managed_group_name... | We should return an empty list if there's an unknown error
from boto3 / AWS API | 625941df956e5f7376d711d8 |
def update_index_gdocs(self, config): <NEW_LINE> <INDENT> indexed_ids = set() <NEW_LINE> p = QueryParser("kind", schema=self.ix.schema) <NEW_LINE> q = p.parse("gdoc") <NEW_LINE> with self.ix.searcher() as s: <NEW_LINE> <INDENT> results = s.search(q,limit=None) <NEW_LINE> for result in results: <NEW_LINE> <INDENT> index... | Update the search index using a collection of
Google Drive documents and files.
Uses the 'id' field to uniquely identify documents.
Also see:
https://developers.google.com/drive/api/v3/reference/files | 625941dfd53ae8145f87a5d6 |
def __init__(self, game): <NEW_LINE> <INDENT> self.game = game <NEW_LINE> self.game.update_win_status() | Initialize a new Reporter.
Positional Arguments:
game -- An instance of a libmorris.game.Game class | 625941df5166f23b2e1a54c5 |
def _validate_source_data(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> jsonschema.validate(self._buffer, self._schema) <NEW_LINE> <DEDENT> except jsonschema.ValidationError as e: <NEW_LINE> <INDENT> raise ValidationError(e) | :raises ValidationError: | 625941dfbe7bc26dc91cd966 |
def entries_curate(): <NEW_LINE> <INDENT> binding = {} <NEW_LINE> url = 'https://api.twitter.com/1.1/collections/entries/curate.json' <NEW_LINE> return _TwitterRequest('POST', url, 'rest:collections', 'post-collections-entries-curate', binding) | Curate a Collection by adding or removing Tweets in bulk. Updates must be
limited to 100 cumulative additions or removals per request. | 625941df2c8b7c6e89b35b2b |
def determine_db_dir(): <NEW_LINE> <INDENT> if platform.system() == "Darwin": <NEW_LINE> <INDENT> return os.path.expanduser("~/Library/Application Support/Orion/") <NEW_LINE> <DEDENT> elif platform.system() == "Windows": <NEW_LINE> <INDENT> return os.path.join(os.environ['APPDATA'], "Orion") <NEW_LINE> <DEDENT> return ... | Return the default location of the orion data directory | 625941df7b180e01f3dc4b63 |
def show_term(term): <NEW_LINE> <INDENT> if term[0] == '-': <NEW_LINE> <INDENT> positive_term = ('+', term[1]) <NEW_LINE> str = show_term(positive_term) <NEW_LINE> return '-' + str <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ".".join([ show_factor(factor) for factor in term[1]]) | Convert a term back into a string.
>>> show_term(parse_term('c1ds[p1m].a1ds[k1]'))
'c1ds[p1m].a1ds[k1]'
>>> show_term(parse_term('-h[b].h[c]'))
'-h[b].h[c]' | 625941df6e29344779a6297c |
def describe_task_definition(taskDefinition=None): <NEW_LINE> <INDENT> pass | Describes a task definition. You can specify a family and revision to find information about a specific task definition, or you can simply specify the family to find the latest ACTIVE revision in that family.
See also: AWS API Documentation
Examples
This example provides a description of the specified task definition.... | 625941df7d43ff24873a300f |
def test_give_chown(self): <NEW_LINE> <INDENT> print("\nIn test_give_chown()...") <NEW_LINE> assert type(PartialRecovery().give_chown("")) == bool | Checking return value type | 625941df31939e2706e4d1d2 |
def set_SecretKey(self, value): <NEW_LINE> <INDENT> super(CreatePhotoPostWithURLInputSet, self)._set_input('SecretKey', value) | Set the value of the SecretKey input for this Choreo. ((required, string) The Secret Key provided by Tumblr (AKA the OAuth Consumer Secret).) | 625941dff7d966606f6aa375 |
def result_set_to_html_table(self, cursor, header = True, headings = None): <NEW_LINE> <INDENT> row = cursor.fetchone() <NEW_LINE> html = '<table>' <NEW_LINE> if header: <NEW_LINE> <INDENT> html += '<tr>' <NEW_LINE> for i in xrange(len(row)): <NEW_LINE> <INDENT> if headings is None or i>=len(headings): <NEW_LINE> <INDE... | Returns an HTML table filled in with data from a result set. | 625941df4428ac0f6e5bab61 |
def get_hr_value(database): <NEW_LINE> <INDENT> hr_req_val = database.child("hr").get().val() <NEW_LINE> if hr_req_val: <NEW_LINE> <INDENT> return convert_val_to_color(hr_req_val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return convert_val_to_color(DEFAULT_HR) | pulls hr values from somewhere
:return: hex color | 625941df046cf37aa974d0b1 |
def write_tables(fname, table_names=None, prefix=None, compress=False, local=False): <NEW_LINE> <INDENT> if table_names is None: <NEW_LINE> <INDENT> table_names = list_tables() <NEW_LINE> <DEDENT> tables = (get_table(t) for t in table_names) <NEW_LINE> key_template = '{}/{{}}'.format(prefix) if prefix is not None else ... | Writes tables to a pandas.HDFStore file.
Parameters
----------
fname : str
File name for HDFStore. Will be opened in append mode and closed
at the end of this function.
table_names: list of str, optional, default None
List of tables to write. If None, all registered tables will
be written.
prefix: str
... | 625941dfa4f1c619b28b039e |
def run_graph(wav_data, labels, input_layer_name, output_layer_name, num_top_predictions): <NEW_LINE> <INDENT> with tf.Session() as sess: <NEW_LINE> <INDENT> softmax_tensor = sess.graph.get_tensor_by_name(output_layer_name) <NEW_LINE> predictions, = sess.run(softmax_tensor, {input_layer_name: wav_data}) <NEW_LINE> top_... | Runs the audio data through the graph and prints predictions. | 625941df596a897236089e29 |
def preprocess(self, ent): <NEW_LINE> <INDENT> return ent | Preprocesses the given dict-like object into another dict-like object.
The default implementation does not alter the object. Users can override
this method to perform custom process. You can yield None to skip the
record. | 625941df94891a1f4081be17 |
def makeArrays(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return (self.df.drop('AnimalID', axis=1).values, self.df['AnimalID'].values) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> print('Warning: the data frame has not been initialized yet, returning empty arrays') <NEW_LINE> return ([], []) | return a tuple of arrays: the data and the ids | 625941df0c0af96317bb8554 |
def crop(self, data): <NEW_LINE> <INDENT> duration = self.data_duration(data) <NEW_LINE> data_out = dict() <NEW_LINE> for key in data: <NEW_LINE> <INDENT> idx = [slice(None)] * data[key].ndim <NEW_LINE> for tdim in self._time.get(key, []): <NEW_LINE> <INDENT> idx[tdim] = slice(duration) <NEW_LINE> <DEDENT> data_out[key... | Crop a data dictionary down to its common time
Parameters
----------
data : dict
As produced by pumpp.transform
Returns
-------
data_cropped : dict
Like `data` but with all time-like axes truncated to the
minimum common duration | 625941df442bda511e8be780 |
def opt_quitter(self, argument): <NEW_LINE> <INDENT> self.fermer() <NEW_LINE> self.pere.envoyer("Fermeture de l'éditeur.") | Option quitter. | 625941df460517430c3944e9 |
def get_results(filename, keyname=None, delimiter=';', quotechar='"'): <NEW_LINE> <INDENT> results = {} <NEW_LINE> with open(filename) as fp: <NEW_LINE> <INDENT> if keyname: <NEW_LINE> <INDENT> func = csv.DictReader <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func = csv.reader <NEW_LINE> <DEDENT> reader = func(fp, de... | Read results from a CSV file and return as dictionary. If `keyname`
is not None, the file is expected to contain column names in the first
row, the records are returned as dictionaries and the indicated
column `keyname` is used as an unique key. Otherwise, the first column
is used as an unique key, and the remaining fi... | 625941df3539df3088e2e6b7 |
def __init__(self, n_samples, v=0.0): <NEW_LINE> <INDENT> self.n_samples = n_samples <NEW_LINE> self.c = [v] * n_samples | Default constructor for CoefficientSpectrum. | 625941df63f4b57ef000147c |
def simulate_bayer(image_rgb, cfa_pattern): <NEW_LINE> <INDENT> image_bayer = np.zeros_like(image_rgb) <NEW_LINE> cfa_pattern = cfa_pattern.upper() <NEW_LINE> if image_rgb.ndim == 3: <NEW_LINE> <INDENT> if cfa_pattern.upper() == 'GBRG': <NEW_LINE> <INDENT> image_bayer[1::2, 0::2, 0] = image_rgb[1::2, 0::2, 0] <NEW_LINE... | Simulate a Bayer image from full RGB image.
:param image_rgb: 3-D numpy array (h, w, 3:rgb) or 4-D image batch
:param cfa_pattern: 'GBRG', 'RGGB' or 'BGGR' | 625941df94891a1f4081be18 |
def confirmbox(msg): <NEW_LINE> <INDENT> form = ConfirmForm(msg) <NEW_LINE> form.show() <NEW_LINE> form.destroy() <NEW_LINE> return form.isconfirm | 显示带有【是】、【否】按钮的提示框,msg为要显示的消息,返回值为true或者false | 625941df8a349b6b435e84e0 |
def gen_lambda_batch(filename: str, noise=None, lmbda=None): <NEW_LINE> <INDENT> wb = Workbook() <NEW_LINE> headers = ["n_samples"] <NEW_LINE> sheet = wb.create_sheet(title="Double Descent") <NEW_LINE> samples = [] <NEW_LINE> errors = {} <NEW_LINE> beta = gen_beta(dimensions=opts["dimensions"]) <NEW_LINE> if(lmbda is N... | Generates an excel worksheet containing data generated over a given lambda scalar range in opts["lambda_scalars"] | 625941df16aa5153ce3627e4 |
def macro_weights(self): <NEW_LINE> <INDENT> total_macro_weights = Lunchbox.macro_weights(self) <NEW_LINE> multiplier = self.consumed() / float(self.prepared()) <NEW_LINE> for macro_id in total_macro_weights: <NEW_LINE> <INDENT> total_macro_weights[macro_id] *= multiplier <NEW_LINE> <DEDENT> return total_macro_weights | Return macronutrient gram weights for this Recipe.
Extends Lunchbox.macro_weights to adjust the gram weight values for
the portion size of this Recipe.
:return: Gram weights of macronutrients for all constituent Quantities
:rtype: dict | 625941dfd10714528d600054 |
def SRWWavefrontFromElectricField(horizontal_start, horizontal_end, horizontal_efield, vertical_start, vertical_end, vertical_efield, energy, z, Rx, dRx, Ry, dRy): <NEW_LINE> <INDENT> horizontal_size = horizontal_efield.shape[0] <NEW_LINE> vertical_size = horizontal_efield.shape[1] <NEW_LINE> if horizontal_size % 2 == ... | Creates a SRWWavefront from pi and sigma components of the electrical field.
:param horizontal_start: Horizontal start position of the grid in m
:param horizontal_end: Horizontal end position of the grid in m
:param horizontal_efield: The pi component of the complex electrical field
:param vertical_start: Vertical star... | 625941df16aa5153ce3627e5 |
def get_instance(service_name): <NEW_LINE> <INDENT> sm = uno.getComponentContext() <NEW_LINE> ctx = sm.getServiceManager() <NEW_LINE> try: <NEW_LINE> <INDENT> service = ctx.createInstance(service_name) <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> service = NONE <NEW_LINE> <DEDENT> return service | Get a service shortcut. | 625941df07d97122c4178c00 |
def __setup_result_display(self): <NEW_LINE> <INDENT> trace.entry() <NEW_LINE> results_frame = Frame(self, relief=RAISED, borderwidth=1) <NEW_LINE> self.result_text = Text(results_frame, wrap=WORD) <NEW_LINE> results_frame.pack(fill=BOTH, expand=True) <NEW_LINE> self.result_text.pack(fill=BOTH) <NEW_LINE> trace.exit() | Creates a frame with a Text widget to display the results of the current maneuver.
:return: | 625941dfb7558d58953c527b |
def __init__(self,data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.right = None <NEW_LINE> self.left = None | OBJECTIVE : To initialize an object of class Node.
INPUT :
self :(Implicit parameter) An object of class Node.
data : The data to be stored at the Node.
RETURN : None | 625941df8e7ae83300e4b33a |
def _delete(self, experiment_name, force, dry_run): <NEW_LINE> <INDENT> cluster = self.cluster <NEW_LINE> if experiment_name: <NEW_LINE> <INDENT> to_delete = experiment_name <NEW_LINE> if force: <NEW_LINE> <INDENT> assert to_delete in cluster.list_experiments(), '[Error] Experiment `{}` not found. ' ... | Stop an experiment, delete corresponding pods, services, and namespace.
If experiment_name is omitted, default to deleting the current namespace. | 625941df99fddb7c1c9de6fc |
def set_results(self, results: PipelineResult) -> None: <NEW_LINE> <INDENT> self._results = results | Stores results of a pipeline run
Args:
results: The pipeline results
Returns: None | 625941dfe5267d203edce006 |
def fitnessFunction(x, i): <NEW_LINE> <INDENT> s = 0 <NEW_LINE> m = 1 <NEW_LINE> card = 1 <NEW_LINE> for gene in ea_list[i].initial_gene_pool[x]: <NEW_LINE> <INDENT> if gene == True: <NEW_LINE> <INDENT> s += card <NEW_LINE> <DEDENT> elif gene == False: <NEW_LINE> <INDENT> m *= card <NEW_LINE> <DEDENT> card += 1 <NEW_LI... | Uses fitness function to calculate fitness for a given individual. | 625941dfcad5886f8bd27346 |
def is_valid(self): <NEW_LINE> <INDENT> if not self.is_begin() and not self.is_end(): <NEW_LINE> <INDENT> self.__check_short_name() <NEW_LINE> self.__check_emissions_probability_sum() <NEW_LINE> <DEDENT> if not self.is_end(): <NEW_LINE> <INDENT> self.__check_transitions_probability_sum() <NEW_LINE> <DEDENT> return True | Checks if the HMM is valid and raises an error if not:
+ Checks if emissions sum up 1.
+ Checks short name has only one letter. | 625941df5e10d32532c5f292 |
def polygon(pen, sides, length): <NEW_LINE> <INDENT> for i in range(sides): <NEW_LINE> <INDENT> pen.forward(length) <NEW_LINE> pen.right( 360.0 / sides ) | makes a [sides] sided polygon each side is [length] long | 625941df99cbb53fe6792f53 |
def upgrade(self): <NEW_LINE> <INDENT> from rhodecode.lib.dbmigrate.migrate.versioning import api <NEW_LINE> from rhodecode.lib.dbmigrate.migrate.exceptions import DatabaseNotControlledError <NEW_LINE> if 'sqlite' in self.dburi: <NEW_LINE> <INDENT> print ( '********************** WARNING ********************... | Upgrades given database schema to given revision following
all needed steps, to perform the upgrade | 625941dfdd821e528d63b514 |
def test_tempdir(self): <NEW_LINE> <INDENT> with self.assertRaises(exceptions.InappropriateError): <NEW_LINE> <INDENT> self.fs.tempdir() | Tempdir raises | 625941df3317a56b86939fbe |
def recoveredRatio(self): <NEW_LINE> <INDENT> population_size = self.Population <NEW_LINE> ratio = round(100 / population_size * self.Request.range[-1]['Recovered'], 2) <NEW_LINE> print("Genesene Bevölkerung", ratio, "%") <NEW_LINE> return ratio | Berechnet die Genesene Bevölkerung
:return - Daten für Genesene Bevölkerung pro Tag | 625941dfb830903b967e9c75 |
def get_model(self, model_id): <NEW_LINE> <INDENT> return self.request(method='GET', url='/v1/models/{0}'.format(model_id), accept_json=True) | :param model_id: The identifier of the desired model
:return: A single instance of a Model object with results for the
specified model. | 625941dfcb5e8a47e48b7e13 |
def __init__(self, center=Point(0.0, 0.0), radius=0.5, n=None, ds=None): <NEW_LINE> <INDENT> self.center = center <NEW_LINE> self.radius = radius <NEW_LINE> self.n, self.ds = n, ds <NEW_LINE> self.create() <NEW_LINE> self.get_mass_center() | Creates the circle.
Parameters
----------
center: Point
Center of the circle; default: Point(0.0, 0.0).
radius: float
Radius of the circle; default: 0.5.
n: None or int
Number of divisions.
ds: None or float
Desired segment-length. | 625941dfbe383301e01b57ec |
def append_residuals_opt(opt_df, cdata, credg, out_fn=None): <NEW_LINE> <INDENT> residual_cols = ['residual', 'norm_residual'] <NEW_LINE> if set(residual_cols).issubset(opt_df.columns.values): <NEW_LINE> <INDENT> print('Residuals already appended to dataframe - exiting') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pr... | Calculates the residuals and normalized residuals for the absolute
optimal calibration fitting, for each frequency and time integration slice,
and appends the residual results to the existing relative calibration results
dataframe.
:param opt_df: Absolute optimal calibration results dataframe
:type opt_df: DataFrame
:... | 625941dfa4f1c619b28b039f |
def update_queues(self, queue_config): <NEW_LINE> <INDENT> logger.info('Updating queues for {}'.format(self.project_id)) <NEW_LINE> if not queue_config: <NEW_LINE> <INDENT> new_queue_config = {'default': {'rate': '5/s'}} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_queue_config = json.loads(queue_config.decode('ut... | Caches new configuration details and cleans up old state.
Args:
queue_config: A JSON string specifying queue configuration. | 625941df3617ad0b5ed68263 |
def getstrugglingstudents(self, df, assignedhwlist, el, s, verbose=True): <NEW_LINE> <INDENT> totstudents = len(df) <NEW_LINE> totstudents80percent = int(len(df) * 0.8) <NEW_LINE> strugglingstudentlist = [] <NEW_LINE> assignedquizzes = [] <NEW_LINE> mask1 = df.columns.str.contains(s) <NEW_LINE> mask2 = np.any([df.colum... | Accepts the Moodle gradebook in percent format as df and searches for empty grades in all columns which belong
to the grading element s. s is usually a search pattern like (Quiz:HW*). el is the column name for
emptygradecount. So a typical call would be getstrugglingstudents(df, 'hw', 'Quiz:HW*')
:param df:
:param assi... | 625941df7c178a314d6ef7d2 |
def do_mccp(self, option): <NEW_LINE> <INDENT> self.protocol.protocol_flags['MCCP'] = True <NEW_LINE> self.protocol.requestNegotiation(MCCP, '') <NEW_LINE> self.protocol.zlib = zlib.compressobj(9) | The client supports MCCP. Set things up by
creating a zlib compression stream. | 625941df0a366e3fb873eb8a |
def setup_logger(): <NEW_LINE> <INDENT> logger = logging.getLogger('user_map') <NEW_LINE> logger.setLevel(logging.DEBUG) <NEW_LINE> handler_level = logging.DEBUG <NEW_LINE> formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') <NEW_LINE> log_dir = APP.config['LOG_DIR'] <NEW_LINE> if 'US... | Set up our logger with sentry support.
| 625941df07f4c71912b117f2 |
def filter_for_message(getter_func, msg): <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> while True: <NEW_LINE> <INDENT> candidate = getter_func(0.05) <NEW_LINE> if candidate and candidate[:3] == msg[:3]: <NEW_LINE> <INDENT> return candidate <NEW_LINE> <DEDENT> if time.time() - start > 5.0: <NEW_LINE> <INDENT> rais... | Helper that calls ``getter_func`` until a matching message
is found, or the timeout occurs. Matching means the same commands
group, i.e. for sent message MVLUP we would accept MVL13
in response. | 625941dfff9c53063f47c55f |
def __init__(self, data): <NEW_LINE> <INDENT> self.type = data.get('type') | Class constructor
:param data: | 625941df6fece00bbac2daaf |
def _transform_id_select_sql(model_version, site, target_schema, target_table, id_name): <NEW_LINE> <INDENT> metadata = stock_metadata(model_version) <NEW_LINE> metadata.info['site'] = site <NEW_LINE> stmt_pairs = set() <NEW_LINE> target_table = target_table.split(",") <NEW_LINE> for table_name, table in metadata.table... | Create SQL for `select` statement transformations.
The `search_path` only needs to contain the source schema; the target
schema is embedded in the SQL statements.
The returned statements are not sufficient for the transformation;
the `pre_transform` needs to be run beforehand.
Returns a set of tuples of (sql_string,... | 625941df796e427e537b0935 |
def setEntries(self, means, covars): <NEW_LINE> <INDENT> for i in range(self.size): <NEW_LINE> <INDENT> self._parameters[i].setEntries(means[i], covars[i]) | means: numpy array KxD
covars: numpy array KxDxD | 625941df498bea3a759b9e1c |
def assemble_ring(self): <NEW_LINE> <INDENT> if self.newring: <NEW_LINE> <INDENT> if not self.start_new_ring(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.lineidx = 0 <NEW_LINE> <DEDENT> ind = self.lineidx <NEW_LINE> while self.ringend1 != self.ringend2: <NEW_LINE> <INDENT> dirconnect = [] <NEW_LINE> try... | Construct a closed ring from the set of lines.
Return True if an opened/closed ring has been built.
Return False if no more ring. | 625941dfa219f33f34628cd2 |
def numUniqueEmails(self, emails): <NEW_LINE> <INDENT> result = set() <NEW_LINE> for email in emails: <NEW_LINE> <INDENT> result_email = "" <NEW_LINE> i = 0 <NEW_LINE> while i < len(email): <NEW_LINE> <INDENT> if email[i] == '.': <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> elif email[i] == '@': <NEW_LINE> <INDENT> b... | :type emails: List[str]
:rtype: int | 625941df82261d6c526ab811 |
def update_celety_status(celery_uid, data): <NEW_LINE> <INDENT> sub_task = SubTaskM.find(sub_task_uid=celery_uid) <NEW_LINE> if sub_task.one_or_none(): <NEW_LINE> <INDENT> sub_task.update(data) <NEW_LINE> db.session.commit() <NEW_LINE> return row2dict(sub_task.one()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return | update celery task result | 625941df8c0ade5d55d3ed2b |
def make_channel_type(self): <NEW_LINE> <INDENT> return random.choice([ "01", "02", "03" ]) | 交易渠道 | 625941dfc432627299f04fb6 |
def test_addAgg(self): <NEW_LINE> <INDENT> self.assess.target = 75 <NEW_LINE> self.assess.save() <NEW_LINE> r = self.client.get(reverse('makeReports:data-agg-create',kwargs={ 'report':self.rpt.pk, 'assessment':self.assess.pk })) <NEW_LINE> self.assertEquals(r.status_code,200) <NEW_LINE> self.client.post(reverse('makeRe... | Tests adding a new AssessmentAggregate | 625941dfb5575c28eb68e370 |
def execute_suppress_output(self, cmdline): <NEW_LINE> <INDENT> cmd = ['ip', 'netns', 'exec', self._get_nsname()] + cmdline <NEW_LINE> with open(os.devnull, "w") as fnull: <NEW_LINE> <INDENT> LOG.debug('execute ' + ' '.join(cmd)) <NEW_LINE> try: <NEW_LINE> <INDENT> return subprocess.call(cmd, stdout=fnull, stderr=fnull... | Executes cmdline inside the namespace, but suppresses output
Args:
cmdline: command line string that'll be executed in the network
namespace.
Returns:
return code of the called process
Raises:
OSError: when the executable is not found or some other error
invoking | 625941df6aa9bd52df037113 |
def places(self): <NEW_LINE> <INDENT> for place_handle in self.db.get_place_handles(): <NEW_LINE> <INDENT> self.progress.step() <NEW_LINE> place = self.db.get_place_from_handle(place_handle) <NEW_LINE> place_name = place.get_name() <NEW_LINE> pname = place_name.get_value() <NEW_LINE> found = False <NEW_LINE> self.toolt... | For all places in the database, if the name contains leading or
trailing spaces. | 625941df8e7ae83300e4b33b |
def get_queryset(self, request): <NEW_LINE> <INDENT> qs = super().get_queryset(request) <NEW_LINE> if request.user.is_superuser: <NEW_LINE> <INDENT> return qs <NEW_LINE> <DEDENT> return qs.filter(Q(receiver_user_id=request.user) | Q(sender_user_id=request.user)) | Specific teacher will see only his department related messages
:param request:
:return: QuerySet<Message> | Messages which are either send by or receive by the current authenticated user | 625941dffff4ab517eb2f7ab |
def _format_filters(self, filters): <NEW_LINE> <INDENT> args = filters.keys() <NEW_LINE> result = {} <NEW_LINE> if len(args) == 1: <NEW_LINE> <INDENT> for key, value in filters.iteritems(): <NEW_LINE> <INDENT> tagvalue = value if isinstance(value, list) else [value] <NEW_LINE> if key.upper().startswith('TAG_'): <NEW_LI... | Give the correct format to filters for get_cost function
Args:
filters {dict}: Key and values of your filters
Raises:
ValueError: Invalid filter key passed.
Returns:
dict -- Well-formatted keys and values of filters | 625941dfac7a0e7691ed4434 |
def normalize_weight(self, samples): <NEW_LINE> <INDENT> for i in range(NUM_OF_INSTANCE): <NEW_LINE> <INDENT> total = 0 <NEW_LINE> for j in range(self.effective_model_num): <NEW_LINE> <INDENT> total += samples[i][j] <NEW_LINE> <DEDENT> for j in range(self.effective_model_num): <NEW_LINE> <INDENT> samples[i][j] /= total... | normalize weight
Parameters
----------
samples: list
a collection of sample, it's a (NUM_OF_INSTANCE * NUM_OF_FUNCTIONS) matrix,
representing{{w11, w12, ..., w1k}, {w21, w22, ... w2k}, ...{wk1, wk2,..., wkk}}
Returns
-------
list
samples after normalize weight | 625941df66656f66f7cbc51a |
def filterAcceptsRow(self, sourceRow, sourceParent): <NEW_LINE> <INDENT> index = self.sourceModel().index(sourceRow, self.filterKeyColumn(), sourceParent) <NEW_LINE> return self.accept_index(index) | Accept the row if the parent has been accepted. | 625941df91f36d47f21ac863 |
def update_ui_command_list_errors(self, command_phase_type=CommandPhaseType.RUN) -> None: <NEW_LINE> <INDENT> debug = False <NEW_LINE> if debug: <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> <DEDENT> blank_icon = QtGui.QIcon() <NEW_LINE> for i in range(len(self.gp_model)): <NEW_LINE> <INDENT> numb... | Once commands have been run. Loop through and check for any errors or warnings.
This is called from: GeoProcessorUI.command_completed().
Returns:
None | 625941df99fddb7c1c9de6fd |
def send_audio(ws): <NEW_LINE> <INDENT> global disconnect_sign <NEW_LINE> global finished_sign <NEW_LINE> global result <NEW_LINE> disconnect_sign = False <NEW_LINE> finished_sign = False <NEW_LINE> result = "" <NEW_LINE> CHUNK = 1024 <NEW_LINE> FORMAT = pyaudio.paInt16 <NEW_LINE> CHANNELS = 1 <NEW_LINE> RATE = 16000 <... | 发送二进制音频数据,注意每个帧之间需要有间隔时间
:param websocket.WebSocket ws:
:return: | 625941dfbf627c535bc1353d |
def _preprare_data_in_groups(self,X, y=None, sample_weights=None): <NEW_LINE> <INDENT> if sparse.issparse(X): <NEW_LINE> <INDENT> group_labels = X.getcol(0).toarray()[:,0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> group_labels = X[:,0] <NEW_LINE> <DEDENT> group_indices = group_labels.argsort() <NEW_LINE> group_labe... | Takes the first column of the feature Matrix X given and
transforms the data into groups accordingly.
Parameters
----------
X : (2d-array like) Feature matrix with the first column the group label
y : (optional, 1d-array like) target values
sample_weights : (optional, 1d-array like) sample weights
Returns
-------
sizes... | 625941df30c21e258bdfa80d |
def __init__(self): <NEW_LINE> <INDENT> self.Sdkappid = None <NEW_LINE> self.Iccid = None <NEW_LINE> self.Content = None | :param Sdkappid: 应用ID
:type Sdkappid: int
:param Iccid: 卡片ID
:type Iccid: str
:param Content: 短信内容长度70限制
:type Content: str | 625941df379a373c97cfaeb4 |
def find_maximal_subarray_sum(nums: List[int], k: int) -> int: <NEW_LINE> <INDENT> length = k <NEW_LINE> max_sum = -float("inf") <NEW_LINE> while length > 0: <NEW_LINE> <INDENT> for i in range(len(nums) + 1 - k): <NEW_LINE> <INDENT> sum_subset = sum(nums[0 + i : k + i]) <NEW_LINE> if sum_subset > max_sum: <NEW_LINE> <I... | Find the maximum sum of elements of a sub-array of a given length k.
Args:
nums: array
k: sub-array length
Returns:
The return value. maximum sum sub-array | 625941dfe8904600ed9f229f |
def getUserFollowerCount(tweet): <NEW_LINE> <INDENT> return tweet["user"]["followers_count"] | method for getting the followers count of the user | 625941df9b70327d1c4e1144 |
def test_get_data(): <NEW_LINE> <INDENT> test_interface = 'SPTInterface' <NEW_LINE> test_variable = 'site:wave:dir' <NEW_LINE> this_dir = os.path.dirname(__file__) <NEW_LINE> test_path = os.path.join(this_dir, 'data', 'test_spectrum_30min.spt' ) <NEW_LINE> interfacer = NamedSocket("FileInterface") <NEW_LINE> interfacer... | Test if data can be retrieved from an interface | 625941df5510c4643540f74a |
def transform_value(self, value): <NEW_LINE> <INDENT> return value | transform the value after macro expansion.
this can be overridden to further transform the value set by
the user *after* macros are expanded, but before the user's
``type`` function is applied. principally exists for
PathOption to canonicalize the path. | 625941dfad47b63b2c50a2ec |
def _summary_text(self): <NEW_LINE> <INDENT> msg = "" <NEW_LINE> activated_devs = nm.nm_activated_devices() <NEW_LINE> for name in self.supported_devices: <NEW_LINE> <INDENT> if name in activated_devs: <NEW_LINE> <INDENT> msg += self._activated_device_msg(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg += _("Wi... | Devices cofiguration shown to user. | 625941dfbde94217f368315b |
@app.route("/search", methods=["GET", "POST"]) <NEW_LINE> @logincheck <NEW_LINE> def search(): <NEW_LINE> <INDENT> form = SearchForm() <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <INDENT> pet_type = form.pettype.data <NEW_LINE> gender = form.gender.data <NEW_LINE> distance = form.distance.data <NEW_LINE> locati... | Display search options | 625941dfe64d504609d74bae |
def find_centroid(cluster): <NEW_LINE> <INDENT> sum_x, sum_y = 0, 0 <NEW_LINE> for r in cluster: <NEW_LINE> <INDENT> sum_x += restaurant_location(r)[0] <NEW_LINE> sum_y += restaurant_location(r)[1] <NEW_LINE> <DEDENT> return [sum_x / len(cluster), sum_y / len(cluster)] | Return the centroid of the locations of the restaurants in cluster. | 625941df0a366e3fb873eb8b |
def __initialize(self, config): <NEW_LINE> <INDENT> self.__eth_client = EthereumWrapper(config) <NEW_LINE> tcf_home = environ.get("TCF_HOME", "../../../") <NEW_LINE> contract_file_name = tcf_home + "/" + config["ethereum"]["direct_registry_contract_file"] <NEW_LINE> contract_address = config["ethe... | Initialize the parameters from config to instance variables. | 625941dfab23a570cc2504f3 |
def choose_action(self, state): <NEW_LINE> <INDENT> return state | Call this method to choose the correct action
:param state: it's previous opponent action
:return: the action chosen by the agent | 625941df9f2886367277abf9 |
def update_corpus_posattr_references(self, corpus_id, posattr_id, fromattr_id, mapto_id): <NEW_LINE> <INDENT> cursor = self._db.cursor() <NEW_LINE> cursor.execute( 'UPDATE corpus_posattr SET fromattr = %s, mapto = %s ' 'WHERE corpus_name = %s AND name = %s', (fromattr_id, mapto_id, corpus_id, posattr_id)) | both fromattr_id and mapto_id can be None | 625941df7d847024c06be62d |
def limit(self, inputFiles): <NEW_LINE> <INDENT> return None | Set a limit based on the model dependent method | 625941df26238365f5f0f1e1 |
def poem_composer(model, seed_sen, poem_len, seq_size, dict, temperature): <NEW_LINE> <INDENT> pseudo_poem = '' <NEW_LINE> dict_len = len(dict) <NEW_LINE> for idx in range(poem_len): <NEW_LINE> <INDENT> for char_idx in range(seq_size): <NEW_LINE> <INDENT> test = model.predict(seed_sen) <NEW_LINE> prediction = model.pre... | generate poems from RNN model
seed_sen = seed sentence fed into the model
poem_len = length of poem to write | 625941dfd58c6744b4257fcd |
def non_monotone(variations, lX, lY, signe): <NEW_LINE> <INDENT> for dummy in range(20): <NEW_LINE> <INDENT> tirage = [a for a in range(len(variations))] <NEW_LINE> try: <NEW_LINE> <INDENT> i0 = tirage.pop(randrange(len(tirage))) <NEW_LINE> while lY[i0] == lY[i0 + 1]: <NEW_LINE> <INDENT> i0 = tirage.pop(randrange(len(t... | Donne un intervalle sur lequel la fonction n'est pas monotone. On peut malgré tout comparer
les extrémités de cet intervalle par le signe de leurs images si signe=True | 625941dff7d966606f6aa377 |
def __init__(self, parent=None): <NEW_LINE> <INDENT> plugins.PluginWidget.__init__(self) <NEW_LINE> QtGui.QWidget.__init__(self, parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.connect(self.pushStart, QtCore.SIGNAL("clicked()"), self.__slot_start_service) <NEW_LINE> self.connect(self.pushStop, QtCore.SIGNAL("clic... | Constructor for main window.
Arguments:
parent: Parent object | 625941df046cf37aa974d0b3 |
def __rmul__(self, value): <NEW_LINE> <INDENT> return self._combine(self.MUL, value, True) | Combine with operator * if left value does not support the combination
:param value: Value to combine with
:type value: Node or any Python type
:returns: Combined expression
:rtype: CombinedExpression | 625941df3cc13d1c6d3c76e7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.