code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def draw_string(self, img, x_pos, y_pos, text, color): <NEW_LINE> <INDENT> prev_char = 0 <NEW_LINE> pen = freetype.Vector() <NEW_LINE> pen.x = x_pos << 6 <NEW_LINE> pen.y = y_pos << 6 <NEW_LINE> hscale = 1.0 <NEW_LINE> matrix = freetype.Matrix(int(hscale)*0x10000, int(0.2*0x10000), int(0...
draw string :param x_pos: text x-postion on img :param y_pos: text y-postion on img :param text: text (unicode) :param color: text color :return: image
625941bf507cdc57c6306c04
def test_gist_without_filename(self): <NEW_LINE> <INDENT> self.setHtmlFromRst(self.sample_without_filename) <NEW_LINE> output = 'https://gist.github.com/fake_id2.js' <NEW_LINE> self.assertHTMLContains("script", attributes={"src": output}) <NEW_LINE> self.assertHTMLContains("pre", text="raw_gist")
Test the gist directive without filename
625941bf21bff66bcd684884
def test_api_failure_on_docker_memory_limit(self): <NEW_LINE> <INDENT> response = Mock(status_code=500, reason='Internal Server Error') <NEW_LINE> self.mocks.configure_mock( 'docker_client', { 'exec_create.side_effect': DockerAPIError( 'Failure creating container', response, 'Failure creating container'), }) <NEW_LINE>...
Docker exec_create raised memory issue on `exec`
625941bf3346ee7daa2b2c99
def process_or_validate_classifier_output_features( output_features, class_labels, supports_class_scores=True ): <NEW_LINE> <INDENT> def raise_error(msg): <NEW_LINE> <INDENT> raise ValueError("Classifier error: %s" % msg) <NEW_LINE> <DEDENT> class_labels = list(class_labels) <NEW_LINE> _int_types = _integer_types + (bo...
Given a list of class labels and a list of output_features, validate the list and return a valid version of output_features with all the correct data type information included.
625941bf2ae34c7f2600d061
def update(self, instance, validated_data): <NEW_LINE> <INDENT> instance.role_id = validated_data.get('role_id', instance.role_id) <NEW_LINE> instance.role_name = validated_data.get('role_name', instance.role_name) <NEW_LINE> instance.activity = validated_data.get('activity', instance.activity) <NEW_LINE> instance.save...
Update and return an existing `Role` instance, given the validated data.
625941bf046cf37aa974cc79
def create_or_update_availabilityset(self): <NEW_LINE> <INDENT> self.log("Creating availabilityset {0}".format(self.name)) <NEW_LINE> try: <NEW_LINE> <INDENT> params_sku = self.compute_models.Sku( name=self.sku ) <NEW_LINE> params = self.compute_models.AvailabilitySet( location=self.location, tags=self.tags, platform_u...
Method calling the Azure SDK to create or update the AS. :return: void
625941bf82261d6c526ab3cb
def add(self, additionalSel): <NEW_LINE> <INDENT> for cut in additionalSel.cuts: <NEW_LINE> <INDENT> self.cuts.append(cut) <NEW_LINE> <DEDENT> self._filter=None
add all cuts defined in a different filter to this one
625941bf0383005118ecf513
def create_release_branch(old, new): <NEW_LINE> <INDENT> LOGGER.info("Bumping version from %s to %s", old, new) <NEW_LINE> run_cmd("git push --all origin") <NEW_LINE> run_cmd(f"git flow release start {new}") <NEW_LINE> with open(SETUP_PY_PATH, encoding="UTF-8") as f: <NEW_LINE> <INDENT> setup_file = f.readlines() <NEW_...
Creates (and completes!) a release branch with the new release number Args: old (str): the old release number (x.y.z) new (str): the new release number (x.y.z)
625941bf7d43ff24873a2bcd
def validate_request(query: str) -> List[str]: <NEW_LINE> <INDENT> request_categories = query.split(DELIMITER) <NEW_LINE> if len(request_categories) == 0 or any( len(cat.strip()) == 0 for cat in request_categories ): <NEW_LINE> <INDENT> raise FeedIndexerError( f"Invalid archive specification '{query}'. Correct format i...
Validate the provided archive/category specification. Return a list of its named archives and categories. Parameters ---------- query : str A concatenation of archive/category specifiers separated by delimiter characters. Raises ------ RssIndexerError If the provided archive string is malformed or specif...
625941bf099cdd3c635f0b8c
def clickProject3(self): <NEW_LINE> <INDENT> self.elementClick(locator="//img[@alt='" + self._project3 + "']//parent::div", locatorType="xpath")
Click the project 3 box that is still under development :return:
625941bf6fb2d068a760efca
def mean(spec, x1, x2): <NEW_LINE> <INDENT> bin1 = bin(spec, x1) <NEW_LINE> bin2 = bin(spec, x2) <NEW_LINE> if bin1 == bin2 or x2 == (spec.x + spec.step / 2)[-1]: <NEW_LINE> <INDENT> return spec.y[bin1], spec.v[bin1] <NEW_LINE> <DEDENT> binbetween = range(bin1[0][0] + 1, bin2[0][0]) <NEW_LINE> flux1 = spec.y[bin1] * ((...
Compute a mean value bewteen x1 and x1. Compute the integral of the flux over the wavelength range defined as [x1,x2] divided by the wavelength range in order to get a flux / wavelength. the variance of this quantity is returned as a 2nd parameter Raises ValueError if the spec range soesn't cover the intended bin widt...
625941bf9f2886367277a7bf
def get_access_key(): <NEW_LINE> <INDENT> return get_config_handler().get_access_key()
Return the access key for the account user.
625941bfde87d2750b85fcbf
@executions.command(name='resume', short_help='Resume a stopped execution') <NEW_LINE> @aria.argument('execution-id') <NEW_LINE> @aria.options.dry_execution <NEW_LINE> @aria.options.retry_failed_tasks <NEW_LINE> @aria.options.mark_pattern() <NEW_LINE> @aria.options.verbose() <NEW_LINE> @aria.pass_model_storage <NEW_LIN...
Resume a stopped execution EXECUTION_ID is the unique ID of the execution.
625941bf8e05c05ec3eea2a2
def union(self, rdds): <NEW_LINE> <INDENT> first_jrdd_deserializer = rdds[0]._jrdd_deserializer <NEW_LINE> if any(x._jrdd_deserializer != first_jrdd_deserializer for x in rdds): <NEW_LINE> <INDENT> rdds = [x._reserialize() for x in rdds] <NEW_LINE> <DEDENT> first = rdds[0]._jrdd <NEW_LINE> rest = [x._jrdd for x in rdds...
Build the union of a list of RDDs. This supports unions() of RDDs with different serialized formats, although this forces them to be reserialized using the default serializer: >>> path = os.path.join(tempdir, "union-text.txt") >>> with open(path, "w") as testFile: ... testFile.write("Hello") >>> textFile = sc.text...
625941bf287bf620b61d3995
def parse_stack(st): <NEW_LINE> <INDENT> return u'%s(%d).%s' % (os.path.basename(st[1]), st[2], st[3])
desc: Generates a nice looking stacktrace for a single item. arguments: st: A stacktrace item. returns: A string for the stacktrace item.
625941bf30dc7b7665901898
def test_st1(self): <NEW_LINE> <INDENT> self.driver.get(os.path.join(self.base_url, 'register')) <NEW_LINE> time.sleep(WAIT_TIME) <NEW_LINE> try: <NEW_LINE> <INDENT> search_box = self.driver.find_element_by_name('username') <NEW_LINE> search_box.send_keys('heng') <NEW_LINE> <DEDENT> except NoSuchElementException: <NEW_...
Test for registration. Note, It is the left over from the first sprint, so we do not implement all the test cases :return:
625941bf6fece00bbac2d66c
def test01a(self): <NEW_LINE> <INDENT> a = np.arange(1e2) <NEW_LINE> b = bcolz.carray(a, chunklen=10, rootdir=self.rootdir) <NEW_LINE> sl = slice(1) <NEW_LINE> assert_array_equal(a[sl], b[sl], "Arrays are not equal")
Testing `__getitem()__` method with only a start
625941bf26068e7796caec0a
def calc_pvalue(p_value: float) -> str: <NEW_LINE> <INDENT> if p_value <= 0.0005: <NEW_LINE> <INDENT> p = '***' <NEW_LINE> <DEDENT> elif p_value <= 0.005: <NEW_LINE> <INDENT> p = '**' <NEW_LINE> <DEDENT> elif p_value <= 0.05: <NEW_LINE> <INDENT> p = '*' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = 'ns' <NEW_LINE> ...
returns a string with the pvalue ready to plot
625941bfd6c5a10208143f78
def __init__(self, queue): <NEW_LINE> <INDENT> self.id = queue.id <NEW_LINE> self.is_canceled = queue.is_canceled <NEW_LINE> self.configuration = queue.get_execution_configuration() <NEW_LINE> self.interface = queue.get_job_interface() <NEW_LINE> self.priority = queue.priority <NEW_LINE> self.required_resources = queue...
Constructor :param queue: The queue model :type queue: :class:`queue.models.Queue`
625941bf50485f2cf553ccc8
def get_metrics(perfdata, nag): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for metric in perfdata.split(): <NEW_LINE> <INDENT> label = perfdata.split('=')[0] <NEW_LINE> path = "%s.%s.%s" % (nag.GRAPHITEPREFIX, nag.HOSTNAME, label) <NEW_LINE> value = nag.VALUE <NEW_LINE> results.append((path, value)) <NEW_LINE> <DEDENT...
returns a [(<path>, <value>)] where each is the metric to send to carbon
625941bf50812a4eaa59c254
def osu_run1(data_set="osu_run1", sample_every=4): <NEW_LINE> <INDENT> path = os.path.join(DATAPATH, data_set) <NEW_LINE> if not data_available(data_set): <NEW_LINE> <INDENT> import zipfile <NEW_LINE> download_data(data_set) <NEW_LINE> zip = zipfile.ZipFile(os.path.join(DATAPATH, data_set, "run1TXT.ZIP"), "r") <NEW_LIN...
Ohio State University's Run1 motion capture data set.
625941bf60cbc95b062c6472
def _multiply_loss_ggn_factor_transpose(self, loss_vecs): <NEW_LINE> <INDENT> mult_func = lambda loss, vec: loss.multiply_ggn_factor_transpose(vec) <NEW_LINE> return self._multiply_across_losses(mult_func, loss_vecs, coeff_mode="sqrt")
Multiply loss_vecs by transpose factor of GGN of total loss.
625941bf0c0af96317bb8118
def play_game(board): <NEW_LINE> <INDENT> print("Ready to play ...\n") <NEW_LINE> discovered=["*"]*len(board) <NEW_LINE> guesses = 0 <NEW_LINE> while discovered != board: <NEW_LINE> <INDENT> print_board(discovered) <NEW_LINE> print("\n") <NEW_LINE> p1 = 0 <NEW_LINE> p2 = 0 <NEW_LINE> while p1 == p2 or p1 not in range(1...
(list of str)->None Plays a concentration game using the given board Precondition: board a list representing a playable deck
625941bf9b70327d1c4e0d04
def test_v_date_invalid(self): <NEW_LINE> <INDENT> date_str = "2013_44_01" <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> v_date(date_str) <NEW_LINE> <DEDENT> date_str = "2013-44-01" <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> v_date(date_str)
Test v_date validator with invalid dates
625941bfd4950a0f3b08c281
def getMaxTimeOfImmobility(self, time = 20, startTime = 0, minSpeed = 10, skip = 12, smooth = 2, forGraph = False): <NEW_LINE> <INDENT> time = time * 60000 <NEW_LINE> start = self.findStart(startTime) <NEW_LINE> t0 = startTime <NEW_LINE> x0, y0 = self.data[start][7:9] <NEW_LINE> speeds = deque() <NEW_LINE> prev = t0 <N...
returns maximum continuous time that the rat was immobile minSpeed argument is in cm/s, smooth and skip are represented in data points
625941bf004d5f362079a265
def test_handle_bad_request(): <NEW_LINE> <INDENT> router = MockRouter() <NEW_LINE> backend = RapidHttpBacked(name='test', router=router) <NEW_LINE> response = backend.handle_request(HttpRequest()) <NEW_LINE> assert_true(isinstance(response, HttpResponseBadRequest))
handle_request must return a HttpResponse
625941bfd10714528d5ffc10
def set(self, table, item, value): <NEW_LINE> <INDENT> command = 'UPDATE ' + str(table) + " SET item='" + str(value) + "' WHERE item='" + str(item) + "';" <NEW_LINE> self.cur.execute(command) <NEW_LINE> self.conn.commit() <NEW_LINE> print('\n' + command)
SQL set call Args: table (str): 'FROM' statement item (str): 'WHERE' statement value (str): 'SET' statement
625941bf8da39b475bd64ea0
def AddValue(self, value, timestamp=None, offset=False): <NEW_LINE> <INDENT> timestamp = timestamp or int(time.time()) <NEW_LINE> Values.AddValue(self, timestamp, value, offset=offset)
Add a value to this TimeSeries. Finds or creates the appropriate Values child object and adds the new value to it. Args: value: integer timestamp: UNIX timestamp; defaults to now offset: if True, values are offsets from previous value
625941bf63f4b57ef000104f
def createWidgets(self): <NEW_LINE> <INDENT> titleLabel = Label(self,text='Jambalaya Text',fg='midnight blue',font='Verdana 30 bold') <NEW_LINE> titleLabel.grid(row=1,columnspan=3, sticky=N+E+W+S) <NEW_LINE> pic = PhotoImage(file='JumbledWords.gif') <NEW_LINE> imageLabel = Label(self, image=pic,borderwidth=0) <NEW_LINE...
Makes the general gameboard:Creates the titles and labels for the program; Creates Exit, Play Again, Guess buttons; Creates the textbox
625941bff9cc0f698b14052d
def transpose_time_pattern(self, reward_time: Series, time_up: float, time_down: float) -> Tuple[Any, ndarray]: <NEW_LINE> <INDENT> reward_time_round = np.around(reward_time.diff(), decimals=4) <NEW_LINE> reward_time_round[(reward_time_round != time_up) & (reward_time_round != time_down)] = 'C' <NEW_LINE> if time_up ==...
Cette méthode convertie les intervalles entre les events en séquance alphabétique simple :param reward_time: contient les temps en seconde :param time_up: temps haut "A" :param time_down: temps bas "B"
625941bf5f7d997b871749c5
def parseFor(tokens, j): <NEW_LINE> <INDENT> (asgnCl, condCl, incrCl, codeCl, rc) = sepForCls(tokens, j); <NEW_LINE> pAsgns = parseForAssignments(asgnCl); <NEW_LINE> pCond = parseExp(condCl); <NEW_LINE> pIncrs = parseForAssignments(incrCl); <NEW_LINE> pCode = yacc(codeCl) + pIncrs; <NEW_LINE> map(tree.append, pAsgns); ...
Helps yacc(..) in parsing for stmt (as while).
625941bfe1aae11d1e749be5
def get_center(square_num): <NEW_LINE> <INDENT> half_square = SQUARE_SIZE // 2 <NEW_LINE> (x_ll, y_ll) = get_LL_corner(square_num) <NEW_LINE> return (x_ll + half_square, y_ll + half_square)
Returns the center coordinate of the square_num
625941bf73bcbd0ca4b2bfa6
def __inner_predict(self, data_idx): <NEW_LINE> <INDENT> if data_idx >= self.__num_dataset: <NEW_LINE> <INDENT> raise ValueError("Data_idx should be smaller than number of dataset") <NEW_LINE> <DEDENT> if self.__inner_predict_buffer[data_idx] is None: <NEW_LINE> <INDENT> if data_idx == 0: <NEW_LINE> <INDENT> n_preds = ...
Predict for training and validation dataset
625941bf07d97122c41787b6
@with_debug_logging <NEW_LINE> def normalize_journal_titles(obj, eng): <NEW_LINE> <INDENT> publications = obj.data.get('publication_info', []) <NEW_LINE> for publication in publications: <NEW_LINE> <INDENT> normalize_journal_title_entry(obj, publication, add_inspire_categories=True) <NEW_LINE> <DEDENT> references = obj...
Normalize the journal titles Normalize the journal titles stored in the `journal_title` field of each object contained in `publication_info` and for each `publication_info.journal_title` in references. Note: The DB is queried in order to get the `$ref` of each journal and add it in `journal_record` as well as...
625941bf442bda511e8be34c
def log(exception: Exception) -> Path: <NEW_LINE> <INDENT> log_file = make_log_file("error") <NEW_LINE> with open(log_file, "w") as f: <NEW_LINE> <INDENT> exc = traceback.format_exception( type(exception), exception, tb=exception.__traceback__ ) <NEW_LINE> for l in exc: <NEW_LINE> <INDENT> f.write(l) <NEW_LINE> <DEDENT...
Logs exception. Writes traceback and contents of the interpreter's stack frames to a new log file.
625941bf4428ac0f6e5ba721
def get_fast_rcnn_blob_names(is_training=True): <NEW_LINE> <INDENT> blob_names = ['rois'] <NEW_LINE> if is_training: <NEW_LINE> <INDENT> blob_names += ['labels_int32'] <NEW_LINE> <DEDENT> if is_training: <NEW_LINE> <INDENT> blob_names += ['bbox_targets'] <NEW_LINE> blob_names += ['bbox_inside_weights'] <NEW_LINE> blob_...
Fast R-CNN blob names.
625941bf8c0ade5d55d3e8e8
def eul57(n): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for i in range(1, n+1): <NEW_LINE> <INDENT> num = 1 <NEW_LINE> den = 2 <NEW_LINE> for j in range(i-1, 0, -1): <NEW_LINE> <INDENT> num += 2 * den <NEW_LINE> tmp = den <NEW_LINE> den = num <NEW_LINE> num = tmp <NEW_LINE> <DEDENT> num += den <NEW_LINE> if num_len(num)...
In the first n = one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
625941bfd10714528d5ffc11
def tag_id_meta(train, val): <NEW_LINE> <INDENT> tag_to_id = {} <NEW_LINE> id_to_tag = {} <NEW_LINE> data = [train, val] <NEW_LINE> tag_id = 0 <NEW_LINE> for df in data: <NEW_LINE> <INDENT> for idx in df.index: <NEW_LINE> <INDENT> for tag in df["tags"][idx]: <NEW_LINE> <INDENT> if tag not in tag_to_id: <NEW_LINE> <INDE...
train, val : list of pandas.DataFrame @returns : (dictionary, dictionary)
625941bf711fe17d825422a1
def _LJ_epsilonsigma_to_ab(coeffs): <NEW_LINE> <INDENT> A = 4.0 * coeffs['epsilon'] * coeffs['sigma']**12.0 <NEW_LINE> B = 4.0 * coeffs['epsilon'] * coeffs['sigma']**6.0 <NEW_LINE> return {"A": A, "B": B}
Convert epsilon/sigma representation to AB representation of the LJ potential
625941bf2c8b7c6e89b356f2
def test_publish_token_authorization_error(self): <NEW_LINE> <INDENT> token = 'asdfasdfasdfasdf' <NEW_LINE> load = {'user': 'foo', 'fun': 'test.arg', 'tgt': 'test_minion', 'arg': 'bar', 'kwargs': {'token': token}} <NEW_LINE> mock_token = {'token': token, 'eauth': 'foo', 'name': 'test'} <NEW_LINE> mock_ret = {'error': {...
Asserts that an AuthorizationError is returned when the token authenticates, but is not authorized.
625941bfec188e330fd5a6d4
def test_lookup(self): <NEW_LINE> <INDENT> dist_a = Distribution.objects.create(name='Foo', version_name='Bar', version_number='1.2') <NEW_LINE> dist_b = Distribution.objects.create(name='Foo', version_name='Lorem', version_number='1.1') <NEW_LINE> Lookup.objects.create(distribution=dist_a, content='eegahw2S\n') <NEW_L...
Do a lookup with existing datas
625941bf99fddb7c1c9de2c2
def _get_actor_id(actor: ObjectOrIDType) -> str: <NEW_LINE> <INDENT> if isinstance(actor, dict): <NEW_LINE> <INDENT> return actor["id"] <NEW_LINE> <DEDENT> return actor
Helper for retrieving an actor `id`.
625941bfe64d504609d74770
@cythonized("u") <NEW_LINE> def dmp_ground_LC(f, u, K): <NEW_LINE> <INDENT> if not u: <NEW_LINE> <INDENT> return dup_LC(f, K) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dmp_ground_LC(dmp_LC(f, K), u-1, K)
Returns ground leading coefficient.
625941bf7047854f462a133c
def initial_segmentation(image, PATCH_RATIO): <NEW_LINE> <INDENT> from skimage.filters import threshold_li, threshold_otsu, threshold_minimum <NEW_LINE> from skimage.morphology import closing, square <NEW_LINE> thresh_li = threshold_li(image) <NEW_LINE> thresh_otsu = threshold_otsu(image) <NEW_LINE> try: <NEW_LINE> <IN...
Initialization of the image segmentation. :param image: A numpy matrix. Original image. :param PATCH_RATIO: Constant. Ratio between patch area against cell mean cell area.
625941bf4c3428357757c25a
def bandpass(X, cutoff=(0.125, 0.375), order=2, axis=0, fs=1.0, **kws): <NEW_LINE> <INDENT> b,a = _bandpass_ba(cutoff=cutoff, order=order, fs=fs) <NEW_LINE> Y = filtfilt(b, a, X, axis=axis, **kws) <NEW_LINE> return Y
Butterworth bandpass filter. *Parameters*: X: ndarray. cutoff: (float, float), low/high-frequency cut, default=(0.125, 0.375) (unit is sample freqency). order: int, default=2. axis: int, default=0. fs: number, sample freqency, default=1.0 *Return*: Y: ndarray, highpassed X.
625941bf94891a1f4081b9d8
def add_insect(self, insect): <NEW_LINE> <INDENT> if insect.is_ant: <NEW_LINE> <INDENT> if self.ant is None: <NEW_LINE> <INDENT> self.ant = insect <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.ant.can_contain(insect): <NEW_LINE> <INDENT> self.ant.contain_ant(insect) <NEW_LINE> <DEDENT> elif insect.can_contain(s...
Add an Insect to this Place. There can be at most one Ant in a Place, unless exactly one of them is a container ant, in which case there can be two. If add_insect tries to add more Ants than is allowed, an assertion error is raised. There can be any number of Bees in a Place.
625941bf5166f23b2e1a5089
def _get_inputs_by_name(self, name): <NEW_LINE> <INDENT> inputs = self._collection.list() <NEW_LINE> logger.info('%s: %d inputs in total. filtering by name (%s)...' % (self.input_name, len(inputs), name)) <NEW_LINE> inputs_dict = merge_util.match_inputs(self.input_name, inputs, name) <NEW_LINE> logger.info('%s: %d inpu...
Get the inputs and entities based on input name. Args: name: The name of input Returns: (dict, list): The dict of inputs and the original input list (entities)
625941bfde87d2750b85fcc0
def update_current_location(client, access_token): <NEW_LINE> <INDENT> data = dict({ 'lat': 51.5112139, 'lng': -0.1198244}) <NEW_LINE> rv = client.put( '/user/location', headers=dict({ "Authorization": "Bearer %s" % access_token }), data=data) <NEW_LINE> return rv
Update user current location
625941bfdc8b845886cb5464
def __init__ (self, point_coordinates, force_unique=True): <NEW_LINE> <INDENT> points = np.asarray(point_coordinates) <NEW_LINE> if points.ndim == 1: <NEW_LINE> <INDENT> points = points.reshape((len(points),1)) <NEW_LINE> <DEDENT> if force_unique: <NEW_LINE> <INDENT> unique = list({tuple(pt) for pt in points}) <NEW_LIN...
Parameters --------- point_coordinates : ndarray, size=(npoints , ndims) force_unique : boolean Force the point coordinates to be unique
625941bf6fb2d068a760efcb
def __ge__(self, other): <NEW_LINE> <INDENT> return self.compare(self, other) >= 0
Method implements the behavior of the '>=' operator. Returns: :bool: whether or not *self* >= *other*.
625941bf26068e7796caec0b
def test_load_works(self, monkeypatch): <NEW_LINE> <INDENT> monkeypatch.setattr( "numpy.load", lambda *args, **kwargs: np.zeros((528, 320, 456), dtype=np.float32), ) <NEW_LINE> monkeypatch.setattr( "atlalign.data.img_as_float32", lambda *args, **kwargs: np.zeros((320, 456), dtype=np.float32), ) <NEW_LINE> x_atlas = nis...
Test that loading works.
625941bf9c8ee82313fbb6a5
def _get_word_ngrams(n, words): <NEW_LINE> <INDENT> assert len(words) > 0 <NEW_LINE> assert n > 0 <NEW_LINE> return _get_ngrams(n, words)
Calculates word n-grams for multiple sentences.
625941bf0a50d4780f666dc0
def _next_break(primitive_boundaries, pos, expects): <NEW_LINE> <INDENT> for i in xrange(pos, len(primitive_boundaries)): <NEW_LINE> <INDENT> sb = primitive_boundaries[i][1] <NEW_LINE> if sb in expects: <NEW_LINE> <INDENT> return sb <NEW_LINE> <DEDENT> <DEDENT> return None
(internal)
625941bf498bea3a759b99e0
def new_category(name): <NEW_LINE> <INDENT> category = Category() <NEW_LINE> category.name = name <NEW_LINE> return category
new_category creates a new Category object given the name
625941bf8c3a8732951582e8
def test_init(self): <NEW_LINE> <INDENT> self.assertLessEqual(self.pmo.max_pos_, 1.0) <NEW_LINE> self.assertGreaterEqual(self.pmo.max_pos_, 0.0) <NEW_LINE> self.assertLess(self.pmo.min_pos_, 1.0) <NEW_LINE> self.assertGreaterEqual(self.pmo.min_pos_, 0.0) <NEW_LINE> self.assertLessEqual(self.pmo.portfolio_size_, len(sel...
Test initialization of PortfolopOptimizer class
625941bf796e427e537b04f4
def main(**kwargs): <NEW_LINE> <INDENT> pass
main function
625941bf23e79379d52ee497
def parse_tracelogging_event(bv: binaryninja.binaryview.BinaryView, stream: Stream) -> Event: <NEW_LINE> <INDENT> channel = stream.read_u8() <NEW_LINE> if channel != 11: <NEW_LINE> <INDENT> raise ETWBreakerUnexpectedToken(11, channel) <NEW_LINE> <DEDENT> level = stream.read_u8() <NEW_LINE> opcode = stream.read_u8() <NE...
A tracelogging event is identified by its channel number_of_channel that are always 11. Actually we can't handle tracelogging event because the lonk between event and provider is made during code execution :ivar stream: current stream use to parse the event :ret: An event object for tracelogging
625941bf7047854f462a133d
@jit <NEW_LINE> def greyscale_filter_numba(filename): <NEW_LINE> <INDENT> image = cv2.imread(filename) <NEW_LINE> imageAsRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) <NEW_LINE> for i in range(len(imageAsRGB)): <NEW_LINE> <INDENT> for j in range(len(imageAsRGB[i])): <NEW_LINE> <INDENT> sum = (imageAsRGB[i, j, 0] * .29 +...
Function to read image and make it greyscale using numba. :param filename: image name in filepath :return: new greyscaled 3d array that represents image
625941bf07f4c71912b113b1
def newWorld(self, world): <NEW_LINE> <INDENT> if world.all_write == False: <NEW_LINE> <INDENT> self.in_publicworld = False <NEW_LINE> self.var_blockchcount = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.in_publicworld = True
Hook to reset griefer blockcount abilities in new worlds if not op.
625941bf7c178a314d6ef38c
def var_mul ( v1 , v2 , name = '' , title = '' ) : <NEW_LINE> <INDENT> f1 = isinstance ( v1 , num_types ) <NEW_LINE> f2 = isinstance ( v2 , num_types ) <NEW_LINE> if f1 and f2 : <NEW_LINE> <INDENT> r = float ( v1 ) * float ( v2 ) <NEW_LINE> return ROOT.RooRealConstant.value ( r ) <NEW_LINE> <DEDENT> elif f1 : v1 = ROOT...
Product of two RooAbsReal objects >>> v1 = ... >>> v2 = ... >>> v = var_mul ( v1 , v2 )
625941bf091ae35668666e93
def SetCookie(self, cookie): <NEW_LINE> <INDENT> return 0
Asocia la cookie. Parametros: cookie -- la cookie a asociar
625941bf5e10d32532c5ee58
def test_builddependency4(self): <NEW_LINE> <INDENT> bdep = BuildDependency.fromdata('deb', 'amd64', 'foo', '1.4', '4') <NEW_LINE> self.assertEqual(bdep.get('binarytype'), 'deb') <NEW_LINE> self.assertEqual(bdep.get('arch'), 'amd64') <NEW_LINE> self.assertEqual(bdep.get('name'), 'foo') <NEW_LINE> self.assertEqual(bdep....
test BuildDependency (fromdata binarytype deb)
625941bff548e778e58cd4ad
def get_build_architecture(): <NEW_LINE> <INDENT> prefix = " bit (" <NEW_LINE> i = sys.version.find(prefix) <NEW_LINE> if i == -1: <NEW_LINE> <INDENT> return "Intel" <NEW_LINE> <DEDENT> j = sys.version.find(")", i) <NEW_LINE> return sys.version[i+len(prefix):j]
Return the processor architecture. Possible results are "Intel" or "AMD64".
625941bf0a50d4780f666dc1
def remove_duplicates(list1): <NEW_LINE> <INDENT> if ( len(list1) == 0 ) or ( len(list1) == 1 ): <NEW_LINE> <INDENT> return list1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if list1[0] == list1[1]: <NEW_LINE> <INDENT> return remove_duplicates(list1[1:]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return list1[0:1]...
Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative.
625941bfbe7bc26dc91cd535
def add(request): <NEW_LINE> <INDENT> form = request.form() <NEW_LINE> b = Blog.new(form) <NEW_LINE> return redirect('/blog/index')
保存新的博文
625941bf236d856c2ad44707
def place(self, target: Any, value: Any, **kwargs: dict) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> target[self.name] = value <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise NullNameError(str(self)) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> if isinstance(target, List) and isin...
Sets ``value`` at Index/Key of ``target`` :param target: object to set ``value`` on. :param value: value to set. :return: None :raises NullNameError: When Index/Key cannot be set :raises TypeError: When ``target`` does not support ``__setitem__`` Changing an existing dict key: >>> from gemma import Item >>> >>> data...
625941bf004d5f362079a266
def set_callbacks(self, shutdown, restart): <NEW_LINE> <INDENT> self.shutdowncb = shutdown <NEW_LINE> self.restartcb = restart
Sets callbacks for the global buttons @param shutdown: shutdown callback @param restart: restart callback
625941bf67a9b606de4a7dec
def tileswrap(ihtORsize, numtilings, floats, wrawidths, ints=None, readonly=False): <NEW_LINE> <INDENT> if ints is None: <NEW_LINE> <INDENT> ints = [] <NEW_LINE> <DEDENT> qfloats = [floor(f * numtilings) for f in floats] <NEW_LINE> Tiles = [] <NEW_LINE> for tiling in range(numtilings): <NEW_LINE> <INDENT> tilingX2 = ti...
returns num-tilings tile indices corresponding to the floats and ints, wrapping some floats
625941bf4f6381625f11496e
def print_last_recorded_balance(table_names): <NEW_LINE> <INDENT> for table_name in table_names: <NEW_LINE> <INDENT> repository = TransactionsRepository(Table.get_from_config(table_name)) <NEW_LINE> latest_balance = repository.get_latest_balance() <NEW_LINE> print('Latest balance for {}: {}'.format(table_name, latest_b...
Print the latest recorded balance of the given tables. :param list(str) table_names: :return None:
625941bfd18da76e23532404
def load_modules(self): <NEW_LINE> <INDENT> self.logger.info('Loading Modules') <NEW_LINE> module_paths = self._tree_read(self.config, ['module-directories'], []) <NEW_LINE> if self._tree_read(self.config, ['include-default-modules'], True): <NEW_LINE> <INDENT> module_paths.append(self.get_default_modules_path()) <NEW_...
Loading modules
625941bf1f037a2d8b946130
def generateReferenceLink(self,anaphora,antecedent,confidence): <NEW_LINE> <INDENT> link = self.atomspace.add_link(types.ReferenceLink, [anaphora, antecedent], TruthValue(.98, TruthValue().confidence_to_count(confidence))) <NEW_LINE> log.fine("Generated a Reference :\n") <NEW_LINE> log.fine("{0}\n".format(link)) <NEW_L...
Generates a reference Link for a pair of anaphora and antecedent with confidence "confidence".
625941bfab23a570cc2500b1
def get_row(A, i): <NEW_LINE> <INDENT> return A[i]
return row i from A.
625941bf16aa5153ce3623a9
@pytest.mark.provider( [VMwareProvider, RHEVMProvider, OpenStackProvider, AzureProvider], scope="module", selector=ONE_PER_TYPE ) <NEW_LINE> @pytest.mark.meta(blockers=[BZ(1702018, forced_streams=["5.11"])], automates=[1702018]) <NEW_LINE> def test_action_prevent_vm_retire(request, vm, vm_on, policy_for_testing): <NEW_...
This test sets the policy that prevents VM retiring. Metadata: test_flag: actions, provision Bugzilla: 1702018 Polarion: assignee: dgaikwad initialEstimate: 1/6h casecomponent: Control
625941bf45492302aab5e1f2
def _handle_rate_limit(self, r): <NEW_LINE> <INDENT> retry_time = int(r.headers['Retry-After']) <NEW_LINE> assert(retry_time > 0) <NEW_LINE> if self.debug: <NEW_LINE> <INDENT> print("-> Sleeping for {0} seconds".format(retry_time)) <NEW_LINE> <DEDENT> time.sleep(retry_time)
Sleep for length of retry time :param r: request object
625941bf56ac1b37e6264105
def tree_str(self, lemma=True, arrow=True): <NEW_LINE> <INDENT> s = '' <NEW_LINE> for lfnode in self.leafNodes: <NEW_LINE> <INDENT> if not arrow: <NEW_LINE> <INDENT> if lemma: s += '{} '.format(lfnode.word) <NEW_LINE> else: s += '{} '.format(lfnode.word_raw) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if lfnode.cat.m...
return the sentence as string
625941bf8a43f66fc4b53f99
def do_unfollow_user(self, arg): <NEW_LINE> <INDENT> if self.login_status == False: <NEW_LINE> <INDENT> print_error_not_login() <NEW_LINE> return <NEW_LINE> <DEDENT> parameters = arg.split() <NEW_LINE> if len(parameters) != 1: <NEW_LINE> <INDENT> print_error_param_num() <NEW_LINE> return <NEW_LINE> <DEDENT> condition =...
Command: unfollow_user {UserID} Description: Unfollow a user
625941bff8510a7c17cf962c
def savefile(cdata,writer): <NEW_LINE> <INDENT> writer.writerows(cdata)
写入数据
625941bf5f7d997b871749c6
def crawl_daili66(self, page_count=8): <NEW_LINE> <INDENT> print('开始获取 66ip 的代理') <NEW_LINE> start_url = 'http://www.66ip.cn/{}.html' <NEW_LINE> urls = [start_url.format(page) for page in range(1, page_count + 1)] <NEW_LINE> for url in urls: <NEW_LINE> <INDENT> print('Crawling', url) <NEW_LINE> html = PageGetter().get_...
获取代理,来源为66ip :param page_count: 页码 :return: 代理
625941bf4a966d76dd550f3e
def spop(self, name): <NEW_LINE> <INDENT> return self.execute_command('SPOP', name)
Remove and return a random member of set ``name``
625941bfa219f33f3462889e
def helium_tiny_ansatz(ab): <NEW_LINE> <INDENT> return Program( X(0), X(1), RX(np.pi/2, 0), H(1), CNOT(0, 1), RZ( ab[0] )(1), CNOT(0, 1), RX(-np.pi/2)(0), H(1), H(0), RX(np.pi/2)(1), CNOT(0, 1), RZ( ab[1] )(1), CNOT(0, 1), H(0), RX(-np.pi/2, 1) )
in this trial, we also explicitly supply the UCC ansatz
625941bf009cb60464c632e5
def thresh_vlim(data, thresh=0.01, Nbin=200): <NEW_LINE> <INDENT> thresh = thresh*np.ones(2) if np.size(thresh) < 2 else thresh <NEW_LINE> H, bin_edges = np.histogram(data[~np.isnan(data)], Nbin) <NEW_LINE> vmin, vmax = bin_edges[0], bin_edges[-1] <NEW_LINE> csH = H.cumsum() / np.nansum(H) <NEW_LINE> ilo = np.where(csH...
Calculate colormap vlim based on a histogram threshold. Excludes fraction on top and bottom given by scalar or 2-tuple thresh.
625941bf21bff66bcd684886
def p_valor(p): <NEW_LINE> <INDENT> pass
valor : llamada | identificador | constante
625941bf596a8972360899f4
def __init__(self, image_dims=[64, 64, 3]): <NEW_LINE> <INDENT> self.name = "Conv_model_2" <NEW_LINE> self.image_dims = image_dims
Sets hyper-parameters Input: image_dims: image dimensions (default [64, 64, 3]) bottleneck_dim: dimension of bottleneck layer (default 40)
625941bf44b2445a33931fc8
def p_repeat_instr(self, p): <NEW_LINE> <INDENT> p[0] = AST.RepeatUntil(p[2], p[4])
repeat_instr : REPEAT instructions UNTIL condition ';'
625941bf1d351010ab855a4e
def serve_version(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.__serve_version_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.__serve_version_with_http_info(**kwargs) <NEW_LINE> r...
serve_version # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.serve_version(async_req=True) >>> result = thread.get() :param async_req: bool :return: str If the method is called asynchronously, r...
625941bf0383005118ecf515
def close(self): <NEW_LINE> <INDENT> if hasattr(self.array, 'close'): <NEW_LINE> <INDENT> self.array.close()
Close array.
625941bfa05bb46b383ec755
def init(): <NEW_LINE> <INDENT> ctx = {} <NEW_LINE> @click.command() <NEW_LINE> @click.option('--cell', required=True, envvar='TREADMILL_CELL', callback=cli.handle_context_opt, expose_value=False) <NEW_LINE> @click.option('--wsapi', required=False, help='Websocket API.', metavar='URL', envvar='TREADMILL_WSAPI') <NEW_LI...
Return top level command handler.
625941bf8e05c05ec3eea2a3
@task <NEW_LINE> def write_code_workspace_file(c, cw_path=None): <NEW_LINE> <INDENT> if not cw_path: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cw_path = next(iglob(str(PROJECT_ROOT / "doodba.*.code-workspace"))) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> cw_path = f"doodba.{PROJECT_ROOT.name}.code...
Generate code-workspace file definition. Some other tasks will call this one when needed, and since you cannot specify the file name there, if you want a specific one, you should call this task before. Most times you just can forget about this task and let it be run automatically whenever needed. If you don't define...
625941bf29b78933be1e55e2
def rescale(image, scale): <NEW_LINE> <INDENT> if isinstance(scale, (tuple, list)): <NEW_LINE> <INDENT> scale = np.random.uniform(scale[0], scale[1]) <NEW_LINE> <DEDENT> elif not isinstance(scale, (int, float)): <NEW_LINE> <INDENT> raise ValueError('scale type should be one of int, float, tuple, list.') <NEW_LINE> <DED...
Rescale apply to image. new pixel = image * scale Args: image: a Image instance. scale: if int float, value multiply with image. if tuple list, randomly picked in the interval `[central_rate[0], central_rate[1])`, value multiply with image. Returns: a Image instance. Raises: scale...
625941bfd53ae8145f87a1a5
def test_input_symmetry_XOR(): <NEW_LINE> <INDENT> n = XOR() <NEW_LINE> k_s, true_k_s = n.input_symmetry(bound='upper', norm=False), 8 / 4 <NEW_LINE> assert (k_s == true_k_s), ('Input Symmetry (node,upper bound) for XOR node does not match. %s != %s' % (k_s, true_k_s)) <NEW_LINE> k_s, true_k_s = n.input_symmetry(bound=...
Test Input Symmetry - XOR
625941bfb830903b967e983f
def path_info_split(path_info): <NEW_LINE> <INDENT> if not path_info: <NEW_LINE> <INDENT> return None, '' <NEW_LINE> <DEDENT> assert path_info.startswith('/'), ( "PATH_INFO should start with /: %r" % path_info) <NEW_LINE> path_info = path_info.lstrip('/') <NEW_LINE> if '/' in path_info: <NEW_LINE> <INDENT> first, rest ...
Splits off the first segment of the path. Returns (first_part, rest_of_path). first_part can be None (if PATH_INFO is empty), '' (if PATH_INFO is '/'), or a name without any /'s. rest_of_path can be '' or a string starting with /.
625941bfff9c53063f47c126
def assignment(self): <NEW_LINE> <INDENT> col = self.collaboration() <NEW_LINE> if not col: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> parent = col.get_parent() <NEW_LINE> if not parent: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return parent.content_object
Returns the Project object that this Project is a response to, or None if this Project is not a response to any other.
625941bf23849d37ff7b2fc2
def remove_conference(self, conf_id): <NEW_LINE> <INDENT> self.options['usr_conferenc_id'] = conf_id <NEW_LINE> self.options['actions'] = 'conference.remove' <NEW_LINE> return self.call(self.options)
Remove a conference that is not active keyword argument: conf_id -- ID of conference to remove
625941bf851cf427c661a443
def __init__(self, flow_graph): <NEW_LINE> <INDENT> self.ctrl_mask = False <NEW_LINE> self.mod1_mask = False <NEW_LINE> self._flow_graph = flow_graph <NEW_LINE> gtk.DrawingArea.__init__(self) <NEW_LINE> self.set_size_request(MIN_WINDOW_WIDTH, MIN_WINDOW_HEIGHT) <NEW_LINE> self.connect('realize', self._handle_window_rea...
DrawingArea contructor. Connect event handlers. Args: main_window: the main_window containing all flow graphs
625941bf8a349b6b435e80a5
def model(flags): <NEW_LINE> <INDENT> ds_filters = utils.parse(flags.ds_filters) <NEW_LINE> ds_repeat = utils.parse(flags.ds_repeat) <NEW_LINE> ds_kernel_size = utils.parse(flags.ds_kernel_size) <NEW_LINE> ds_stride = utils.parse(flags.ds_stride) <NEW_LINE> ds_dilation = utils.parse(flags.ds_dilation) <NEW_LINE> ds_res...
MatchboxNet model. It is based on paper MatchboxNet: 1D Time-Channel Separable Convolutional Neural Network Architecture for Speech Commands Recognition https://arxiv.org/pdf/2004.08531.pdf Args: flags: data/model parameters Returns: Keras model for training Raises: ValueError: if any of input list has differ...
625941bffb3f5b602dac35c2
def test_delete_failure_not_accepted_right(self): <NEW_LINE> <INDENT> self.file_repository_right.accepted = False <NEW_LINE> self.file_repository_right.save() <NEW_LINE> url = reverse('file_repository') <NEW_LINE> data = { 'file_repository_id': self.file_repository.id, } <NEW_LINE> self.client.force_authenticate(user=s...
Tests to delete a file repository without accepting the right
625941bf30dc7b766590189a
def set_start_state(self, msg): <NEW_LINE> <INDENT> self._g.set_start_state(conversions.msg_to_string(msg))
Specify a start state for the group. Parameters ---------- msg : moveit_msgs/RobotState Examples -------- >>> from moveit_msgs.msg import RobotState >>> from sensor_msgs.msg import JointState >>> joint_state = JointState() >>> joint_state.header = Header() >>> joint_state.header.stamp = rospy.Time.now() >>> joint_state...
625941bf9c8ee82313fbb6a6
def test_table_from_bool_fields2(self): <NEW_LINE> <INDENT> arr = np.array([(False,), (True,), (False,)], dtype=[('a', '?')]) <NEW_LINE> hdu = fits.BinTableHDU(data=arr) <NEW_LINE> assert (hdu.data['a'] == arr['a']).all()
Regression test for https://trac.assembla.com/pyfits/ticket/215 Tests the case where a multi-field ndarray (not a recarray) containing a bool field is used to initialize a `BinTableHDU`.
625941bf6fece00bbac2d66e
def dropAllTables(self): <NEW_LINE> <INDENT> cursor = self.conn.cursor() <NEW_LINE> cursor.execute('''DROP TABLE IF EXISTS artist''') <NEW_LINE> cursor.execute('''DROP TABLE IF EXISTS album''') <NEW_LINE> cursor.execute('''DROP TABLE IF EXISTS track''') <NEW_LINE> self.conn.commit() <NEW_LINE> self.conn.close()
Drops all tables in the database
625941bf4d74a7450ccd40f5
def negotiate_tls(tcp_conn, context): <NEW_LINE> <INDENT> tls_conn = context.wrap_socket(tcp_conn, server_side=True) <NEW_LINE> negotiated_protocol = tls_conn.selected_alpn_protocol() <NEW_LINE> if negotiated_protocol is None: <NEW_LINE> <INDENT> negotiated_protocol = tls_conn.selected_npn_protocol() <NEW_LINE> <DEDENT...
Given an established TCP connection and a HTTP/2-appropriate TLS context, this function: 1. wraps TLS around the TCP connection. 2. confirms that HTTP/2 was negotiated and, if it was not, throws an error.
625941bf9b70327d1c4e0d05