code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def affine_bn_relu_backward(dout, cache): <NEW_LINE> <INDENT> fc_cache, bn_cache, relu_cache = cache <NEW_LINE> dbn = relu_backward(dout, relu_cache) <NEW_LINE> da, dgamma, dbeta = batchnorm_backward(dbn, bn_cache) <NEW_LINE> dx, dw, db = affine_backward(da, fc_cache) <NEW_LINE> return dx, dw, db, dgamma, dbeta | Backward pass for the affine-bn-relu convenience layer | 625941d350485f2cf553cf7d |
def Vec_Ridge(Product_A, Product_B, Product_AB, vectorizer=CountVectorizer()): <NEW_LINE> <INDENT> X_train, X_test, y_train, y_test = train_test_split(Product_AB['key_words'], Product_AB['sentiment_score'], test_size=0.33, random_state=42) <NEW_LINE> training_features = vectorizer.fit_transform(X_train) <NEW_LINE> test... | Input product_AB data frame
Returns train/test split
Vectorizes data, and creates dictionary of {index:feature_name}
Inputs vectorized data into a ridge regression to get coefficents of each features
Returns top negative values and top positive values | 625941d33617ad0b5ed680d9 |
@app.route('/users/<int:user_id>/edit/<int:favorite_id>', methods=["GET", "POST"]) <NEW_LINE> def edit_favorite(user_id, favorite_id): <NEW_LINE> <INDENT> if 'user_id' not in session: <NEW_LINE> <INDENT> flash("Please login first", "danger") <NEW_LINE> return redirect('/login') <NEW_LINE> <DEDENT> favorite = Favorite.q... | Edits a list | 625941d3cb5e8a47e48b7c8b |
def create_nested_list(list_values, nested_index_sets): <NEW_LINE> <INDENT> nested_list_values = [] <NEW_LINE> list_to_add_to = nested_list_values <NEW_LINE> list_to_use = list_values <NEW_LINE> sublist = [] <NEW_LINE> finished_forming_sublist = True <NEW_LINE> return_list = [] <NEW_LINE> for n in range(len(nested_inde... | Create nested lists containing the values in list_values based on the
indices to turn into sublists in nested_index_sets.
To clarify: Initially, the first two indices in nested_index_sets[0] will
be taken (referred to as 'start' and 'end'), and list_values[start:end] will
be replaced with a sublist containing values f... | 625941d33346ee7daa2b2f50 |
def _next_power_of_2(self, v): <NEW_LINE> <INDENT> if v == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> v -= 1 <NEW_LINE> v |= v >> 1 <NEW_LINE> v |= v >> 2 <NEW_LINE> v |= v >> 4 <NEW_LINE> v |= v >> 8 <NEW_LINE> v |= v >> 16 <NEW_LINE> return v + 1 | Returns the next power of 2, or the argument if it's
already a power of 2.
:param v: the value to be tested.
:type v: int
:returns: the next power of 2.
:rtype: int | 625941d37d43ff24873a2e83 |
def setRules(self, rules): <NEW_LINE> <INDENT> self.rules = rules | :param rules: (Optional) | 625941d3e8904600ed9f2111 |
def time_in_stop(self) -> timedelta: <NEW_LINE> <INDENT> return self.departure - self.arrival | Get the difference of time between the departure and the arrival time | 625941d35fdd1c0f98dc0416 |
def _UpdateNewestRevInMilestoneDict(bots, tests, milestone_dict): <NEW_LINE> <INDENT> if bots and tests: <NEW_LINE> <INDENT> test_path = bots[0] + '/' + tests[0] <NEW_LINE> test_key = utils.TestKey(test_path) <NEW_LINE> datastore_hooks.SetSinglePrivilegedRequest() <NEW_LINE> query = graph_data.Row.query() <NEW_LINE> qu... | Updates the most recent rev in the milestone dict.
The global milestone dicts are declared with 'None' for the end of the
current milestone range. If we might be using the last milestone, update
the end of the current milestone range to be the most recent revision. | 625941d33539df3088e2e52d |
def read_from_config(self): <NEW_LINE> <INDENT> cs_target = glob.glob(self.cfg_path) <NEW_LINE> with open(cs_target[0]) as f: <NEW_LINE> <INDENT> content = f.readlines() <NEW_LINE> <DEDENT> hipfire = 0 <NEW_LINE> awp = 0 <NEW_LINE> for x in content: <NEW_LINE> <INDENT> if x.startswith("sensitivity \""): <NEW_LINE> <IND... | We keep CSGO as our base sensitivity hence the BaseSensitivity and CS:GO Sensitivity are 1:1 in 360/cm. | 625941d3cc0a2c11143dd073 |
def stop(self): <NEW_LINE> <INDENT> self._serving = False <NEW_LINE> localClientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> try: <NEW_LINE> <INDENT> localClientSock.connect(self.sock.getsockname()) <NEW_LINE> <DEDENT> except ConnectionResetError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> time... | Stop the server. | 625941d3596a897236089ca2 |
def _initialize_data_(self): <NEW_LINE> <INDENT> from pandas.core.frame import DataFrame <NEW_LINE> assert(type(self.isotherm_data)==DataFrame) <NEW_LINE> self.adsorbent_id = self.adsorption_data['adsorbent_id'][0] <NEW_LINE> self.adsorptive_id = self.adsorption_data['adsorptive_id'][0] <NEW_LINE> self.isotherm_id = se... | checks if input data files are valid
accepted data types include int, float, data frame, and file paths
:return: | 625941d3bde94217f3682fd2 |
def test_assign_unicode(self): <NEW_LINE> <INDENT> erikku = u'\u30a8\u30ea\u30c3\u30af' <NEW_LINE> def assign(keyword, val): <NEW_LINE> <INDENT> h[keyword] = val <NEW_LINE> <DEDENT> h = fits.Header() <NEW_LINE> h[u'FOO'] = 'BAR' <NEW_LINE> assert 'FOO' in h <NEW_LINE> assert h['FOO'] == 'BAR' <NEW_LINE> assert h[u'FOO'... | Regression test for https://trac.assembla.com/pyfits/ticket/134
Assigning a unicode literal as a header value should not fail silently.
If the value can be converted to ASCII then it should just work.
Otherwise it should fail with an appropriate value error.
Also tests unicode for keywords and comments. | 625941d3283ffb24f3c55ae2 |
def __init__( self, name=None, description=None, auth=None, category_id=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.description = description <NEW_LINE> self.auth = auth <NEW_LINE> self.category_id = category_id | Initializes the variables for the categories class | 625941d3be383301e01b5667 |
def convert_to_input_spec(inputs, input_spec): <NEW_LINE> <INDENT> def check_type_and_len(input, spec, check_length=False): <NEW_LINE> <INDENT> if type(input) is not type(spec): <NEW_LINE> <INDENT> raise TypeError('type(input) should be {}, but received {}.'.format( type(spec), type(input))) <NEW_LINE> <DEDENT> if chec... | Replaces tensor in structured `inputs` by InputSpec in `input_spec`.
Args:
inputs(list|dict): nested structure list or dict.
input_spec(list|dict): same nested structure list or dict as inputs.
Return:
Same structure with inputs by replacing the element with specified InputSpec. | 625941d38e7ae83300e4b1b0 |
def _get_classifiers(self): <NEW_LINE> <INDENT> return { 'RandomForestRegressor ': RandomForestRegressor(n_estimators=100, n_jobs=self.n_jobs, random_state=42) } | :return: dict. {name:classifier} | 625941d3435de62698dfde30 |
def generate_build_rules(self): <NEW_LINE> <INDENT> raise NotImplementedError | Generate build rules for underlying build system. | 625941d3462c4b4f79d1d8b3 |
def draw_up_line(self, turtle, color, long): <NEW_LINE> <INDENT> turtle.color(color) <NEW_LINE> turtle.pendown() <NEW_LINE> turtle.setheading(90) <NEW_LINE> turtle.forward(long) <NEW_LINE> turtle.penup() <NEW_LINE> turtle.setheading(0) <NEW_LINE> turtle.forward(3) | This function simply draws a line going up and then turns to prepare for the the next line to be draws.
:param turtle: The turtle to use
:param color: White or black
:param long: The length of the bar
:return:None | 625941d35166f23b2e1a533c |
def handleItemEntered(self, index): <NEW_LINE> <INDENT> if index.isValid(): <NEW_LINE> <INDENT> row = index.row() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> idExp = str(self.proxyModel.sibling(row, 0, index).data()) <NEW_LINE> try: <NEW_LINE> <INDENT> self.timer.stop() <NEW_LINE> QToolTip.... | Process event when mouse enters an item and
create a `QTooltip` which describes the category, with a timer
Parameter:
index: a `QModelIndex` instance | 625941d3566aa707497f474a |
def get_access_token(self, verifier): <NEW_LINE> <INDENT> if isinstance(verifier, bytes): <NEW_LINE> <INDENT> verifier = verifier.decode('utf8') <NEW_LINE> <DEDENT> self._fetcher.set_verifier(verifier) <NEW_LINE> params = {} <NEW_LINE> params['User-Agent'] = self.user_agent <NEW_LINE> content, status_code = self._fetch... | Uses the verifier to exchange a request token for an access token. | 625941d4bd1bec0571d90813 |
def __neg__(self): <NEW_LINE> <INDENT> return Bruch(-self.zaehler,self.nenner) | Nimmt einen Bruch entgegen und gibt ihn als negativen Bruch zurück
:return: Gibt einen negativen Bruch zurück | 625941d3bde94217f3682fd3 |
def del_qubit(self, node): <NEW_LINE> <INDENT> self._del_node(node) | Remove a qubit. TODO: this is a hack right now. | 625941d4fff4ab517eb2f620 |
def save_config(attrs, path): <NEW_LINE> <INDENT> toml.dump(attrs, path) | Saves a configuration dictionary to a file. | 625941d460cbc95b062c6727 |
@ray.remote <NEW_LINE> def _read_csv_with_offset_pandas_on_ray( fname, num_splits, start, end, kwargs, header ): <NEW_LINE> <INDENT> index_col = kwargs.pop("index_col", None) <NEW_LINE> bio = open(fname, "rb") <NEW_LINE> bio.seek(start) <NEW_LINE> to_read = header + bio.read(end - start) <NEW_LINE> bio.close() <NEW_LIN... | Use a Ray task to read a chunk of a CSV into a Pandas DataFrame.
Note: Ray functions are not detected by codecov (thus pragma: no cover)
Args:
fname: The filename of the file to open.
num_splits: The number of splits (partitions) to separate the DataFrame into.
start: The start byte offset.
end: The e... | 625941d4b57a9660fec33a69 |
def main(arguments): <NEW_LINE> <INDENT> model = 'SSC_2' <NEW_LINE> luminosity = '1000 / 1 fbarn' <NEW_LINE> script_path = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> ISR_file = '{}/../../scripts/WHIZARD_scripts/isr_spectrum_files/ee_Waisty_opt_Jan2012_1000GeV_B1b.circe'.format(script_path) <NEW_LI... | Main function:
Create Sindarin files for simulation runs with the given parameters. | 625941d46fece00bbac2d923 |
def typeToType(t): <NEW_LINE> <INDENT> assert t is not None <NEW_LINE> return clr.GetClrType(t) <NEW_LINE> moduleName = t.__module__ <NEW_LINE> fullName = moduleName[4:] + '.' + t.__name__ <NEW_LINE> if issubclass(t, System.Exception): <NEW_LINE> <INDENT> assembly = System.Reflection.Assembly.GetAssembly(t._class) <NEW... | Horrible hack around the fact that Python.NET gets confused between
the distinction between System.Type instances and Python classes.
The basic approach is thus: get the full name, then use System.Reflection
to fetch the assembly which contains the type, and ask it for the type.
As a fun aside, this can also be achiev... | 625941d45fc7496912cc3b61 |
def create_collection(self, project_id: str, name: str, *, description: str = None, language: str = None, enrichments: List['CollectionEnrichment'] = None, **kwargs) -> 'DetailedResponse': <NEW_LINE> <INDENT> if project_id is None: <NEW_LINE> <INDENT> raise ValueError('project_id must be provided') <NEW_LINE> <DEDENT> ... | Create a collection.
Create a new collection in the specified project.
:param str project_id: The ID of the project. This information can be found
from the deploy page of the Discovery administrative tooling.
:param str name: The name of the collection.
:param str description: (optional) A description of the c... | 625941d4de87d2750b85ff77 |
def authenticate_credentials(self, request, access_token): <NEW_LINE> <INDENT> token = self.get_access_token(access_token) <NEW_LINE> if not token: <NEW_LINE> <INDENT> raise AuthenticationFailed({ 'error_code': OAUTH2_TOKEN_ERROR_NONEXISTENT, 'developer_message': u'The provided access token does not match any valid tok... | Authenticate the request, given the access token.
Overrides base class implementation to discard failure if user is
inactive. | 625941d44a966d76dd5511f3 |
def get_robot(self): <NEW_LINE> <INDENT> return self._robot | Get the robot.
:return IRobot: robot that is part of this environment | 625941d4fb3f5b602dac3878 |
def deduce_summit(peaks): <NEW_LINE> <INDENT> id2summits = {} <NEW_LINE> for peak in peaks: <NEW_LINE> <INDENT> if peak[-1] not in id2summits: <NEW_LINE> <INDENT> id2summits[peak[-1]] = [] <NEW_LINE> <DEDENT> id2summits[peak[-1]].append(peak[-2]) <NEW_LINE> <DEDENT> singles = [] <NEW_LINE> for summits in id2summits.val... | This function deduces the summit of the peak obtained by merging those in
"peaks".
peaks = [(..., summit, ID), ...], where ID represents the peak set ID.
Return an integer coordinate. | 625941d4656771135c3eba53 |
def is_constant() -> "DFPattern": <NEW_LINE> <INDENT> return ConstantPattern() | Syntatic sugar for creating a ConstantPattern.
Parameters
----------
name: str
The name of the input pattern to match.
Returns
-------
result: tvm.relay.dataflow_pattern.DFPattern
The resulting pattern. | 625941d4187af65679ca5302 |
def loop(self): <NEW_LINE> <INDENT> self.active = True <NEW_LINE> while self.active: <NEW_LINE> <INDENT> self.draw() <NEW_LINE> cmd = self.stdscr.getch() <NEW_LINE> self.controller.trigger(cmd) | Main control loop | 625941d47c178a314d6ef645 |
def testPictureCopyB8(self): <NEW_LINE> <INDENT> self.pict = Picture("white.bmp") <NEW_LINE> self.pict2 = Picture(self.pict) <NEW_LINE> self.height = self.pict.getHeight() <NEW_LINE> self.width = self.pict.getWidth() <NEW_LINE> if(self.height != 50): print('Warning: height not correct') <NEW_LINE> if(self.width != 50):... | Test Picture(copyPicture) constructor (bmp) [8] - pixels | 625941d457b8e32f5248367f |
def toggle_broken(self, item): <NEW_LINE> <INDENT> item.toggle_broken() | Calls the toggle_broken method on the item to change the item
| 625941d4925a0f43d254a05b |
def calcFaceSize(points): <NEW_LINE> <INDENT> dist = [] <NEW_LINE> for i in range(len(points)): <NEW_LINE> <INDENT> if i != 14: <NEW_LINE> <INDENT> dist.append(distance.euclidean(points[14],points[i])) <NEW_LINE> <DEDENT> <DEDENT> return dist | "
Calculates the distance between each feature and the nose, feature 14 | 625941d4aad79263cf390c26 |
def test_step3(self): <NEW_LINE> <INDENT> c = Circle(4) <NEW_LINE> c.diameter = 2 <NEW_LINE> actual = c.radius <NEW_LINE> expected = 1 <NEW_LINE> self.assertEqual(expected, actual) | Run a test to show the diameter can be set | 625941d4c4546d3d9de72c18 |
def __init__(self, screen, settings, fs, path_sound='sounds/mordisco.wav'): <NEW_LINE> <INDENT> self.screen = screen <NEW_LINE> self.settings = settings <NEW_LINE> self.fs = fs <NEW_LINE> self.height = settings.snake_height <NEW_LINE> self.margin = settings.snake_margin <NEW_LINE> self.screen_rect = self.screen.get_rec... | Initialize snake with a few segments. Store all attributes too. | 625941d4d8ef3951e3243721 |
def newKey(length=_KEY_DEFAULT_LENGTH): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> length = int(length) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> length = _KEY_DEFAULT_LENGTH <NEW_LINE> <DEDENT> table = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" <NEW_LINE> key = "" <NEW_LINE> indexMax = le... | returns a new crypted key of given length. | 625941d4d18da76e235326bb |
def add_event(self, title, day, time): <NEW_LINE> <INDENT> Calendar.add_event(self, title, day, time, self._room) | (Calendar, str, int, int, str) -> NoneType
Add a new event to this calendar to be held in room on the day'th
day at time (assuming the calendar starts on day 0, and all times
are given in hourly increments with 0 being 12AM and 23 being 11PM) | 625941d48e05c05ec3eea559 |
def test_rebuild_multichain_missing(self): <NEW_LINE> <INDENT> r = structure_rebuild_test(self.pdb_2XHE, False) <NEW_LINE> self.assertEqual(r["residues"], 787) <NEW_LINE> self.assertEqual(r["rCount"], 835) <NEW_LINE> self.assertEqual(r["rMatchCount"], 835) <NEW_LINE> self.assertEqual(r["aCount"], 6267) <NEW_LINE> self.... | Convert multichain missing atom protein to internal coordinates and back. | 625941d401c39578d7e7501f |
def login(self, server, username=None, password="", code=None, *args, **kwargs): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> new_args = dict( sync_original_prompt=False, auto_prompt_reset=False, original_prompt=f"[$]|{self.duo_pattern}", ) <NEW_LINE> if kwargs: <NEW_LINE> <INDENT> kwargs.update(... | Login to an SSH server while checking the DNS, silencing logs,
and suppressing the traceback for pxssh exceptions
(such as incorrect password errors).
Watch for a Duo prompt and authenticate with codes.
If ``code`` is `'interact'`, run `interact()` so that the user can interact
with the Duo prompt.
If ``code`` is n... | 625941d40a50d4780f667077 |
def test_returns_None_on_no_file_name(self): <NEW_LINE> <INDENT> lst = ['a', 'b', 'c'] <NEW_LINE> file = None <NEW_LINE> result = self.ignore_file(file, lst) <NEW_LINE> expected_result = None <NEW_LINE> self.assertEqual(result, expected_result) | Returns True when the file matches a pattern | 625941d432920d7e50b283b5 |
def cache_general_settings(): <NEW_LINE> <INDENT> session["generalsettings"]["theme"] = request.json["theme"] <NEW_LINE> session.modified = True | Stores the general settings.
| 625941d415fb5d323cde0cf5 |
def getRadius(self): <NEW_LINE> <INDENT> return _fife.LightRendererSimpleLightInfo_getRadius(self) | getRadius(LightRendererSimpleLightInfo self) -> float | 625941d4a219f33f34628b4b |
def get_color_rules(): <NEW_LINE> <INDENT> if RULE_CACHE: <NEW_LINE> <INDENT> return RULE_CACHE <NEW_LINE> <DEDENT> from os import environ <NEW_LINE> try: <NEW_LINE> <INDENT> rules = environ['LS_COLORS'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> for rule in rules.split(':'):... | Returns a dict of pattern : colorcode, retrieved from LS_COLORS. | 625941d4ac7a0e7691ed42ad |
def __init__(self, compressedString): <NEW_LINE> <INDENT> self.compressedString = re.findall("\D\d+", compressedString) <NEW_LINE> for i in range(len(self.compressedString)): <NEW_LINE> <INDENT> self.compressedString[i] = (self.compressedString[i][0], int(self.compressedString[i][1:])) <NEW_LINE> <DEDENT> self.current_... | :type compressedString: str | 625941d4c432627299f04e2b |
def split(s, like_cmd=True, check=True): <NEW_LINE> <INDENT> if like_cmd and re.search(cmd_meta, s): <NEW_LINE> <INDENT> def i(): <NEW_LINE> <INDENT> quote_mode = False <NEW_LINE> for m in re.finditer(r'(\^.)|(\")|([^\^\"]+)', s): <NEW_LINE> <INDENT> escaped, quote, text = m.groups() <NEW_LINE> if escaped: <NEW_LINE> <... | Split a string of command line arguments like DOS and Windows do.
On windows, before a command line argument becomes a char* in a
program's argv, it must be parsed by both cmd.exe, and by
CommandLineToArgvW.
If like_cmd is true, then this will emulate both cmd.exe and
CommandLineToArgvW. Since cmd.exe is a shell, a... | 625941d4796e427e537b07ab |
def _put(d, k, item): <NEW_LINE> <INDENT> if "." in k: <NEW_LINE> <INDENT> key, rest = k.split(".", 1) <NEW_LINE> if key not in d: <NEW_LINE> <INDENT> logger.debug("_put: [%s] doesn't exist, creating..." % (key)) <NEW_LINE> d[key] = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if rest and not type(d[key]) == dict: ... | This is a simple yet powerful function!
Recursively drills down into the provided dictionary (d),
creating keys along the way if needed,
to ultimately set the desired key (k) to the provided value (item.) | 625941d4aad79263cf390c27 |
def asarray(a, dtype=None): <NEW_LINE> <INDENT> return core.array(a, dtype, False) | Converts an object to array.
This is equivalent to ``array(a, dtype, copy=False)``.
This function currently does not support the ``order`` option.
Args:
a: The source object.
dtype: Data type specifier. It is inferred from the input by default.
Returns:
cupy.ndarray: An array on the current device. If ``... | 625941d496565a6dacc8f8ae |
def test_success_getting_by_owner(self): <NEW_LINE> <INDENT> response = self.make_request() <NEW_LINE> self.assertEqual(200, response.status_code, "'OK' status code is expected.") <NEW_LINE> self.assertEqual('application/octet-stream', response.content_type, "Has to be an octet-stream.") <NEW_LINE> self.assertEqual(sel... | Download public served file by owner with all valid params. | 625941d463b5f9789fde72c9 |
def test_consume_with_orphan_build(self, caplog): <NEW_LINE> <INDENT> caplog.set_level(logging.DEBUG) <NEW_LINE> self.handler(self.sample_message) <NEW_LINE> build = self.db.query(Build).filter_by(nvr=self.sample_nvr).one() <NEW_LINE> update = build.update <NEW_LINE> build.update = None <NEW_LINE> self.db.delete(update... | Assert existing builds without an update can be handled.
Such builds can exist e.g. if they're used in a buildroot override. | 625941d4d4950a0f3b08c532 |
def get_context(self, request, *args, **kwargs): <NEW_LINE> <INDENT> context = super().get_context(request, *args, **kwargs) <NEW_LINE> context['HELLO'] = "DUDE, YOU'RE GETTIN A DELL" <NEW_LINE> context['services'] = ServicePage.objects.live().public() <NEW_LINE> return context | override of a Page method | 625941d4a8370b7717052a82 |
def _make_partition(file_name, endpoint, total): <NEW_LINE> <INDENT> name = file_name.split(endpoint)[-1] <NEW_LINE> url = 'https://download.open.fda.gov' + endpoint + name <NEW_LINE> file_size = os.path.getsize(file_name)/1024/1024.0 <NEW_LINE> return { 'display_name': _make_display_name(endpoint, name), 'file': url, ... | Helper function for making the partition object that is appended to
manifest.partitions list. | 625941d4dd821e528d63b38c |
def print_status(self, info, num_execs, start): <NEW_LINE> <INDENT> elapsed = max(int(time.time() - start), 1) <NEW_LINE> exec_s = num_execs // elapsed <NEW_LINE> cov = sum(len(edges) for edges in self.edges.values()) <NEW_LINE> print('#{} {} cov: {} corpus: {} exec/s: {}'.format( num_execs, info, cov, len(self.corpus)... | 打印状态
:param info:
:param num_execs:
:param start:
:return: | 625941d44e696a04525c962f |
def field_rows(self, well_row, well_column): <NEW_LINE> <INDENT> imgs = self.well_images(well_row, well_column) <NEW_LINE> return list(set([attribute(img, 'y') for img in imgs])) | Field rows for given well. Equivalent to --Y in files.
Parameters
----------
well_column : int
Starts at 0. Same as --U in files.
well_row : int
Starts at 0. Same as --V in files.
Returns
-------
list of ints
Rows found for specified well. | 625941d445492302aab5e4a9 |
def yield_indices(index_spec): <NEW_LINE> <INDENT> if index_spec is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif ":" in index_spec: <NEW_LINE> <INDENT> i0, i1 = [int(i) for i in index_spec.split(":")] <NEW_LINE> if i0 > i1: <NEW_LINE> <INDENT> for i in range(i1, i0 + 1): <NEW_LINE> <INDENT> yield i <NEW_LI... | Given an index specification string as "<i1>:<i0>" or "<i>" yields all bits
that it is comprised of. The function also supports cases when i0 > i1. | 625941d456ac1b37e62643b1 |
def list_queue_members(self): <NEW_LINE> <INDENT> res = self._list_model(model=models.QueueMember) <NEW_LINE> return res | Retrieve a list of queue members. | 625941d48e05c05ec3eea55a |
def get_all_cities(): <NEW_LINE> <INDENT> url = 'http://pm25.in/' <NEW_LINE> city_list = [] <NEW_LINE> r = requests.get(url, timeout=30) <NEW_LINE> soup = BeautifulSoup(r.text, 'lxml') <NEW_LINE> city_div = soup.find_all('div', class_="bottom")[1] <NEW_LINE> city_link_list = city_div.find_all('a') <NEW_LINE> for city_l... | 获取所有城市及url | 625941d4dc8b845886cb571a |
def GBFS(s0, trans, goal, h): <NEW_LINE> <INDENT> print('Running gbfs:') <NEW_LINE> open = PriorityQueue() <NEW_LINE> open.push(Node(s0)) <NEW_LINE> visited = set() <NEW_LINE> while open: <NEW_LINE> <INDENT> n = open.pop() <NEW_LINE> visited.add(n.s) <NEW_LINE> if n.s in goal: <NEW_LINE> <INDENT> path = n.path() <NEW_L... | Performs a greedy best-first search.
Performs a greedy best-first search starting from state s0 and trying to
reach goal state, if it exists. Search also prints out the results if the
path is found.
Args:
s0: String representing the name of the starting state.
trans: A dictionary containing list of possible t... | 625941d46aa9bd52df036f88 |
def emptyRecentFilesList(self): <NEW_LINE> <INDENT> for i in xrange( int( Settings.instance().readValue( key = 'Common/nb-recent-files-max' ) ) ): <NEW_LINE> <INDENT> self.listActionsRecentFiles[i].setText( "%s:" % str(i+1) ) <NEW_LINE> <DEDENT> self.saveToRecent(data=b'') <NEW_LINE> self.recentMenu.setEnabled(False) <... | Remove all files from the recent list | 625941d4379a373c97cfad29 |
def errorPropagatorDifference(num, den, dnum, dden): <NEW_LINE> <INDENT> a, b = np.real(num), np.imag(num) <NEW_LINE> x, y = np.real(den), np.imag(den) <NEW_LINE> da, db = np.real(dnum), np.imag(dnum) <NEW_LINE> dx, dy = np.real(dden), np.imag(dden) <NEW_LINE> mag = np.abs(num-den) <NEW_LINE> dmag = np.sqrt(((da**2+dx*... | Do error propagation for two calculations on two complex numbers. Calculates
|num-den| and angle(num-den), and provides errors on them. Error propagation
determiend by calculating |num-den| = sqrt((a+ib-(x+iy)) * (a-ib-(x-iy))),
and doing error propagation on that. Similar for the angle, where angle=arctan(
num/den). P... | 625941d41f037a2d8b9463e2 |
def clean_username(self): <NEW_LINE> <INDENT> username = self.cleaned_data["username"] <NEW_LINE> try: <NEW_LINE> <INDENT> User.objects.get(username__iexact=username) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> return username <NEW_LINE> <DEDENT> raise forms.ValidationError(_("A user with that use... | Ensure that the supplied username is unique. | 625941d423849d37ff7b3272 |
def item_get_attribute(self, key, attrib_name, default=None): <NEW_LINE> <INDENT> item = self._items.get(key, None) <NEW_LINE> if item is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attrib = item[1] <NEW_LINE> if attrib is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return getattr(attrib, at... | Params
------
Arg1: key: name of the item
Arg2: attrib_name: name of the attribute
Retrieves the value of the attribute previously assigned with item_set_attribute | 625941d4187af65679ca5303 |
def __init__(self, source_input_ids, target_input_ids, num_units, num_layers, source_vocab_size, target_vocab_size, target_sequences_lengths, train_test_predict, grad_clip_norm, learning_rate, target_vocab_char_to_int, batch_size, max_sequences_length, keep_prob=1.0, start_tokens=None, end_token=None): <NEW_LINE> <INDE... | Implement the Seq2seq_model
:param source_input_ids: a batch of source inputs with shape (batch_size, source_time_steps)
:param target_input_ids: a batch of target inputs with shape (batch_size, target_time_steps)
:param num_units: number of hidden units
:param num_layers: number of MultiRNNCell layers
:param source_v... | 625941d410dbd63aa1bd2d86 |
def surf_noalt(self, name, alpha=True) : <NEW_LINE> <INDENT> if name == None : <NEW_LINE> <INDENT> name = '' <NEW_LINE> <DEDENT> if name not in self.surfaces : <NEW_LINE> <INDENT> self.create_surf(name, alpha) <NEW_LINE> <DEDENT> surface = self.surfaces[name] <NEW_LINE> return surface | generate and return only pygame surface | 625941d463d6d428bbe446d3 |
def singleNumber(self, nums): <NEW_LINE> <INDENT> return reduce(lambda i, j: int(i) ^ int(j), nums) | :type nums: List[int]
:rtype: int | 625941d491f36d47f21ac6d8 |
def put(self, value, wait=False, timeout=30.0, use_complete=False, callback=None, callback_data=None): <NEW_LINE> <INDENT> if not self.wait_for_connection(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif (self.ftype in (dbr.ENUM, dbr.TIME_... | Set value for PV.
optionally waiting until the processing is
complete, and optionally specifying a callback function to be run
when the processing is complete. | 625941d423e79379d52ee746 |
def test_create_container(self): <NEW_LINE> <INDENT> suffix = datetime.utcnow().strftime('%Y%m%d%H%M%S%m') <NEW_LINE> containerName = TEST_CONTAINER_PREFIX + suffix <NEW_LINE> response = self.swift_operations.create_container(containerName) <NEW_LINE> self.assertIsNone(response) <NEW_LINE> self.test_world['containers']... | Test if it can be possible create a new container into the object storage. | 625941d45e10d32532c5f10b |
@pytest.fixture(scope='module', autouse=True) <NEW_LINE> def numpy_extension(): <NEW_LINE> <INDENT> jsonpickle.ext.numpy.register_handlers() <NEW_LINE> yield <NEW_LINE> jsonpickle.ext.numpy.unregister_handlers() | Initialize the numpy extension for this test module | 625941d485dfad0860c3b03f |
def peaks(x, y, params): <NEW_LINE> <INDENT> data = fitlib.fixed_width_predictor( x=x, y=y, params=params ) <NEW_LINE> return data | Returns peaks for x and y data | 625941d4d7e4931a7ee9e102 |
def test_clone_burst_configuration(self): <NEW_LINE> <INDENT> first_burst = TestFactory.store_burst(self.test_project.id) <NEW_LINE> cloned_burst = first_burst.clone() <NEW_LINE> self._compare_bursts(first_burst, cloned_burst) <NEW_LINE> self.assertEqual(first_burst.selected_tab, cloned_burst.selected_tab, "Selected ta... | Test that all the major attributes are the same after a clone burst but the
id of the cloned one is None. | 625941d4627d3e7fe0d69035 |
def save_images(self, sess, epoch): <NEW_LINE> <INDENT> if not os.path.exists(self._images_dir): <NEW_LINE> <INDENT> os.makedirs(self._images_dir) <NEW_LINE> <DEDENT> names = ['inputA_', 'inputB_', 'fakeA_', 'fakeB_', 'cycA_', 'cycB_'] <NEW_LINE> with open(os.path.join( self._output_dir, 'epoch_' + str(epoch) + '.html'... | Saves input and output images.
:param sess: The session.
:param epoch: Currnt epoch. | 625941d429b78933be1e588d |
def get_email_event_subscriptions(self, event_ids=None, limit=None, offset=None, order=None, sort_by=None, headers=None, **request_parameters): <NEW_LINE> <INDENT> check_type(headers, dict) <NEW_LINE> check_type(event_ids, basestring) <NEW_LINE> check_type(offset, int) <NEW_LINE> check_type(limit, int) <NEW_LINE> check... | Gets the list of email Subscriptions's based on provided offset and limit .
Args:
event_ids(basestring): eventIds query parameter. List of email subscriptions related to the respective
eventIds (Comma separated event ids) .
offset(int): offset query parameter. The number of Subscriptions's to offset in... | 625941d43346ee7daa2b2f51 |
def CenterOfBoundBox(self, tolerance: Optional[float] = None) -> Vector: <NEW_LINE> <INDENT> return self.BoundingBox(tolerance=tolerance).center | :param tolerance: Tolerance passed to the :py:meth:`BoundingBox` method
:returns: Center of the bounding box of this shape | 625941d499fddb7c1c9de575 |
def test_thumbnail(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> manager = MockManager() <NEW_LINE> model = Model(manager, data, "/uri/1") <NEW_LINE> model.thumbnail() <NEW_LINE> manager._make_request.assert_called_with('get', '/uri/1/thumbnail') | Check that thumbnail() runs without error | 625941d44f88993c3716c24b |
def imges_means(self): <NEW_LINE> <INDENT> img_means = [] <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> img_means.append(np.mean(self.x_train[self.y_train == i], axis=0)) <NEW_LINE> <DEDENT> img_means = np.array(img_means) <NEW_LINE> return img_means[:, :, :, np.newaxis] | calculate the mean of pre iamge
:return: img_means np.array | 625941d46e29344779a627f5 |
def pathway(nodes): <NEW_LINE> <INDENT> steps = [] <NEW_LINE> for i in range(len(nodes) - 1): <NEW_LINE> <INDENT> steps.append((nodes[i], nodes[i + 1])) <NEW_LINE> <DEDENT> steps.append((nodes[-1], nodes[0])) <NEW_LINE> return steps | Converts a list of joined nodes into the pairwise steps
Parameters
----------
nodes : list
list of integers of nodes to convert
Returns
-------
List of tuples of edges involved in pathway | 625941d4adb09d7d5db6c973 |
def _state_changed_listener(self, event): <NEW_LINE> <INDENT> self._states[event.data['entity_id']] = event.data['new_state'] | Listens for state changed events and applies them. | 625941d4b830903b967e9aee |
def setup_method(self): <NEW_LINE> <INDENT> self.session = FakedSession('fake-host', 'fake-hmc', '2.13.1', '1.8') <NEW_LINE> self.client = Client(self.session) <NEW_LINE> self.faked_cpc = self.session.hmc.cpcs.add({ 'object-id': 'fake-cpc1-oid', 'parent': None, 'class': 'cpc', 'name': CPC_NAME, 'description': 'CPC #1 (... | Setup that is called by pytest before each test method.
Set up a faked session, and add a faked CPC in DPM mode without any
child resources. | 625941d4d8ef3951e3243722 |
def check_table_dtypes(table, key_dtype, value_dtype): <NEW_LINE> <INDENT> if key_dtype.base_dtype != table.key_dtype: <NEW_LINE> <INDENT> raise TypeError("Invalid key dtype, expected %s but got %s." % (table.key_dtype, key_dtype)) <NEW_LINE> <DEDENT> if value_dtype.base_dtype != table.value_dtype: <NEW_LINE> <INDENT> ... | Check that the given key_dtype and value_dtype matches the table dtypes.
Args:
table: The table to check types against to.
key_dtype: The key data type to check.
value_dtype: The value data type to check.
Raises:
TypeError: when 'key_dtype' or 'value_dtype' doesn't match the table data
types. | 625941d4d6c5a10208144230 |
def copy(self, cr, uid, id, default=None, context=None): <NEW_LINE> <INDENT> line_facade = self.pool.get('account.balance.reporting.template.line') <NEW_LINE> template = self.browse(cr, uid, id) <NEW_LINE> new_id = self.create(cr, uid, { 'name': '%s*' % template.name, 'type': 'user', 'report_xml_id': template.report_xm... | Redefine the copy method to perform it correctly as the line
structure is a graph. | 625941d45f7d997b87174c7d |
def GetGlobalVariable(self, name): <NEW_LINE> <INDENT> return value(LazyTarget.GetTarget().FindGlobalVariables(name, 0).GetValueAtIndex(0)) | Get the value object representation for a kernel global variable
params:
name : str - name of the variable. ex. version
returns: value - python object representing global variable.
raises : Exception in case the variable is not found. | 625941d48a349b6b435e8358 |
@when('User makes {authenticated} {request_type} request {request_template_name} to endpoint {endpoint} containing') <NEW_LINE> def make_template_request(context: Context, authenticated: str, request_type: str, request_template_name: str, endpoint: str): <NEW_LINE> <INDENT> body_values = {} <NEW_LINE> if context.table ... | get the template, populate values from table, post results to context | 625941d48c3a87329515859f |
def list_address_groupings(self) -> list: <NEW_LINE> <INDENT> return self.__rpc.batch(["listaddressgroupings"]) | Lists groups of addresses which have had their common ownership made public by common use as inputs or as
the resulting change in past transactions
Returns
-------
list
[
[
[
"address", (string) The bitcoin address
amount, (numeric) The amoun... | 625941d44d74a7450ccd43a8 |
def paintEvent(self, event): <NEW_LINE> <INDENT> metric = self.fontMetrics() <NEW_LINE> if metric.width(self.__text) > self.contentsRect().width(): <NEW_LINE> <INDENT> QLabel.setText(self, metric.elidedText(self.__text, Qt.ElideMiddle, self.width())) <NEW_LINE> if self.__customTooltip is None: <NEW_LINE> <INDENT> QLabe... | Called when painting is required | 625941d4be383301e01b5668 |
def _get_or_create_task_state_for_key( self, task_key, in_progress_states_by_key=None ): <NEW_LINE> <INDENT> if task_key in self._saved_task_states_by_key: <NEW_LINE> <INDENT> return self._saved_task_states_by_key[task_key] <NEW_LINE> <DEDENT> if in_progress_states_by_key is None: <NEW_LINE> <INDENT> in_progress_states... | Constructs a TaskState for a task key. The TaskState is memoized, so subsequent
requests for the same key are fast and always return the same object. | 625941d40c0af96317bb83cd |
def _chk_space(self, fl, main_template, sub_template, name): <NEW_LINE> <INDENT> kws = ['sr0', '.iso', 'tmpfs'] <NEW_LINE> lns = self._format_file_content(fl) <NEW_LINE> if lns: <NEW_LINE> <INDENT> lns = [ tuple(ln.split()) for ln in lns if not any(kw in ln for kw in kws) ] <NEW_LINE> disks = [] <NEW_LINE> for tp in ln... | This function is for the following chk_disk and chk_inode | 625941d48c0ade5d55d3eba0 |
def test_save_contact(cursor): <NEW_LINE> <INDENT> with cursor as cur: <NEW_LINE> <INDENT> cur.execute("SELECT * FROM contact") <NEW_LINE> contacts = cur.fetchall() <NEW_LINE> assert len(contacts) == 0 <NEW_LINE> save(cursor=cur, name="Guilherme", phone="3333-3333") <NEW_LINE> cur.execute("SELECT * FROM contact") <NEW_... | [Scenario] Save contact.
[Assertion] That contact was saved. | 625941d4099cdd3c635f0e3f |
def tree_to_df(tree, branch): <NEW_LINE> <INDENT> array = tree.AsMatrix(columns=[branch]) <NEW_LINE> df = pd.DataFrame() <NEW_LINE> df[branch] = array.ravel() <NEW_LINE> return df | Converts a branch of a tree into an
dataframe. Useful for plotting.
Parameters
----------
tree: TTree
tree were the data is
branch: str
branch to plot
Returns
-------
df : pd.DataFrame
dataframe containing the ``branch`` | 625941d42eb69b55b151ca95 |
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: <NEW_LINE> <INDENT> graph = DefaultDict(set) <NEW_LINE> seen = set() <NEW_LINE> def dfs(source, target): <NEW_LINE> <INDENT> if source not in seen: <NEW_LINE> <INDENT> seen.add(source) <NEW_LINE> if source == target: return True <NEW_LINE> return a... | For each edge (u, v), traverse the graph with a depth-first search
to see if we can connect u to v. If we can, then it must be the duplicate edge.
Time Complexity: O(N^2) where N is the number of vertices
(and also the number of edges) in the graph.
In the worst case, for every edge we include,
we have to search e... | 625941d45166f23b2e1a533d |
def qteGetAppletFromWidget(widgetObj): <NEW_LINE> <INDENT> if widgetObj is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if hasattr(widgetObj, '_qteAdmin'): <NEW_LINE> <INDENT> return widgetObj._qteAdmin.qteApplet <NEW_LINE> <DEDENT> visited = [widgetObj] <NEW_LINE> wid = widgetObj.parent() <NEW_LINE> while... | Return the parent applet of ``widgetObj``.
|Args|
* ``widgetObj`` (**QWidget**): widget (if any) for which the
containing applet is requested.
|Returns|
* **QtmacsApplet**: the applet containing ``widgetObj`` or **None**.
|Raises|
* **None** | 625941d4cb5e8a47e48b7c8d |
def tokenize(x, stem=False, lemma=False): <NEW_LINE> <INDENT> x = re.sub(r'(?:<[^>]+>)', '', x) <NEW_LINE> pattern = '0-9 $ ` % {} <> -,: _ \ . = +| /' <NEW_LINE> x = re.sub(r'(pattern)', '', x) <NEW_LINE> tokens = word_tokenize(x) <NEW_LINE> tokens = [token for token in tokens if token not in stopwords.words('english'... | html tags, numbers, and special characters in each paragraph are replaced with space and sentences are tokenized.
Apply stemming/lemmatization and return tokens.
:param x: paragraph
:param stem: apply stemming if stem is true
:param lemma: apply lemmatization of lemma is true
:return: tokens | 625941d407d97122c4178a72 |
def observe(self, observation): <NEW_LINE> <INDENT> if self.use_batch_act: <NEW_LINE> <INDENT> self.lastY = self.lastYs[self.batchindex] <NEW_LINE> self.lastYs[self.batchindex] = None <NEW_LINE> <DEDENT> if hasattr(self, 'lastY') and self.lastY is not None: <NEW_LINE> <INDENT> self.metrics.update(observation, self.last... | Process observation for metrics. | 625941d482261d6c526ab686 |
def test_users_get_timesheet_users(self): <NEW_LINE> <INDENT> pass | Test case for users_get_timesheet_users
Get users accounts in your organisation. Requires the 'ManageOrganisationUsers' or 'ManageOrganisationGroups' permissions. # noqa: E501 | 625941d4460517430c394367 |
def revoke_leadership(self, broker_ids): <NEW_LINE> <INDENT> for b_id in broker_ids: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> broker = self.cluster_topology.brokers[b_id] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.log.error("Invalid broker id %s.", b_id) <NEW_LINE> raise InvalidBrokerIdError( "Br... | Revoke leadership for given brokers.
:param broker_ids: List of broker-ids whose leadership needs to be revoked. | 625941d4f548e778e58cd763 |
def validate_license(key: str) -> bool: <NEW_LINE> <INDENT> return_value = True <NEW_LINE> key_list = key.split('-') <NEW_LINE> if len(key_list) != 5: <NEW_LINE> <INDENT> return_value = False <NEW_LINE> <DEDENT> elif key_list[0] != 'PB': <NEW_LINE> <INDENT> return_value = False <NEW_LINE> <DEDENT> for key_part in key_l... | Write a regex that matches a PyBites license key
(e.g. PB-U8N435EH-PG65PW87-IXPWQG5T-898XSZI4) | 625941d4b7558d58953c50f7 |
def get_data(): <NEW_LINE> <INDENT> data = pd.read_csv('./data.csv') <NEW_LINE> data.colums = ['id', 'x1', 'x2', 'x3', 'y'] <NEW_LINE> return data | get data | 625941d45fcc89381b1e18a5 |
def magic_list(num): <NEW_LINE> <INDENT> return list(filter(magic, range(2,num+1))) | creates a list of all magical numbers from 2 to num | 625941d4bd1bec0571d90814 |
def test_guppy_watchlist(self, generate_spotter): <NEW_LINE> <INDENT> spots = generate_spotter <NEW_LINE> assert "NASA941" in spots.watchlist_rn.keys() <NEW_LINE> assert spots.watchlist_rn["NASA941"]["desc"] == "NASA Super Guppy" <NEW_LINE> assert spots.watchlist_rn["NASA941"]["img"] == "" | Check that the Super Guppy entry in valid_watchlist is properly imported | 625941d4dd821e528d63b38d |
def _envelope_absint(self, tau=44): <NEW_LINE> <INDENT> dLTI=scipy.signal.StateSpace((1-1/tau),1,1/tau,0,dt=1) <NEW_LINE> _, ih, _ = scipy.signal.dlsim(dLTI,numpy.abs(self.array)) <NEW_LINE> return Env(ih.reshape(-1),rate=self.rate,delay=self.delay,tjust=self.tjust) | Calculate de envelope as the LTI of the absolute value
tau - integer
Characteristic time of the decay of the LTI integration, mesured in samples
| 625941d4283ffb24f3c55ae5 |
def searchFAQs(self, search_text=None, owner=None, sort=None): <NEW_LINE> <INDENT> return FAQSearch( search_text=search_text, owner=owner, sort=sort, project=self).getResults() | See `IQuestionCollection`. | 625941d4462c4b4f79d1d8b5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.