code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@command <NEW_LINE> def ex(foo, b=None, spam=None): <NEW_LINE> <INDENT> print(foo, b, spam)
Nothing interesting. :param foo: Bla bla. :param -b: A little flag. :param -s, --spam: Spam spam spam spam.
625941bd5166f23b2e1a5053
def prophet(self, changepoint_prior_scale=.35, fit_pred=False, actual_pred=False, pred=False, fit=False, residuals=False): <NEW_LINE> <INDENT> if self.forecast_type == 1: <NEW_LINE> <INDENT> return self.prophet_series() <NEW_LINE> <DEDENT> if self.forecast_type == 2: <NEW_LINE> <INDENT> return self.prophet_dataframe(fit_pred=fit_pred, actual_pred=actual_pred, pred=pred, fit=fit, residuals=residuals )
wraps prophet-series and prophet_dataframe methods to forecast forecasting for single series returns a dictionary forecasting for dataframe returns back dataframe of predictions -can alter parameters to also return fitted values Args: -----Only relevant for dataframes below------ fit_pred: returns dataframe of fitted and predicted values actual_pred: returns dataframe of actual and predicted values pred: returns dataframe of predicted values only fit: returns dataframe of fitted values only residuals: returns dataframe of residual values only Returns: series: if series passed in, returns dict of parameters of forecast object dataframe: if dataframe passed in, dataframe of predictions and optionally fitted values is returned
625941bdcc40096d6159584c
def get_args(): <NEW_LINE> <INDENT> args, unparsed = parser.parse_known_args() <NEW_LINE> if args.num_gpu > 0: <NEW_LINE> <INDENT> setattr(args, 'cuda', True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(args, 'cuda', False) <NEW_LINE> <DEDENT> if len(unparsed) > 1: <NEW_LINE> <INDENT> logger.info(f"Unparsed args: {unparsed}") <NEW_LINE> <DEDENT> return args, unparsed
Parses all of the arguments above, which mostly correspond to the hyperparameters mentioned in the paper.
625941bd7d43ff24873a2b98
def save_class_activation_images(org_img, activation_map, file_name): <NEW_LINE> <INDENT> if not os.path.exists('../results'): <NEW_LINE> <INDENT> os.makedirs('../results') <NEW_LINE> <DEDENT> heatmap, heatmap_on_image = apply_colormap_on_image(org_img, activation_map, 'hsv') <NEW_LINE> path_to_file = os.path.join('../results', file_name+'_Cam_On_Image.png') <NEW_LINE> save_image(heatmap_on_image, path_to_file)
Saves cam activation map and activation map on the original image Args: org_img (PIL img): Original image activation_map (numpy arr): Activation map (grayscale) 0-255 file_name (str): File name of the exported image
625941bd26068e7796caebd4
def p_clause_sees(p): <NEW_LINE> <INDENT> p[0] = p[1:]
clause_sees : _SEES_ expr_PLUSComma
625941bd293b9510aa2c3193
def get_incomplete_assessment_sections(self, assessment_taken_id): <NEW_LINE> <INDENT> return
Gets the incomplete assessment sections of this assessment. :param assessment_taken_id: ``Id`` of the ``AssessmentTaken`` :type assessment_taken_id: ``osid.id.Id`` :return: the list of incomplete assessment sections :rtype: ``osid.assessment.AssessmentSectionList`` :raise: ``IllegalState`` -- ``has_assessment_begun()`` is ``false`` :raise: ``NotFound`` -- ``assessment_taken_id`` is not found :raise: ``NullArgument`` -- ``assessment_taken_id`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``PermissionDenied`` -- authorization failure occurred *compliance: mandatory -- This method must be implemented.*
625941bd0c0af96317bb80e3
def can_execute ( self ): <NEW_LINE> <INDENT> return False
Returns True if the item can be 'executed' in some meaningful fashion, and False if it cannot.
625941bd56ac1b37e62640cf
def __init__(self, parent=None): <NEW_LINE> <INDENT> super(faa_nasr2shpDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self)
Constructor.
625941bdb7558d58953c4e14
def test_vote_not_exist(self): <NEW_LINE> <INDENT> response = self.client.get("/api/vote/1", follow=True) <NEW_LINE> self.assertEqual(response.status_code, 404) <NEW_LINE> response = self.client.get("/api/vote/abc", follow=True) <NEW_LINE> self.assertEqual(response.status_code, 404)
test the vote endpoint to get info of a non-exist note, should return not found
625941bd23849d37ff7b2f8b
def get_media_handles(self, sort_handles=False, locale=glocale): <NEW_LINE> <INDENT> if (self.db is not None) and self.db.is_open(): <NEW_LINE> <INDENT> return list(self.iter_media_handles()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return []
Return a list of database handles, one handle for each Media in the database.
625941bdd99f1b3c44c67490
def contains_seeds(seeds): <NEW_LINE> <INDENT> shp = [np.asarray(s).max() + 2 for s in seeds] <NEW_LINE> rav = np.ravel_multi_index(seeds, shp) <NEW_LINE> def result(structure, index=None, value=None): <NEW_LINE> <INDENT> sid = structure.indices() <NEW_LINE> if len(sid) != len(seeds): <NEW_LINE> <INDENT> raise TypeError("Dimensions of seeds and data do not agree") <NEW_LINE> <DEDENT> rav2 = np.ravel_multi_index(sid, shp, mode='clip') <NEW_LINE> return np.intersect1d(rav, rav2).size > 0 <NEW_LINE> <DEDENT> return result
Critieria that leaves contain at least one of a list of seed positions Parameters ---------- seeds : tuple of array-like seed locations. The ith array in the tuple lists the ith coordinate for each seed. This is the format returned, e.g., by np.where
625941bdcb5e8a47e48b79a8
def set_layer_props(s,l, color=(0.0,1.0,0.0), opacity=1.0, blend='additive', minval=0.0, maxval=.25, shift=(0,0,0)): <NEW_LINE> <INDENT> l=s.layers[l].layer <NEW_LINE> (shiftx,shifty,shiftz)=shift <NEW_LINE> matrix = [[1,0,0,shiftx*1000],[0,1,0,shifty*1000],[0,0,1,shiftz*1000],[0,0,0,1]] <NEW_LINE> l._json_data['color']=color <NEW_LINE> l._json_data['blend']=blend <NEW_LINE> l._json_data['opacity']=opacity <NEW_LINE> l._json_data['min']=minval <NEW_LINE> l._json_data['max'] = maxval <NEW_LINE> l._json_data['transform']=matrix <NEW_LINE> l._json_data['shader']=get_shader(minval,maxval,color)
function to set properties of a neuroglancer layer Parameters ---------- s: neuroglancer.ViewerState neuroglancer viewer state (from viewer.txn()) l: str key for layer you want to set such that layer=s.layers[l] color: tuple (r,g,b) tuple of color for layer values [0,1] Default (0,1,0) opacity: float opacity of layer (default=1.0) minval: float minimum value of lookup function (default=0.0) maxval: float maximum value of lookup function (default=1.0) shift: tuple (dx,dy,dz) shift of layer in global coordinates (default=(0,0,0)) Returns: None
625941bdbaa26c4b54cb101d
def get_elements_for_label(self, label): <NEW_LINE> <INDENT> elements = [] <NEW_LINE> for element in self.tree.getiterator(): <NEW_LINE> <INDENT> for setting_name, setting_value in element.items(): <NEW_LINE> <INDENT> if setting_value.startswith("[") and setting_value.endswith("]"): <NEW_LINE> <INDENT> label_i = setting_value.split("[")[1].split(":")[0] <NEW_LINE> if label_i == label: elements.append((element, setting_name)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return elements
Thisf unction ... :param label: :return:
625941bdbe7bc26dc91cd500
def _fft_created_(self, freq, fft): <NEW_LINE> <INDENT> if self._show_fft and self._fft_window is not None: <NEW_LINE> <INDENT> self._close_fft_window_() <NEW_LINE> <DEDENT> elif not self._show_fft: <NEW_LINE> <INDENT> self._show_fft = True <NEW_LINE> self._fft_window = PyGraphSubPlotWindow(self) <NEW_LINE> self._fft_window.setWindowTitle('FFT') <NEW_LINE> fft_plot = PyGraphWidget(self._fft_window) <NEW_LINE> fft_plot.set_data(freq, fft) <NEW_LINE> fft_plot.set_plot_color('y') <NEW_LINE> fft_plot.y_label = 'FFT amplitude' <NEW_LINE> fft_plot.x_label = 'FFT frequency' <NEW_LINE> self._fft_window.setCentralWidget(fft_plot) <NEW_LINE> self._fft_window.is_closing.append(self._window_was_closed_) <NEW_LINE> self._fft_window.show()
Callback when FFT creation has been finished :param freq: frequency data :param fft: amplitude data
625941bd2eb69b55b151c7a6
def get_predicts(x_matrix, model, poly, scale, dummy_idx): <NEW_LINE> <INDENT> x_matrix = np.array(x_matrix) <NEW_LINE> temp_list = split_poly_scale_join([x_matrix], dummy_idx, poly, scale) <NEW_LINE> x_matrix = temp_list[0] <NEW_LINE> return model.predict(x_matrix)
Returns predictions made by a given model. This function takes in an X_matrix and uses the imported model to return the predicted (y-hat) values as a list. :param x_matrix: pd.DataFrame The matrix containing all the attributes needed to make predictions :param model: sklearn.linear_model type The prefitted model used to make predictions :param poly: int The degree in which a polynomial regression was performed If 0, printed results won't include this information. :param scale: bool If *False*, no scaling will occur. If *True*, features will be StandardScaled. :param dummy_idx: int The index at which dummy values start (inclusive). :return: list Returns a list of the predicted (y-hat) values
625941bd656771135c3eb766
def session_gae(session): <NEW_LINE> <INDENT> sample_directories = collect_sample_dirs('appengine/standard') <NEW_LINE> run_tests_in_sesssion( session, 'python2.7', sample_directories, use_appengine=True)
Runs test for GAE Standard samples.
625941bdfbf16365ca6f60b8
def __init__(self, str): <NEW_LINE> <INDENT> list = str.strip().split('\t') <NEW_LINE> if len(list) != 9: <NEW_LINE> <INDENT> logw('GTF initialized with list n=%d!', len(list)) <NEW_LINE> <DEDENT> self.seqname = list[0] <NEW_LINE> self.source = list[1] <NEW_LINE> self.feature = list[2] <NEW_LINE> self.start = int(list[3]) <NEW_LINE> self.end = int(list[4]) <NEW_LINE> self.score = list[5] <NEW_LINE> self.strand = list[6] <NEW_LINE> self.frame = list[7] <NEW_LINE> self.attribute = {} <NEW_LINE> attribute_list = list[8].split(";") <NEW_LINE> for item in attribute_list: <NEW_LINE> <INDENT> attribute = item.strip(' ') <NEW_LINE> if len(attribute) > 0: <NEW_LINE> <INDENT> key = attribute.split(" ")[0] <NEW_LINE> value = attribute.split(" ")[1] <NEW_LINE> self.attribute[key] = value.strip('"')
Given a str row from a gtf file, return a GTF object
625941bdd268445f265b4d69
def format_resource_filesize(size): <NEW_LINE> <INDENT> return formatters.localised_filesize(int(size))
Show a file size, formatted for humans.
625941bd4c3428357757c224
def on_tool_event(self, id, callback): <NEW_LINE> <INDENT> pass
Register a callback for events on the tool identified by 'id'.
625941bdd58c6744b4257b5b
def __doStep(self, i, player): <NEW_LINE> <INDENT> if not self.squares[i] == 'N': <NEW_LINE> <INDENT> if self.debug: print('illegal field') <NEW_LINE> player.saveForLearning(-1, False) <NEW_LINE> self.__nextStep() <NEW_LINE> return <NEW_LINE> <DEDENT> if self.xIsNext: <NEW_LINE> <INDENT> self.squares[i] = 'X' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.squares[i] = 'O' <NEW_LINE> <DEDENT> self.history.append(self.squares.copy()) <NEW_LINE> self.xIsNext = not self.xIsNext <NEW_LINE> if self.__winner() == self.squares[i]: <NEW_LINE> <INDENT> if self.debug: print('game is done,', self.squares[i], 'is winner') <NEW_LINE> player.saveForLearning(1, True) <NEW_LINE> return <NEW_LINE> <DEDENT> if self.done(): <NEW_LINE> <INDENT> if self.debug: print('game is done') <NEW_LINE> player.saveForLearning(0, True) <NEW_LINE> return <NEW_LINE> <DEDENT> player.saveForLearning(0, False) <NEW_LINE> self.__nextStep() <NEW_LINE> return
One step forward :param i: index for next placement :return: nextSituation, number, doneState
625941bd4c3428357757c225
def test_to_from_json(self): <NEW_LINE> <INDENT> tmp_filename = "mosaic_geom.json" <NEW_LINE> self.mosaic_geom.to_json(tmp_filename) <NEW_LINE> mosaic_geom = MosaicGeometry.from_json(tmp_filename) <NEW_LINE> os.remove(tmp_filename) <NEW_LINE> assert mosaic_geom.name == self.mosaic_geom.name <NEW_LINE> assert mosaic_geom.description == self.mosaic_geom.description <NEW_LINE> assert mosaic_geom.tile_names == self.mosaic_geom.tile_names <NEW_LINE> assert np.all(mosaic_geom._adjacency_matrix == self.mosaic_geom._adjacency_matrix)
Tests dumping a mosaic geometry to and loading it from disk.
625941bd4a966d76dd550f07
def run(gParameters): <NEW_LINE> <INDENT> import keras <NEW_LINE> from keras.datasets import mnist <NEW_LINE> from keras.models import Sequential <NEW_LINE> from keras.layers import Dense, Dropout, Flatten <NEW_LINE> from keras.layers import Conv2D, MaxPooling2D <NEW_LINE> from keras import backend as K <NEW_LINE> batch_size = gParameters['batch_size'] <NEW_LINE> num_classes = 10 <NEW_LINE> epochs = gParameters['epochs'] <NEW_LINE> activation = gParameters['activation'] <NEW_LINE> optimizer = gParameters['optimizer'] <NEW_LINE> img_rows, img_cols = 28, 28 <NEW_LINE> (x_train, y_train), (x_test, y_test) = mnist.load_data() <NEW_LINE> if K.image_data_format() == 'channels_first': <NEW_LINE> <INDENT> x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) <NEW_LINE> x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) <NEW_LINE> input_shape = (1, img_rows, img_cols) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) <NEW_LINE> x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) <NEW_LINE> input_shape = (img_rows, img_cols, 1) <NEW_LINE> <DEDENT> x_train = x_train.astype('float32') <NEW_LINE> x_test = x_test.astype('float32') <NEW_LINE> x_train /= 255 <NEW_LINE> x_test /= 255 <NEW_LINE> print('x_train shape:', x_train.shape) <NEW_LINE> print(x_train.shape[0], 'train samples') <NEW_LINE> print(x_test.shape[0], 'test samples') <NEW_LINE> y_train = keras.utils.to_categorical(y_train, num_classes) <NEW_LINE> y_test = keras.utils.to_categorical(y_test, num_classes) <NEW_LINE> model = Sequential() <NEW_LINE> model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) <NEW_LINE> model.add(Conv2D(64, (3, 3), activation='relu')) <NEW_LINE> model.add(MaxPooling2D(pool_size=(2, 2))) <NEW_LINE> model.add(Dropout(0.25)) <NEW_LINE> model.add(Flatten()) <NEW_LINE> model.add(Dense(128, activation='relu')) <NEW_LINE> model.add(Dropout(0.5)) <NEW_LINE> model.add(Dense(num_classes, activation='softmax')) <NEW_LINE> model.summary() <NEW_LINE> model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) <NEW_LINE> history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) <NEW_LINE> score = model.evaluate(x_test, y_test, verbose=0) <NEW_LINE> print('Test loss:', score[0]) <NEW_LINE> print('Test accuracy:', score[1]) <NEW_LINE> return history
Trains a simple convnet on the MNIST dataset. Gets to 99.25% test accuracy after 12 epochs (there is still a lot of margin for parameter tuning). 16 seconds per epoch on a GRID K520 GPU.
625941bd96565a6dacc8f5c7
def read_table_file(self, file, format='ascii.no_header'): <NEW_LINE> <INDENT> logger.info(f"Reading file names from input file {file!r}") <NEW_LINE> try: <NEW_LINE> <INDENT> table = Table.read(file, format=format) <NEW_LINE> if format == 'ascii.no_header': <NEW_LINE> <INDENT> default_column_name = table.colnames[0] <NEW_LINE> table[default_column_name].name = 'FILE' <NEW_LINE> <DEDENT> <DEDENT> except IORegistryError as e: <NEW_LINE> <INDENT> sys.tracebacklimit = 0 <NEW_LINE> raise e <NEW_LINE> <DEDENT> return list(table['FILE'].data)
Interprets text in a file input. Args: file (str): Name of the file containing the table. format (str, optional): Format string of the input table. Returns: table (astropy.Table): Table based on file input. common_path (str): Common path to the files in the table.
625941bd24f1403a92600a64
def Clone(self): <NEW_LINE> <INDENT> return FloatValidator(self.min_val, self.max_val, self.choices)
Required method
625941bd8a43f66fc4b53f63
def covariance(x,y): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cov_xy = 0 <NEW_LINE> n=0 <NEW_LINE> xmin,xmax,xmed,xm,sx = stats(x) <NEW_LINE> ymin,ymay,ymed,ym,sy = stats(x) <NEW_LINE> for i, j in zip(x,y): <NEW_LINE> <INDENT> cov_xy += (i-xm)*(j-ym) <NEW_LINE> n += 1 <NEW_LINE> <DEDENT> cov_xy = cov_xy/len(x) <NEW_LINE> r = cov_xy/(sx*sy) <NEW_LINE> return(cov_xy,r) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> PrintException()
I might delete this as it is now redundant, but we shall see. Computes the covariance inputs of x and y, also returning the Pearson r value between x and y.
625941bd66656f66f7cbc0a5
def strStr(self, haystack, needle): <NEW_LINE> <INDENT> l_h = len(haystack) <NEW_LINE> l_n = len(needle) <NEW_LINE> if l_h >= l_n > 0 : <NEW_LINE> <INDENT> for i in range(l_h - l_n + 1): <NEW_LINE> <INDENT> if haystack[i] == needle[0]: <NEW_LINE> <INDENT> if haystack[i:i+l_n] == needle: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> elif l_n == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return -1
:type haystack: str :type needle: str :rtype: int
625941bdcc0a2c11143dcd8b
def __add__(self, other): <NEW_LINE> <INDENT> return ImageDataset( self.data + other.data, self.mode + "+" + other.mode, pseudo_labels=None, transform=self.transform, verbose=False, sort=False, )
work for combining query and gallery into the test data loader
625941bd21bff66bcd684850
def encode(self, word): <NEW_LINE> <INDENT> new_word = [] <NEW_LINE> for w in word.lower(): <NEW_LINE> <INDENT> new_letter_idx = (self.a * self.alphabet.index(w) + self.s) % len(self.alphabet) <NEW_LINE> new_word.append(self.alphabet[new_letter_idx]) <NEW_LINE> <DEDENT> return "".join(new_word)
:param word: input open message :return: encrypted input message
625941bdd53ae8145f87a16f
def get(self, request, username): <NEW_LINE> <INDENT> count = User.objects.get(username=username).count() <NEW_LINE> data = { "username": username, "count": count } <NEW_LINE> return Response(data)
获取指定用户名数量
625941bd8e71fb1e9831d6a5
def write_voltage(self, filename, voltages): <NEW_LINE> <INDENT> file = open(filename, 'a') <NEW_LINE> delimiter = '\t' <NEW_LINE> text = delimiter.join(voltages) <NEW_LINE> file.write(text + '\n') <NEW_LINE> file.close()
Writes the voltages to end of filename.
625941bdf548e778e58cd477
def print_shell_info(self): <NEW_LINE> <INDENT> print("start_time='{}'".format(str(self.get_start_time()))) <NEW_LINE> print("end_time='{}'".format(str(self.get_end_time())))
Print information about this class in shell style
625941bd67a9b606de4a7db7
def maximal_order(self, v=None): <NEW_LINE> <INDENT> return self._maximal_order(self._normalize_prime_list(v))
Return the maximal order, i.e., the ring of integers, associated to this number field. INPUT: - ``v`` - (default: ``None``) ``None``, a prime, or a list of primes. - if ``v`` is ``None``, return the maximal order. - if ``v`` is a prime, return an order that is `p`-maximal. - if ``v`` is a list, return an order that is maximal at each prime in the list ``v``. EXAMPLES: In this example, the maximal order cannot be generated by a single element:: sage: k.<a> = NumberField(x^3 + x^2 - 2*x+8) sage: o = k.maximal_order() sage: o Maximal Order in Number Field in a with defining polynomial x^3 + x^2 - 2*x + 8 We compute `p`-maximal orders for several `p`. Note that computing a `p`-maximal order is much faster in general than computing the maximal order:: sage: p = next_prime(10^22); q = next_prime(10^23) sage: K.<a> = NumberField(x^3 - p*q) sage: K.maximal_order([3]).basis() [1/3*a^2 + 1/3*a + 1/3, a, a^2] sage: K.maximal_order([2]).basis() [1/3*a^2 + 1/3*a + 1/3, a, a^2] sage: K.maximal_order([p]).basis() [1/3*a^2 + 1/3*a + 1/3, a, a^2] sage: K.maximal_order([q]).basis() [1/3*a^2 + 1/3*a + 1/3, a, a^2] sage: K.maximal_order([p,3]).basis() [1/3*a^2 + 1/3*a + 1/3, a, a^2] An example with bigger discriminant:: sage: p = next_prime(10^97); q = next_prime(10^99) sage: K.<a> = NumberField(x^3 - p*q) sage: K.maximal_order(prime_range(10000)).basis() [1, a, a^2]
625941bd0fa83653e4656eb7
def get_activation(identifier): <NEW_LINE> <INDENT> if isinstance(identifier, six.string_types): <NEW_LINE> <INDENT> name_to_fn = { "gelu": gelu, "custom_swish": swish, } <NEW_LINE> identifier = str(identifier).lower() <NEW_LINE> if identifier in name_to_fn: <NEW_LINE> <INDENT> return tf.keras.activations.get(name_to_fn[identifier]) <NEW_LINE> <DEDENT> <DEDENT> return tf.keras.activations.get(identifier)
Maps a identifier to a Python function, e.g., "relu" => `tf.nn.relu`. It checks string first and if it is one of customized activation not in TF, the corresponding activation will be returned. For non-customized activation names and callable identifiers, always fallback to tf.keras.activations.get. Args: identifier: String name of the activation function or callable. Returns: A Python function corresponding to the activation function.
625941bde64d504609d7473b
def __init__(self, server, port, host='', snmpservermgr=None): <NEW_LINE> <INDENT> self.snmpservermgr = snmpservermgr <NEW_LINE> if (self.snmpservermgr == None): <NEW_LINE> <INDENT> self.snmpservermgr = snmpsocket(server) <NEW_LINE> <DEDENT> ucomm.udpserver.__init__(self, server, port, host, self.snmpservermgr)
Initialize
625941bd442bda511e8be317
def find_distinct(self, query, attribute): <NEW_LINE> <INDENT> return piped_command(self.child, {'db.find_distinct': {'query': query, 'attribute': attribute}})
Return a list representing the diversity of a given attribute in the documents matched by the query. :param query: json :type query: str :param attribute: String describing the attribute :type attribute: str :return: A list of values the attribute can have in the set of documents described by the query :rtype: list
625941bd07d97122c4178780
def new(self, name=None, data=None): <NEW_LINE> <INDENT> check_type(value=name, allowed_types=[str, None], var_name="name", raise_exception=True) <NEW_LINE> check_type(value=data, allowed_types=[dict, None], var_name="data", raise_exception=True) <NEW_LINE> try: <NEW_LINE> <INDENT> self.dm_client.table_read(name=name) <NEW_LINE> <DEDENT> except IkatsNotFoundError: <NEW_LINE> <INDENT> return Table(api=self.api, name=name, data=data) <NEW_LINE> <DEDENT> raise IkatsConflictError("Table already exist. Try using `get()` method")
Creates an empty table locally :param name: (optional) name of the Table :param data: (optional) data of the table (as a JSON) :type name: str or None :type data: dict or None :return: the Table object :rtype: Table :raises IkatsConflictError: if table already exist
625941bd6fece00bbac2d637
def test_get_min_max_none(self): <NEW_LINE> <INDENT> response = self.client.post(reverse('timeseries_min_max_json'), {'model_name': 'xgds_timeseries.TimeSeriesExample', 'flight_ids': [1, 2, 3]}) <NEW_LINE> self.assertEquals(response.status_code, 204)
Test getting the min and max values with a bad filter
625941bd2eb69b55b151c7a7
def inversedSamples(orderedSamples): <NEW_LINE> <INDENT> reverseSamples = [] <NEW_LINE> for sample in orderedSamples: <NEW_LINE> <INDENT> reverseSamples.append(sample[-1:-(len(sample)+1):-1]) <NEW_LINE> <DEDENT> return reverseSamples
Parameters ---------- orderedSamples : Requiere una lista de arreglos, que estos arreglos esten ordenados, para regresar una lista con los mismos arreglos pero ordenados de forma inversa Returns ------- Una lista de arreglos con orden inverso
625941bd5fcc89381b1e15b8
def shell_stop(sim, cmd, exit_code=1): <NEW_LINE> <INDENT> import subprocess <NEW_LINE> if sim.current_step == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> wrap_cmd = cmd.format(sim=sim) <NEW_LINE> output = subprocess.check_output(wrap_cmd, shell=True, stderr=subprocess.STDOUT, executable="/bin/bash") <NEW_LINE> if len(output) > 0: <NEW_LINE> <INDENT> _log.info('shell command "{}" returned: {}'.format(cmd, output.strip())) <NEW_LINE> <DEDENT> <DEDENT> except subprocess.CalledProcessError as e: <NEW_LINE> <INDENT> if e.returncode == exit_code: <NEW_LINE> <INDENT> raise SimulationEnd('shell command "{}" returned "{}"'.format(cmd, e.output.strip())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _log.error('shell command {} failed with output {}'.format(cmd, e.output)) <NEW_LINE> raise
Execute the shell command `cmd` and stop the simulation if the command returns an exit value equal to `exit_code`. `cmd` is actually a format string that may contain references to the passed `sim` instance. For instance, a valid command is #!python echo {sim.current_step} {sim.rmsd} >> {sim.output_path}.out which will append the step and rmsd to {sim.output_path}.out.
625941bdab23a570cc25007b
def fetch_records(resources): <NEW_LINE> <INDENT> if not resources: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> query = Session.query(Reservation) <NEW_LINE> query = query.filter(Reservation.resource.in_(resources.keys())) <NEW_LINE> query = query.order_by( Reservation.resource, Reservation.status, Reservation.start, Reservation.email, Reservation.token, ) <NEW_LINE> return query.all()
Returns the records used for the dataset.
625941bd45492302aab5e1bb
def flatten(self, head: 'Node') -> 'Node': <NEW_LINE> <INDENT> def inorder(cur, tail): <NEW_LINE> <INDENT> tail.next = cur <NEW_LINE> if not cur: <NEW_LINE> <INDENT> return tail <NEW_LINE> <DEDENT> cur.prev = tail <NEW_LINE> nxt = cur.next <NEW_LINE> tail = inorder(cur.child, cur) <NEW_LINE> cur.child = None <NEW_LINE> return inorder(nxt, tail) <NEW_LINE> <DEDENT> dummy = Node(None, None, None, None) <NEW_LINE> inorder(head, dummy) <NEW_LINE> root = dummy.next <NEW_LINE> if root: <NEW_LINE> <INDENT> root.prev = None <NEW_LINE> <DEDENT> return root
04/29/2020 23:53
625941bd460517430c394087
def __init__(self, name="SilverServiceTaxi", fuel=0, fanciness=2): <NEW_LINE> <INDENT> super().__init__(name, fuel) <NEW_LINE> self.price_per_km = self.price_per_km * fanciness
Initialise a SilverServiceTaxi instance, based on parent class Taxi.
625941bd26068e7796caebd5
def _add_instances_conversion_methods(newInstances): <NEW_LINE> <INDENT> cls_name = newInstances.__name__ <NEW_LINE> @torch.jit.unused <NEW_LINE> def from_instances(instances: Instances): <NEW_LINE> <INDENT> fields = instances.get_fields() <NEW_LINE> image_size = instances.image_size <NEW_LINE> ret = newInstances(image_size) <NEW_LINE> for name, val in fields.items(): <NEW_LINE> <INDENT> assert hasattr(ret, f"_{name}"), f"No attribute named {name} in {cls_name}" <NEW_LINE> setattr(ret, name, deepcopy(val)) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> newInstances.from_instances = from_instances
Add from_instances methods to the scripted Instances class.
625941bda05bb46b383ec71f
def __call__(self, r): <NEW_LINE> <INDENT> content_type = r.headers.get('Content-Type'.encode('utf-8'), '') <NEW_LINE> if not content_type and extract_params(r.body): <NEW_LINE> <INDENT> content_type = CONTENT_TYPE_FORM_URLENCODED <NEW_LINE> <DEDENT> if not isinstance(content_type, unicode): <NEW_LINE> <INDENT> content_type = content_type.decode('utf-8') <NEW_LINE> <DEDENT> is_form_encoded = (CONTENT_TYPE_FORM_URLENCODED in content_type) <NEW_LINE> if is_form_encoded: <NEW_LINE> <INDENT> r.headers['Content-Type'] = CONTENT_TYPE_FORM_URLENCODED <NEW_LINE> r.url, headers, r.body = self.client.sign( unicode(r.url), unicode(r.method), r.body or '', r.headers) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r.url, headers, _ = self.client.sign( unicode(r.url), unicode(r.method), None, r.headers) <NEW_LINE> <DEDENT> r.headers.update(headers) <NEW_LINE> r.url = to_native_str(r.url) <NEW_LINE> return r
Add OAuth parameters to the request. Parameters may be included from the body if the content-type is urlencoded, if no content type is set a guess is made.
625941bd7c178a314d6ef356
def crearFacebook(): <NEW_LINE> <INDENT> print("Creando cuenta de Facebook") <NEW_LINE> nombre = input("Ingrese su nombre: ") <NEW_LINE> edad = int(input("Ingrese su edad: ")) <NEW_LINE> ciudad = input("Ingrese el nombre de su ciudad: ") <NEW_LINE> pais = input("Ingrese el nombre de su pais: ") <NEW_LINE> idioma = input("Ingrese que idioma habla: ") <NEW_LINE> correo = input("Ingrese su correo electronico: ") <NEW_LINE> cadena = "Nombre: %s\nEdad: %d\nCiudad: %s\nPais: %s\nIdioma: %s\nCorreo: %s\n" % (nombre,edad,ciudad,pais,idioma,correo) <NEW_LINE> return cadena
explicación de método, se pide a la persona ingrasar datos por teclado para poder presentar un resumen en pantalla
625941bd60cbc95b062c6445
def run_tornado(settings): <NEW_LINE> <INDENT> from tornado import ioloop, httpserver, wsgi <NEW_LINE> container = wsgi.WSGIContainer(make_application(settings)) <NEW_LINE> http_server = httpserver.HTTPServer(container) <NEW_LINE> http_server.listen(8000) <NEW_LINE> print("Serving on port 8000...") <NEW_LINE> ioloop.IOLoop.instance().start()
Run application using Tornade Web framework WSGI server
625941bd9f2886367277a78b
def getdefaultvalue(self): <NEW_LINE> <INDENT> return self._defaultvalue
Returns the default value for this opt. Subclasses should override this to return a new value if the value type is mutable.
625941bd8e05c05ec3eea26d
def __str__(self): <NEW_LINE> <INDENT> return ''.join(('%\n', ''.join(self._gcodebuf), '%\n'))
Return the complete G code file as a string.
625941bdd8ef3951e3243438
def json2registered(self): <NEW_LINE> <INDENT> fich = open('registered.json', 'w') <NEW_LINE> try: <NEW_LINE> <INDENT> self.Dicc = json.loads(fich) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> fich.close()
Comprobar la existencia del fichero json
625941bd23e79379d52ee462
def allTracks(ln): <NEW_LINE> <INDENT> types1 = ('BASS', 'CHORD', 'ARPEGGIO', 'SCALE', 'DRUM', 'WALK', 'PLECTRUM') <NEW_LINE> types2 = ('MELODY', 'SOLO', 'ARIA') <NEW_LINE> allTypes = types1 + types2 <NEW_LINE> ttypes = [] <NEW_LINE> if len(ln) < 1: <NEW_LINE> <INDENT> error("AllTracks: argument (track?) required") <NEW_LINE> <DEDENT> i = 0 <NEW_LINE> while i < len(ln) and ln[i].upper() in allTypes: <NEW_LINE> <INDENT> ttypes.append(ln[i].upper()) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> if ttypes == []: <NEW_LINE> <INDENT> ttypes = types1 <NEW_LINE> <DEDENT> if i >= len(ln): <NEW_LINE> <INDENT> error("AllTracks: Additional argument (command?) required") <NEW_LINE> <DEDENT> cmd = ln[i].upper() <NEW_LINE> args = i + 1 <NEW_LINE> if not cmd in trackFuncs: <NEW_LINE> <INDENT> error("AllTracks: command '%s' doen't exist" % cmd) <NEW_LINE> <DEDENT> for n in gbl.tnames: <NEW_LINE> <INDENT> if not gbl.tnames[n].vtype in ttypes: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> trackFuncs[cmd](n, ln[args:])
Apply track to all tracks.
625941bd30c21e258bdfa396
def update(self, examples): <NEW_LINE> <INDENT> old_centroid = self.centroid <NEW_LINE> self.examples = examples <NEW_LINE> self.centroid = self.compute_centroid() <NEW_LINE> return old_centroid.distance(self.centroid)
Assume examples is a non-empty list of examples Replace examples; reurns amount centroid has changed
625941bd097d151d1a222d57
def testSymLinkInPath(self): <NEW_LINE> <INDENT> repoADir = os.path.join(self.testDir, 'a') <NEW_LINE> repoBDir = os.path.join(self.testDir, 'b') <NEW_LINE> butler = dp.Butler(outputs=dp.RepositoryArgs( mode='w', mapper=dpTest.EmptyTestMapper, root=repoADir)) <NEW_LINE> tmpDir = tempfile.mkdtemp() <NEW_LINE> os.symlink(tmpDir, repoBDir) <NEW_LINE> butler = dp.Butler(inputs=repoADir, outputs=repoBDir) <NEW_LINE> self.assertIsInstance(butler, dp.Butler) <NEW_LINE> cfg = dp.PosixStorage.getRepositoryCfg(tmpDir) <NEW_LINE> self.assertEqual(repoADir, cfg.parents[0]) <NEW_LINE> cfg = dp.PosixStorage.getRepositoryCfg(repoBDir) <NEW_LINE> self.assertEqual(repoADir, cfg.parents[0])
Test that when a symlink is in an output repo path that the repoCfg stored in the output repo has a parent path from the actual output lcoation to the input repo.
625941bd3617ad0b5ed67df4
def exists(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> if not r.exists(self.key): <NEW_LINE> <INDENT> raise ValueError( "Object %s does not exist in the database." % self.key ) <NEW_LINE> <DEDENT> return f(self, *args, **kwargs) <NEW_LINE> <DEDENT> return wrapper
Raises an exception if the user does not exist.
625941bd30dc7b7665901865
def is_active(self): <NEW_LINE> <INDENT> return self.active
Check if a user entry is currently an Active User @return: True if the User was active, or False if the operation could not complete.
625941bd6aa9bd52df036c9e
def test_perm(): <NEW_LINE> <INDENT> pass
>>> M = [2, 2, 0, 5, 3, 5, 7, 4] >>> M[2] # c is mapped to a 0 >>> sorted(max_perm(M)) [0, 2, 5]
625941bd92d797404e304085
def query_key(self, filename, key, sheet): <NEW_LINE> <INDENT> if not bool(self._template_data_dict) and bool(self._datamap_data_dict): <NEW_LINE> <INDENT> self._set_datamap_and_template_data() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return self._get_value_of_cell_referred_by_key(filename, key, sheet) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> logger.critical( "Unable to process datamapline due to problem with sheet/cellref referred to by datamap" ) <NEW_LINE> raise
Given a filename, key and sheet, raises the value in the spreadsheet. Raises KeyError if any of filename, key and sheet are not in the datamap.
625941bd99cbb53fe6792ae3
def byte_to_string(old_unpacked): <NEW_LINE> <INDENT> if type(old_unpacked) is dict: <NEW_LINE> <INDENT> new_unpacked = {} <NEW_LINE> for old_key, old_value in old_unpacked.items(): <NEW_LINE> <INDENT> new_key=byte_to_string(old_key) <NEW_LINE> new_unpacked[new_key]=byte_to_string(old_unpacked[old_key]) <NEW_LINE> <DEDENT> return new_unpacked <NEW_LINE> <DEDENT> elif type(old_unpacked) is list: <NEW_LINE> <INDENT> new_unpacked=[] <NEW_LINE> for old_value in old_unpacked: <NEW_LINE> <INDENT> new_unpacked.append(byte_to_string(old_value)) <NEW_LINE> <DEDENT> return new_unpacked <NEW_LINE> <DEDENT> elif type(old_unpacked) is bytes: <NEW_LINE> <INDENT> return old_unpacked.decode('utf-8') <NEW_LINE> <DEDENT> elif type(old_unpacked) is str or bool: <NEW_LINE> <INDENT> return old_unpacked <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Argument is of type {}".format(type(old_unpacked)))
Role : Recursively convert bytestrings to strings into all elements of the unpacked message Input : The unpacked message with bytestrings Output : The unpacked message with strings only
625941bd8e71fb1e9831d6a6
def generate_bike_mapping(bike_features): <NEW_LINE> <INDENT> bike_mapping = defaultdict(list) <NEW_LINE> for fid, feat in bike_features.items(): <NEW_LINE> <INDENT> attrs = feat['properties'] <NEW_LINE> bike_infra = attrs['BIKETYP'] or '' <NEW_LINE> bike_there = attrs['BIKETHERE'] <NEW_LINE> if not bike_infra and not bike_there: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> bicycle = None <NEW_LINE> cycleway = None <NEW_LINE> rlis_bicycle = None <NEW_LINE> bike_id = attrs['BIKEID'] <NEW_LINE> if bike_infra in ('BKE-BLVD', 'BKE-SHRD'): <NEW_LINE> <INDENT> cycleway = 'shared_lane' <NEW_LINE> <DEDENT> elif bike_infra in ('BKE-BUFF', 'BKE-LANE'): <NEW_LINE> <INDENT> cycleway = 'lane' <NEW_LINE> <DEDENT> elif bike_infra == 'BKE-TRAK': <NEW_LINE> <INDENT> cycleway = 'track' <NEW_LINE> <DEDENT> elif bike_infra == 'SHL-WIDE': <NEW_LINE> <INDENT> cycleway = 'shoulder' <NEW_LINE> <DEDENT> elif 'OTH-' in bike_infra or bike_there in ('LT', 'MT', 'HT'): <NEW_LINE> <INDENT> bicycle = 'designated' <NEW_LINE> <DEDENT> if bike_there == 'CA': <NEW_LINE> <INDENT> rlis_bicycle = 'caution_area' <NEW_LINE> <DEDENT> feat_info = { 'fid': fid, 'bike_id': bike_id, 'tags': { 'bicycle': bicycle, 'cycleway': cycleway, 'RLIS:bicycle': rlis_bicycle } } <NEW_LINE> local_id = int(str(bike_id)[-6:]) <NEW_LINE> bike_mapping[local_id].append(feat_info) <NEW_LINE> <DEDENT> return bike_mapping
Creates a dictionary that links bike infrastructure to their corresonding features in the streets data set via the relationship between the former's 'BIKEID' and the latter's 'LOCALID'
625941bd57b8e32f52483395
def polyline(off, scl) : <NEW_LINE> <INDENT> if scl != 0 : <NEW_LINE> <INDENT> return np.array([off, scl]) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return np.array([off])
Returns an array representing a linear polynomial. Parameters ---------- off, scl : scalars The "y-intercept" and "slope" of the line, respectively. Returns ------- y : ndarray This module's representation of the linear polynomial ``off + scl*x``. See Also -------- chebline Examples -------- >>> from numpy import polynomial as P >>> P.polyline(1,-1) array([ 1, -1]) >>> P.polyval(1, P.polyline(1,-1)) # should be 0 0.0
625941bdaad79263cf390938
def modifyVPProperty(self, doc_obj_or_list, prop_name, new_value): <NEW_LINE> <INDENT> if App.GuiUp: <NEW_LINE> <INDENT> if type(doc_obj_or_list) is not list: <NEW_LINE> <INDENT> doc_obj_or_list = [doc_obj_or_list] <NEW_LINE> <DEDENT> for doc_obj in doc_obj_or_list: <NEW_LINE> <INDENT> if doc_obj.Document is not self.document: <NEW_LINE> <INDENT> raise ValueError("Document object to be modified does not belong to document TempoVis was made for.") <NEW_LINE> <DEDENT> oldval = getattr(doc_obj.ViewObject, prop_name) <NEW_LINE> setattr(doc_obj.ViewObject, prop_name, new_value) <NEW_LINE> if not self.data.has_key((doc_obj.Name,prop_name)): <NEW_LINE> <INDENT> self.data[(doc_obj.Name,prop_name)] = oldval <NEW_LINE> self.restore_on_delete = True
modifyVPProperty(self, doc_obj_or_list, prop_name, new_value): modifies prop_name property of ViewProvider of doc_obj_or_list, and remembers original value of the property. Original values will be restored upon TempoVis deletion, or call to restore().
625941bd711fe17d8254226c
def __init__( self, *, value: Optional[List["TemplateSpec"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(TemplateSpecsListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None
:keyword value: An array of Template Specs. :paramtype value: list[~azure.mgmt.resource.templatespecs.v2021_03_01_preview.models.TemplateSpec]
625941bd16aa5153ce362374
@wrap(['space', float]) <NEW_LINE> def expm1(space, d): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return space.wrap(math.expm1(d)) <NEW_LINE> <DEDENT> except OverflowError: <NEW_LINE> <INDENT> return space.wrap(rfloat.INFINITY)
Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
625941bd32920d7e50b280c9
def login(self): <NEW_LINE> <INDENT> login_index_url = 'https://gitee.com/login' <NEW_LINE> check_login_url = 'https://gitee.com/check_user_login' <NEW_LINE> form_data = {'user_login': self.username} <NEW_LINE> index_headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;' 'q=0.9,image/webp,image/apng,*/*;' 'q=0.8,application/signed-exchange;v=b3;q=0.9', 'Host': 'gitee.com', 'User-Agent': random.choice(USER_AGENTS) } <NEW_LINE> try: <NEW_LINE> <INDENT> resp = self.session.get(login_index_url, headers=index_headers, timeout=5) <NEW_LINE> csrf_token = self.get_csrf_token(resp.text) <NEW_LINE> headers = { 'Referer': 'https://gitee.com/login', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': csrf_token, 'User-Agent': random.choice(USER_AGENTS) } <NEW_LINE> self.session.post(check_login_url, headers=headers, data=form_data, timeout=5) <NEW_LINE> data = f'{csrf_token}$gitee${self.password}' <NEW_LINE> pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(PUBLIC_KEY.encode()) <NEW_LINE> encrypt_data = rsa.encrypt(data.encode(), pubkey) <NEW_LINE> encrypt_data = base64.b64encode(encrypt_data).decode() <NEW_LINE> form_data = { 'encrypt_key': 'password', 'utf8': '✓', 'authenticity_token': csrf_token, 'redirect_to_url': '', 'user[login]': self.username, 'encrypt_data[user[password]]': encrypt_data, 'user[remember_me]': 1 } <NEW_LINE> resp = self.session.post(login_index_url, headers=index_headers, data=form_data, timeout=5) <NEW_LINE> return '个人主页' in resp.text or '我的工作台' in resp.text <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(f'login error occurred, message: {e}') <NEW_LINE> return False
登录主入口
625941bdc432627299f04b3f
def main(): <NEW_LINE> <INDENT> workspace = os.path.realpath(os.path.dirname(__file__)) <NEW_LINE> config_file = os.path.join(workspace, "config.json") <NEW_LINE> ztock.run(config_file) <NEW_LINE> return
Reads config, creates trader and runs trading function continuously at configured time intervals.
625941bddd821e528d63b0a6
def _build_config(salt_id, parent, this, state_stack): <NEW_LINE> <INDENT> buf = cStringIO.StringIO() <NEW_LINE> deepness = len(state_stack) - 1 <NEW_LINE> indent = '{0}'.format(deepness * ' ') <NEW_LINE> if _is_statement(parent, this): <NEW_LINE> <INDENT> _build_statement(salt_id, parent, this, indent, buf, state_stack) <NEW_LINE> <DEDENT> elif _is_reference(parent, this, state_stack): <NEW_LINE> <INDENT> print('{0}{1}({2});'.format(indent, parent, this), file=buf, end='') <NEW_LINE> <DEDENT> elif _is_options(parent, this, state_stack): <NEW_LINE> <INDENT> _build_options(salt_id, parent, this, indent, buf, state_stack) <NEW_LINE> <DEDENT> elif _are_parameters(this, state_stack): <NEW_LINE> <INDENT> _build_parameters(salt_id, parent, this, buf, state_stack) <NEW_LINE> <DEDENT> elif _is_simple_parameter(this, state_stack): <NEW_LINE> <INDENT> return _build_simple_parameter(this, indent) <NEW_LINE> <DEDENT> elif _is_complex_parameter(this, state_stack): <NEW_LINE> <INDENT> return _build_complex_parameter(salt_id, this, indent, state_stack) <NEW_LINE> <DEDENT> elif _is_list_parameter(this, state_stack): <NEW_LINE> <INDENT> return ', '.join(this) <NEW_LINE> <DEDENT> elif _is_string_parameter(this, state_stack): <NEW_LINE> <INDENT> return _build_string_parameter(this) <NEW_LINE> <DEDENT> elif _is_int_parameter(this, state_stack): <NEW_LINE> <INDENT> return str(this) <NEW_LINE> <DEDENT> elif _is_boolean_parameter(this, state_stack): <NEW_LINE> <INDENT> return 'no' if this else 'yes' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('{0}# BUG, please report to the syslog-ng mailing list: syslog-ng@lists.balabit.hu'.format(indent), file=buf, end='') <NEW_LINE> raise SyslogNgError('Unhandled case while generating configuration from YAML to syslog-ng format') <NEW_LINE> <DEDENT> buf.seek(0) <NEW_LINE> return buf.read()
Builds syslog-ng configuration from a parsed YAML document. It maintains a state_stack list, which represents the current position in the configuration tree. The last value in the state_stack means: 0: in the root or in a statement 1: in an option 2: in a parameter 3: in a parameter of a parameter Returns the built config.
625941bd55399d3f055885af
def main(): <NEW_LINE> <INDENT> global yc, tb, tm, tc <NEW_LINE> app = QApplication(sys.argv) <NEW_LINE> yc = YourClips() <NEW_LINE> QApplication.setQuitOnLastWindowClosed(False) <NEW_LINE> yc.setWindowFlags(Qt.FramelessWindowHint) <NEW_LINE> yc.setWindowFlags(Qt.WindowStaysOnTopHint) <NEW_LINE> yc.setWindowFlags(Qt.Tool) <NEW_LINE> tm = threading.Thread(target = listenMouse) <NEW_LINE> tb = threading.Thread(target = listenBoard) <NEW_LINE> tc = threading.Thread(target = timerCheck) <NEW_LINE> tm.start() <NEW_LINE> tb.start() <NEW_LINE> tc.start() <NEW_LINE> print('--- 程序初始化成功,进入事件循环 ---\n') <NEW_LINE> sys.exit(app.exec_())
主函数:创建了Qt主程序,创建了监听剪贴板、鼠标移动、键盘输入线程,并启动
625941bd4e4d5625662d42d7
@app.route('/addmember', methods=['POST']) <NEW_LINE> def add_user(): <NEW_LINE> <INDENT> email = request.form.get("email") <NEW_LINE> password = request.form.get("password") <NEW_LINE> hash_pw = bcrypt.generate_password_hash(password, 10).decode("utf-8") <NEW_LINE> fname = request.form.get("fname") <NEW_LINE> lname = request.form.get("lname") <NEW_LINE> language = request.form.get("language") <NEW_LINE> new_user = User(email=email, password=hash_pw, fname=fname, lname=lname, language=language) <NEW_LINE> db.session.add(new_user) <NEW_LINE> db.session.commit() <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> if 'file' in request.files: <NEW_LINE> <INDENT> file = request.files['file'] <NEW_LINE> if file.filename != '': <NEW_LINE> <INDENT> if file and allowed_file(file.filename): <NEW_LINE> <INDENT> filename = secure_filename( "{}.jpg".format(new_user.user_id)) <NEW_LINE> file.save(os.path.join( app.config['UPLOAD_FOLDER'], filename)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return redirect("/feedpage")
Process registration. Add registered user to database.
625941bdc4546d3d9de7292d
def concatHMMs(hmmmodels, namelist): <NEW_LINE> <INDENT> final_startprob = hmmmodels[namelist[0]]['startprob'][:-1] <NEW_LINE> single_num_states = hmmmodels[namelist[0]]['startprob'].shape[0] <NEW_LINE> final_num_states = len(namelist) * (single_num_states - 1) + 1 <NEW_LINE> final_transmat = np.zeros((final_num_states, final_num_states)) <NEW_LINE> final_means = hmmmodels[namelist[0]]['means'] <NEW_LINE> final_covars = hmmmodels[namelist[0]]['covars'] <NEW_LINE> for i in range(0, len(namelist)): <NEW_LINE> <INDENT> start = i * (single_num_states - 1) <NEW_LINE> end = start + single_num_states <NEW_LINE> final_transmat[start:end, start:end] = hmmmodels[namelist[i]]['transmat'] <NEW_LINE> if (i != 0): <NEW_LINE> <INDENT> final_means = np.vstack((final_means, hmmmodels[namelist[i]]['means'])) <NEW_LINE> final_covars = np.vstack((final_covars, hmmmodels[namelist[i]]['covars'])) <NEW_LINE> final_startprob = np.concatenate((final_startprob, hmmmodels[namelist[i]]['startprob'][:-1])) <NEW_LINE> <DEDENT> <DEDENT> final_startprob = np.log(final_startprob) <NEW_LINE> final_transmat = np.log(final_transmat[:-1, :-1]) <NEW_LINE> combinedhmm = {'name': namelist, 'means': final_means, 'startprob': final_startprob, 'covars': final_covars, 'transmat': final_transmat} <NEW_LINE> return combinedhmm
Concatenates HMM models in a left to right manner Args: hmmmodels: list of dictionaries with the following keys: name: phonetic or word symbol corresponding to the model startprob: M+1 array with priori probability of state transmat: (M+1)x(M+1) transition matrix means: MxD array of mean vectors covars: MxD array of variances namelist: list of model names that we want to concatenate D is the dimension of the feature vectors M is the number of states in each HMM model (could be different for each) Output combinedhmm: dictionary with the same keys as the input but combined models Example: wordHMMs['o'] = concatHMMs(phoneHMMs, ['sil', 'ow', 'sil'])
625941bdde87d2750b85fc8b
def short(self): <NEW_LINE> <INDENT> if self.value == 1: <NEW_LINE> <INDENT> desc = "P" <NEW_LINE> <DEDENT> elif self.value == 2: <NEW_LINE> <INDENT> desc = "T" <NEW_LINE> <DEDENT> elif self.value == 3: <NEW_LINE> <INDENT> desc = "Z" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> desc = "R" <NEW_LINE> <DEDENT> return desc
Return first letter of race.
625941bd66656f66f7cbc0a6
def ispython(object): <NEW_LINE> <INDENT> pyclass = 0 <NEW_LINE> pycode = 0 <NEW_LINE> pyinstance = 0 <NEW_LINE> if inspect.isclass(object): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> object.__doc__ <NEW_LINE> pyclass = 1 <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pyclass = 0 <NEW_LINE> <DEDENT> <DEDENT> elif inspect.ismethod(object): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> object.__str__ <NEW_LINE> pycode = 1 <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pycode = 0 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> object.__str__ <NEW_LINE> pyinstance = 1 <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pyinstance = 0 <NEW_LINE> <DEDENT> <DEDENT> return pyclass | pycode | pyinstance
Figure out if this is Python code or Java code..
625941bd851cf427c661a40e
def print_right_to_left(root: Node, level: int): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if level == 1: <NEW_LINE> <INDENT> print(root.data, end=" ") <NEW_LINE> <DEDENT> elif level > 1: <NEW_LINE> <INDENT> print_right_to_left(root.right, level - 1) <NEW_LINE> print_right_to_left(root.left, level - 1)
Print elements on particular level from right to left direction of the binary tree. >>> print_right_to_left(make_tree(), 2) 3 2
625941bd4428ac0f6e5ba6ed
def _traverse(self, node): <NEW_LINE> <INDENT> if not self._istraversable(node): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._enter(node) <NEW_LINE> for next in self._next(node): <NEW_LINE> <INDENT> self._traverse(next) <NEW_LINE> <DEDENT> self._exit(node)
The internal node traversal operation. @param node The current node in the traversal
625941bdf8510a7c17cf95f7
def _get_user_queryset_from_officer(user): <NEW_LINE> <INDENT> return User.objects.filter(groups__in=[b.group for b in user.c4cuser.get_administrated_branches()])
Return a queryset asking for all the users that the officer can moderate
625941bdcc0a2c11143dcd8c
def nickname(): <NEW_LINE> <INDENT> return "SmartBC"
Returns the nickname of this baroque chess agent.
625941bdbde94217f3682cf0
def send(self, send_data): <NEW_LINE> <INDENT> if hasattr(self, 'sock') == False or self.sock is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if hasattr(self, 'clientsock') == False or self.clientsock is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if type(send_data) == str: <NEW_LINE> <INDENT> self.clientsock.send(send_data.encode() + self.buf_split) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.clientsock.send(send_data + self.buf_split) <NEW_LINE> <DEDENT> <DEDENT> except ConnectionAbortedError: <NEW_LINE> <INDENT> return
送信処理
625941bd462c4b4f79d1d5cc
def dubins_segment(t,qi,segment,alt): <NEW_LINE> <INDENT> st = math.sin(qi[3]) <NEW_LINE> ct = math.cos(qi[3]) <NEW_LINE> if segment == seg_type["L_SEG"]: <NEW_LINE> <INDENT> qt= (math.sin(qi[3]+t) - st, -math.cos(qi[3]+t) + ct, alt*t, t) <NEW_LINE> <DEDENT> elif segment == seg_type["R_SEG"]: <NEW_LINE> <INDENT> qt = (-math.sin(qi[3]-t) + st, math.cos(qi[3]-t) - ct, alt*t, -t) <NEW_LINE> <DEDENT> elif segment == seg_type["S_SEG"]: <NEW_LINE> <INDENT> qt = (ct*t, st*t, alt*t, 0.0) <NEW_LINE> <DEDENT> qt = (qt[0] + qi[0], qt[1] + qi[1], qt[2] + qi[2], qt[3] + qi[3]) <NEW_LINE> return qt
Paramaters t: StepSize qi: Initial coords segment: Current segment type of dubins path
625941bd5f7d997b87174991
def run_game(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> <DEDENT> self.screen.fill(self.settings.bg_color) <NEW_LINE> pygame.display.flip()
Main loop for the game
625941bd3eb6a72ae02ec3d1
def walk_albums(self, ltype, size=None, fromYear=None,toYear=None, genre=None, offset=None): <NEW_LINE> <INDENT> if ltype == 'byGenre' and genre is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if ltype == 'byYear' and (fromYear is None or toYear is None): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> response = self.getAlbumList2( ltype=ltype, size=size, fromYear=fromYear, toYear=toYear,genre=genre, offset=offset) <NEW_LINE> if not response["albumList2"]["album"]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for album in response["albumList2"]["album"]: <NEW_LINE> <INDENT> yield album
(ID3 tags) Request all albums for a given genre and iterate over each album.
625941bd009cb60464c632b0
def merge(repo, node, force=None, remind=True, mergeforce=False): <NEW_LINE> <INDENT> stats = mergemod.update(repo, node, True, force, mergeforce=mergeforce) <NEW_LINE> _showstats(repo, stats) <NEW_LINE> if stats[3]: <NEW_LINE> <INDENT> repo.ui.status(_("use 'hg resolve' to retry unresolved file merges " "or 'hg update -C .' to abandon\n")) <NEW_LINE> <DEDENT> elif remind: <NEW_LINE> <INDENT> repo.ui.status(_("(branch merge, don't forget to commit)\n")) <NEW_LINE> <DEDENT> return stats[3] > 0
Branch merge with node, resolving changes. Return true if any unresolved conflicts.
625941bd507cdc57c6306bd0
def test_heading_negative(self): <NEW_LINE> <INDENT> first = Position(0, 0, 0) <NEW_LINE> second = Position(-1, 0, 0) <NEW_LINE> self.assertTrue(first.heading(second) >= 0)
Headings shouldn't be negative. Well, they can be, technically, but in Bravo, they should be clamped to the unit circle.
625941bd3c8af77a43ae369a
def getTime(self) -> float: <NEW_LINE> <INDENT> return (self._get_time() - self._startTime) / 1e6
Returns the time in seconds since the watchdog was last fed.
625941bdb830903b967e9809
def metadata_modify_result_table(self, table_id, table_name_zh, field_list, operator="admin", default_storage="influxdb"): <NEW_LINE> <INDENT> kwargs = { "bk_token": self.bk_token, "table_id": table_id, "operator": operator, "field_list": field_list, "table_name_zh": table_name_zh, "default_storage": default_storage } <NEW_LINE> data = self.client.monitor.metadata_modify_result_table(kwargs) <NEW_LINE> result = {"result": False, "message": "nothing", "data": {}} <NEW_LINE> if data.get("result", False): <NEW_LINE> <INDENT> result['result'] = data['result'] <NEW_LINE> result['data'] = data['data'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.warning( f"{get_now_time()} 修改监控结果表失败:{data['message']} 接口名称(metadata_modify_result_table) 请求参数({kwargs}) 返回参数({data})") <NEW_LINE> <DEDENT> result['message'] = data['message'] <NEW_LINE> return result
修改监控结果表 :param table_id:string 是 结果表ID,格式应该为 库.表(例如,system.cpu) :param table_name_zh:string 是 结果表中文名 :param operator:string 是 操作者 :param default_storage:string 是 默认存储类型,目前支持influxdb :param field_list:array 否 字段信息,数组元素为dict,例:field_name(字段名), field_type(字段类型), tag(字段类型, metirc -- 指标, dimension -- 维度) :return:result
625941bd76d4e153a657ea2c
def isOneBitCharacter(self, bits): <NEW_LINE> <INDENT> if len(bits) <= 2: <NEW_LINE> <INDENT> return bits[0] != 1 <NEW_LINE> <DEDENT> if bits[-2] == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> s = [False] * (len(bits)) <NEW_LINE> s[0] = (bits[0]==0) <NEW_LINE> s[1] = not (bits[0]==0 and bits[1] ==1) <NEW_LINE> for i in range(2, len(s)): <NEW_LINE> <INDENT> if bits[i] == 1: <NEW_LINE> <INDENT> if bits[i-1] == 1: <NEW_LINE> <INDENT> s[i] = s[i-2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s[i] = False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if bits[i-1] == 1: <NEW_LINE> <INDENT> s[i] = s[i-2] or s[i-1] <NEW_LINE> <DEDENT> if bits[i-1] == 0: <NEW_LINE> <INDENT> s[i] = s[i-1] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return s[i-1] and not s[i-2]
:type bits: List[int] :rtype: bool
625941bda8ecb033257d2fcb
def load_frame(file_path): <NEW_LINE> <INDENT> with Image.open(file_path) as img: <NEW_LINE> <INDENT> img_arr = np.array(img) <NEW_LINE> <DEDENT> data = dk.sessions.parse_img_filepath(file_path) <NEW_LINE> return img_arr, data
Retrieve an image and its telemetry data.
625941bd5510c4643540f2e7
def remove_ds_instance(dirsrv): <NEW_LINE> <INDENT> _log = dirsrv.log.getChild('remove_ds') <NEW_LINE> _log.debug("Removing instance %s" % dirsrv.serverid) <NEW_LINE> _log.debug("Stopping instance %s" % dirsrv.serverid) <NEW_LINE> dirsrv.stop() <NEW_LINE> remove_paths = {} <NEW_LINE> remove_paths['backup_dir'] = dirsrv.ds_paths.backup_dir <NEW_LINE> remove_paths['cert_dir'] = dirsrv.ds_paths.cert_dir <NEW_LINE> remove_paths['config_dir'] = dirsrv.ds_paths.config_dir <NEW_LINE> remove_paths['db_dir'] = dirsrv.ds_paths.db_dir <NEW_LINE> remove_paths['changelogdb_dir'] = dirsrv.get_changelog_dir() <NEW_LINE> remove_paths['ldif_dir'] = dirsrv.ds_paths.ldif_dir <NEW_LINE> remove_paths['lock_dir'] = dirsrv.ds_paths.lock_dir <NEW_LINE> remove_paths['log_dir'] = dirsrv.ds_paths.log_dir <NEW_LINE> marker_path = "%s/sysconfig/dirsrv-%s" % (dirsrv.ds_paths.sysconf_dir, dirsrv.serverid) <NEW_LINE> _log.debug("Checking for instance marker at %s" % marker_path) <NEW_LINE> assert os.path.exists(marker_path) <NEW_LINE> config_dir = dirsrv.ds_paths.config_dir <NEW_LINE> config_dir_rm = "{}.removed".format(config_dir) <NEW_LINE> if os.path.exists(config_dir_rm): <NEW_LINE> <INDENT> _log.debug("Removing previously existed %s" % config_dir_rm) <NEW_LINE> shutil.rmtree(config_dir_rm) <NEW_LINE> <DEDENT> _log.debug("Copying %s to %s" % (config_dir, config_dir_rm)) <NEW_LINE> try: <NEW_LINE> <INDENT> shutil.copytree(config_dir, config_dir_rm) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for path_k in remove_paths: <NEW_LINE> <INDENT> _log.debug("Removing %s" % remove_paths[path_k]) <NEW_LINE> shutil.rmtree(remove_paths[path_k], ignore_errors=True) <NEW_LINE> <DEDENT> os.remove(marker_path) <NEW_LINE> _log.debug("Removing %s" % marker_path) <NEW_LINE> _log.debug("Removing the systemd symlink") <NEW_LINE> subprocess.check_call(["systemctl", "disable", "dirsrv@{}".format(dirsrv.serverid)]) <NEW_LINE> _log.debug("Complete")
This will delete the instance as it is define. This must be a local instance.
625941bd9b70327d1c4e0cd0
def process_response(self, request, response, spider): <NEW_LINE> <INDENT> re_match = re.match('.*?/utrack/verify.*', response.url) <NEW_LINE> if re_match: <NEW_LINE> <INDENT> url = re_match.group(0) <NEW_LINE> spider.browser.get(url) <NEW_LINE> while True: <NEW_LINE> <INDENT> selector = Selector(text=spider.browser.page_source) <NEW_LINE> captcha_url = selector.css('#captcha::attr(src)').extract_first('') <NEW_LINE> if not captcha_url: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> captcha_url = "https://www.lagou.com" + captcha_url <NEW_LINE> image = requests.get(captcha_url) <NEW_LINE> chaojiying = Chaojiying_Client('Yanxueshan', 'lingtian..1021', '898966') <NEW_LINE> result = chaojiying.PostPic(image.content, 1005)['pic_str'] <NEW_LINE> spider.browser.find_element_by_css_selector("#code").send_keys(result) <NEW_LINE> spider.browser.find_element_by_css_selector("#submit").click() <NEW_LINE> return HtmlResponse(url=spider.browser.current_url, body=spider.browser.page_source, encoding="utf-8", request=request) <NEW_LINE> <DEDENT> <DEDENT> return response
对拉勾网重定向302的解决,捕捉到302URL,然后进行处理
625941bd5fcc89381b1e15b9
@mod.route('/get_rec_as_json', methods=['GET']) <NEW_LINE> @mod.route('/get_rec_as_json/', methods=['GET']) <NEW_LINE> @mod.route('/get_rec_as_json/<int:rec_id>/', methods=['GET']) <NEW_LINE> def get_rec_as_json(rec_id=None): <NEW_LINE> <INDENT> import json <NEW_LINE> out = '' <NEW_LINE> rec_id = cleanRecordID(rec_id) <NEW_LINE> rec = Client(g.db).get(rec_id) <NEW_LINE> if rec: <NEW_LINE> <INDENT> out = json.dumps(rec._asdict()) <NEW_LINE> out = out.replace('null','" "') <NEW_LINE> <DEDENT> return out
Return a json object with the requested client data or the empty string
625941bd8e05c05ec3eea26e
def _determine_log_level(self, args): <NEW_LINE> <INDENT> if CLILogging.ONLY_SHOW_ERRORS_FLAG in args: <NEW_LINE> <INDENT> if CLILogging.DEBUG_FLAG in args or CLILogging.VERBOSE_FLAG in args: <NEW_LINE> <INDENT> raise CLIError("--only-show-errors can't be used together with --debug or --verbose") <NEW_LINE> <DEDENT> self.cli_ctx.only_show_errors = True <NEW_LINE> return CliLogLevel.ERROR <NEW_LINE> <DEDENT> if CLILogging.DEBUG_FLAG in args: <NEW_LINE> <INDENT> self.cli_ctx.only_show_errors = False <NEW_LINE> return CliLogLevel.DEBUG <NEW_LINE> <DEDENT> if CLILogging.VERBOSE_FLAG in args: <NEW_LINE> <INDENT> self.cli_ctx.only_show_errors = False <NEW_LINE> return CliLogLevel.INFO <NEW_LINE> <DEDENT> if self.cli_ctx.only_show_errors: <NEW_LINE> <INDENT> return CliLogLevel.ERROR <NEW_LINE> <DEDENT> return CliLogLevel.WARNING
Get verbose level by reading the arguments.
625941bd5166f23b2e1a5055
def t_rblock_RSTART(self, t): <NEW_LINE> <INDENT> t.lexer.rblock_level += 1
\{\%
625941bd7d43ff24873a2b9a
def outer_xml(self) -> str: <NEW_LINE> <INDENT> self._check_vanished() <NEW_LINE> return self._elem.toOuterXml()
Get the full HTML representation of this element.
625941bd090684286d50ebde
def write_test_file(description, chain, trusted_certs, utc_time, verify_result): <NEW_LINE> <INDENT> test_data = '[Created by: %s]\n\n%s\n' % (sys.argv[0], description) <NEW_LINE> for cert in chain: <NEW_LINE> <INDENT> test_data += '\n' + cert.get_cert_pem() <NEW_LINE> <DEDENT> for cert in trusted_certs: <NEW_LINE> <INDENT> cert_data = cert.get_cert_pem() <NEW_LINE> cert_data = cert_data.replace('CERTIFICATE', 'TRUSTED_CERTIFICATE') <NEW_LINE> test_data += '\n' + cert_data <NEW_LINE> <DEDENT> test_data += '\n' + data_to_pem('TIME', utc_time) <NEW_LINE> verify_result_string = 'SUCCESS' if verify_result else 'FAIL' <NEW_LINE> test_data += '\n' + data_to_pem('VERIFY_RESULT', verify_result_string) <NEW_LINE> write_string_to_file(test_data, g_out_pem)
Writes a test file that contains all the inputs necessary to run a verification on a certificate chain
625941bd63b5f9789fde6fe2
def __init__(self, model, name=None): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.X = self.model.X <NEW_LINE> self.y = self.model.y <NEW_LINE> self.n, self.k = np.shape(self.X) <NEW_LINE> self.predict_list, self.predict_varr, self.scvr = [], [], [] <NEW_LINE> self.name = name
X- sampling plane y- Objective function evaluations name- the name of the model
625941bd50485f2cf553cc95
def calc_breathing(rrlist, hrdata, sample_rate, measures={}, working_data={}): <NEW_LINE> <INDENT> x = np.linspace(0, len(rrlist), len(rrlist)) <NEW_LINE> x_new = np.linspace(0, len(rrlist), len(rrlist)*10) <NEW_LINE> interp = UnivariateSpline(x, rrlist, k=3) <NEW_LINE> breathing = interp(x_new) <NEW_LINE> breathing_rolmean = rolmean(breathing, 0.75, sample_rate) <NEW_LINE> peaks, working_data = detect_peaks(breathing, breathing_rolmean, 1, sample_rate, update_dict=False) <NEW_LINE> if len(peaks) > 1: <NEW_LINE> <INDENT> signaltime = len(hrdata) / sample_rate <NEW_LINE> measures['breathingrate'] = len(peaks) / signaltime <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> measures['breathingrate'] = np.nan <NEW_LINE> <DEDENT> return measures
function to estimate breathing rate from heart rate signal. Upsamples the list of detected rr_intervals by interpolation then tries to extract breathing peaks in the signal. keyword arguments: sample_rate -- sample rate of the heart rate signal
625941bdcc40096d6159584e
def test_can_see_puck(self): <NEW_LINE> <INDENT> for _ in range(10): <NEW_LINE> <INDENT> self.half_ice_rink.set_random_positions_for_agents() <NEW_LINE> orig_pos = copy(self.half_ice_rink.puck.pos) <NEW_LINE> for player in self.half_ice_rink.defense + self.half_ice_rink.attack: <NEW_LINE> <INDENT> self.move_puck_to(player.pos) <NEW_LINE> self.assertTrue(player.can_see_puck()) <NEW_LINE> self.move_puck_to(orig_pos) <NEW_LINE> self.move_puck_to(player.__pt_in_front_of_me__()) <NEW_LINE> self.assertTrue(player.can_see_puck()) <NEW_LINE> self.move_puck_to(orig_pos)
'Seeing' the puck works?
625941bd56ac1b37e62640d1
def test_user_cant_create_records_in_other_domains(self): <NEW_LINE> <INDENT> request = self.u_client.post( reverse('record-list'), { 'name': 'site.u.example.com', 'content': '192.168.1.4', 'type': 'A', 'domain': get_domain_url(self.su_domain), 'auto_ptr': AutoPtrOptions.NEVER.id, }, ) <NEW_LINE> self.assertEqual(request.status_code, 400)
Normal user can't create records in domain she doesn't own.
625941bd1d351010ab855a19
def optimizer_func(): <NEW_LINE> <INDENT> return fluid.optimizer.AdagradOptimizer( learning_rate=3e-3, regularization=fluid.regularizer.L2DecayRegularizer(8e-4))
optimizer function
625941bd435de62698dfdb4f
def get_queue(sqs, logger, q_name: str): <NEW_LINE> <INDENT> logger.debug('in get SQS url') <NEW_LINE> try: <NEW_LINE> <INDENT> response = sqs.get_queue_url(QueueName=q_name) <NEW_LINE> <DEDENT> except Exception as exp: <NEW_LINE> <INDENT> logger.error('get_queue_url failed due to: {}'.format(exp)) <NEW_LINE> raise ClientError('no sqs url') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug('queue url get response: {}'.format(response)) <NEW_LINE> if response['ResponseMetadata']['HTTPStatusCode'] != 200: <NEW_LINE> <INDENT> raise ClientError('get sqs url: HTTPStatus != 200') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> response['QueueUrl'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ClientError('no sqs queue url returned {}'.format(response)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = response['QueueUrl'] <NEW_LINE> logger.info('sqs url: {}'.format(response['QueueUrl'])) <NEW_LINE> <DEDENT> <DEDENT> return url
get an AWS SQS url synchronously, async version below Throws a ClientError exception if the HTTP Status is not 200 or there is not a Key:Value pair containing the Q url :param sqs: aws sqs client :param q_name: str: the name of the sqs Q :return: the q url
625941bd24f1403a92600a65
def load_pictures_from_file(filename='d_pet_pictures.txt', nb_lines=-1): <NEW_LINE> <INDENT> with open(filename, 'r') as file: <NEW_LINE> <INDENT> lines = file.readlines() <NEW_LINE> <DEDENT> pictures = lines[1:] if nb_lines == -1 else lines[1:nb_lines + 1] <NEW_LINE> return [picture.rstrip().split(' ') for picture in pictures]
Load pictures from Kaggle file
625941bd01c39578d7e74d37
def get_bookmarks(self, updateSequenceNum): <NEW_LINE> <INDENT> user = self.get_current_user()['upn'] <NEW_LINE> bookmarks_db = BookmarksDB(self.settings['user_dir'], user) <NEW_LINE> if updateSequenceNum: <NEW_LINE> <INDENT> updateSequenceNum = int(updateSequenceNum) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> updateSequenceNum = 0 <NEW_LINE> <DEDENT> updated_bookmarks = bookmarks_db.get_bookmarks(updateSequenceNum) <NEW_LINE> message = {'bookmarks_updated': updated_bookmarks} <NEW_LINE> self.write_message(json_encode(message))
Returns a JSON-encoded list of bookmarks updated since the last *updateSequenceNum*. If *updateSequenceNum* resolves to False, all bookmarks will be sent to the client.
625941bd8a349b6b435e8070
def test_func_get_file_time_stamp_for_good_case(self): <NEW_LINE> <INDENT> str_env = os.path.join(self.str_test_directory, "test_func_get_file_time_stamp_for_good_case") <NEW_LINE> self.func_make_dummy_dir(str_env) <NEW_LINE> str_product_1 = os.path.join(str_env, "product_1.txt") <NEW_LINE> self.func_make_dummy_file(str_product_1) <NEW_LINE> os.utime(str_product_1, (1441214830.0,1441214830.0)) <NEW_LINE> pipe_cur = Pipeline.Pipeline("test_func_get_file_time_stamp_for_good_case") <NEW_LINE> d_stamp = pipe_cur.func_get_file_time_stamp(str_product_1) <NEW_LINE> self.func_remove_files([str_product_1]) <NEW_LINE> self.func_remove_dirs([str_env]) <NEW_LINE> self.func_test_equals(1441214830.0, d_stamp)
Make sure we are reading in the time stamp correctly
625941bd7d847024c06be1b5