code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_logger(self): <NEW_LINE> <INDENT> return self.logger | Returns the default logger object of python
| 625941c557b8e32f524834a9 |
def check_for_missing_files(self, path): <NEW_LINE> <INDENT> return None | Return a list of necessary files for the current type of dataset that are missing in the given folder. None if path seems valid. | 625941c566656f66f7cbc1b9 |
@register.filter(name='alarm_status') <NEW_LINE> def alarm_status(value): <NEW_LINE> <INDENT> return get_status_value(value, STATUS) | alarm status | 625941c53539df3088e2e35a |
def upscale(self, input_directory, output_directory, scale_ratio, upscaler_exceptions, push_strength=None, push_grad_strength=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return_value = 0 <NEW_LINE> extracted_frame_files = [f for f in input_directory.iterdir() if str(f).lower().endswith('.png') or str(f).lower()... | Anime4K wrapper
Arguments:
file_in {string} -- input file path
file_out {string} -- output file path
Keyword Arguments:
scale {int} -- scale ratio (default: {None})
push_strength {int} -- residual push strength (default: {None})
push_grad_strength {int} -- residual gradient push strength (default:... | 625941c58e71fb1e9831d7b9 |
def process_com(command): <NEW_LINE> <INDENT> command = delete_spaces(command) <NEW_LINE> command = command.upper() <NEW_LINE> return command | This function returns the command such that it is correct and interpretable by the program.
Input : command, a string
Preconditions :
Output : command, the string but without spaces and containing only uppercase letters. | 625941c5f7d966606f6aa012 |
def getConfGraphics(self): <NEW_LINE> <INDENT> return [{ 'type': hwclass.GRAPHICS, 'device': ( 'spice' if self.conf['display'] in ('qxl', 'qxlnc') else 'vnc'), 'specParams': vmdevices.graphics.makeSpecParams(self.conf)}] | Normalize graphics device provided by conf. | 625941c5cad5886f8bd26fe9 |
def down_list(): <NEW_LINE> <INDENT> query = 'hostgroup=all&style=hostdetail&hoststatustypes=4' <NEW_LINE> down = retrieve_station_status(query) <NEW_LINE> down_numbers = pc_name_to_station_number(down) <NEW_LINE> return down_numbers | Get Nagios page which lists DOWN hosts
:return: set of station number of stations that are DOWN. | 625941c530dc7b7665901977 |
def test_filter_interdiff_opcodes_early_change(self): <NEW_LINE> <INDENT> opcodes = [ ('replace', 2, 3, 2, 3), ] <NEW_LINE> self._sanity_check_opcodes(opcodes) <NEW_LINE> orig_diff = self._build_dummy_diff_data(1, 5, 1, 6, pre_lines_of_context=2) <NEW_LINE> new_diff = self._build_dummy_diff_data(1, 5, 1, 6, pre_lines_o... | Testing filter_interdiff_opcodes with a change early in the file | 625941c597e22403b379cfa8 |
def present_cards_for_selection(self, cards, n_cards=1): <NEW_LINE> <INDENT> cards_selected = [] <NEW_LINE> while len(cards_selected) < n_cards: <NEW_LINE> <INDENT> s = "" <NEW_LINE> for idx, card in enumerate(cards): <NEW_LINE> <INDENT> s += "(" + str(idx + 1) + ") " + str(card) <NEW_LINE> if card != cards[-1]: <NEW_L... | Presents a text-based representation of the game via stdout and prompts a human user for decisions.
:param cards: list of cards in player's hand
:param n_cards: number of cards that player must select
:return: list of n_cards cards selected from player's hand | 625941c59b70327d1c4e0de4 |
def ai_check_bottom_left(self, x, y, grid): <NEW_LINE> <INDENT> if grid[x+1][y-1] and grid[x+2][y-2]: <NEW_LINE> <INDENT> return grid[x+1][y-1] == grid[x+2][y-2] | Returns if both positions to the bottom-left are taken by the same char. | 625941c51f037a2d8b94620d |
def lxml_subelement(self, root, name, text=None, attributes=None): <NEW_LINE> <INDENT> tmp = lxml.etree.SubElement(root, name) <NEW_LINE> if text is not None: <NEW_LINE> <INDENT> tmp.text = text <NEW_LINE> <DEDENT> if attributes is not None: <NEW_LINE> <INDENT> for k, v in attributes.items(): <NEW_LINE> <INDENT> tmp.se... | Method to add a new element to an LXML tree, optionally include text
and a dictionary of attributes. | 625941c5f8510a7c17cf970b |
def get(self, **kwargs): <NEW_LINE> <INDENT> results = self.run(limit=1, **kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> return next(results) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return None | Get first result from this.
Beware: get() ignores the LIMIT clause on GQL queries.
Args:
kwargs: Any keyword arguments accepted by datastore_query.QueryOptions().
Returns:
First result from running the query if there are any, else None. | 625941c54d74a7450ccd41d3 |
def extern(fname): <NEW_LINE> <INDENT> run([fname] + sys.argv[1:]) | Invoke the given 'external' python script. | 625941c5e8904600ed9f1f3a |
def test_iterInterior(self): <NEW_LINE> <INDENT> atoms = [(0, 2), (4, 2), (8, 2)] <NEW_LINE> self.assertEqual(atoms, list(Interval.fromAtoms(atoms).iterInterior())) <NEW_LINE> self.assertEqual([], list(Interval().iterInterior())) | Tests the iterInterior method. | 625941c55e10d32532c5ef36 |
def __init__(self, percentage=None, age=None, **kwargs): <NEW_LINE> <INDENT> super(AgeInsight, self).__init__(percentage=percentage, **kwargs) <NEW_LINE> self.age = age | __init__ method.
:param float percentage: Percentage.
:param str age: Age
:param kwargs: | 625941c594891a1f4081bab8 |
def do_ok(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> min_d = float(str(self.ui.lineEdit_minD.text())) <NEW_LINE> max_d = float(str(self.ui.lineEdit_maxD.text())) <NEW_LINE> tolerance = float(str(self.ui.lineEdit_tolerance.text())) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.ui.label_message... | accept the current set up and return
:return: | 625941c53d592f4c4ed1d080 |
def finishJoin( self, table: sqlalchemy.sql.FromClause, joinOn: List[sqlalchemy.sql.ColumnElement] ) -> None: <NEW_LINE> <INDENT> onclause: Optional[sqlalchemy.sql.ColumnElement] <NEW_LINE> if len(joinOn) == 0: <NEW_LINE> <INDENT> onclause = None <NEW_LINE> <DEDENT> elif len(joinOn) == 1: <NEW_LINE> <INDENT> onclause =... | Complete a join on dimensions.
Must be preceded by call to `startJoin`.
Parameters
----------
table : `sqlalchemy.sql.FromClause`
SQLAlchemy object representing the logical table (which may be a
join or subquery expression) to be joined. Must be the same object
passed to `startJoin`.
joinOn : `list` of `... | 625941c54428ac0f6e5ba801 |
def build_g5_data(life_line_list): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for allegiance in get_allegiances_list(life_line_list): <NEW_LINE> <INDENT> res.append({"key": allegiance, "values": build_values(life_line_list, allegiance)}) <NEW_LINE> <DEDENT> return res | build graph5 data in the following structures {"key": allegiance_name, "values": values_array | 625941c5187af65679ca512d |
def rn_config_adapter(context): <NEW_LINE> <INDENT> return queryUtility(ISmartlinkConfig, name="smartlink_config", context=context) | Form Adapter | 625941c5ec188e330fd5a7b1 |
def _h2_cmp_costheta_ ( h1 , h2 , density = False ) : <NEW_LINE> <INDENT> assert isinstance ( h1 , ROOT.TH2 ) and 2 == h1.dim () , "cmp_cos: invalid type of h1 %s/%s" % ( h1 , type ( h1 ) ) <NEW_LINE> if isinstance ( h2 , ROOT.TH1 ) : <NEW_LINE> <INDENT> assert 2 == h2.dim () , "cmp... | Compare the 2D-historgams (as functions)
Calculate the scalar product and get ``cos(theta)'' from it
>>> h1 = ... ## the first histo
>>> h2 = ... ## the second histo
>>> cos_theta = h1.cmp_cos ( h2 )
- it could be rather slow | 625941c5091ae35668666f70 |
def terminate(self): <NEW_LINE> <INDENT> self.send('end') <NEW_LINE> self.runner.join() <NEW_LINE> return self | Shutdown | 625941c576d4e153a657eb40 |
def process_url(url): <NEW_LINE> <INDENT> import re <NEW_LINE> import numpy as np <NEW_LINE> import pandas as pd <NEW_LINE> if '_en.' in url: language = 'en' <NEW_LINE> elif '_ja.' in url: language = 'ja' <NEW_LINE> elif '_de.' in url: language = 'de' <NEW_LINE> elif '_fr.' in url: language = 'fr' <NEW_LINE> elif '_zh.... | Extracts four variables from URL string:
language: code - with 'na' for 'no language detected'
website: what type of website: 'wikipedia', 'wikimedia', 'mediawiki'
access: type of access: 'all-access', 'desktop', 'mobile-web'
agent: type of agent: 'spider', 'all-agents' | 625941c5d53ae8145f87a282 |
def get_trajectory3(self): <NEW_LINE> <INDENT> positions = [] <NEW_LINE> inds = [ i for i,x in enumerate(self.file_array) if "ATOMIC_POSITIONS" in x ] <NEW_LINE> for ind in inds: <NEW_LINE> <INDENT> these_positions = [ list( map( float, line.strip().split()[1:])) for line in self.file_array[ind+1:ind+self.nat+1] ] <NEW... | returns trajectory as a list of lists
each of which contains on the the
float representations positions of the
atomic species | 625941c5f9cc0f698b14060c |
def _step_train(self, x_train, y_train, x_validation, y_validation): <NEW_LINE> <INDENT> data_size = x_train.shape[0] <NEW_LINE> print("training on ", data_size, "images") <NEW_LINE> history_cbk = self.model.fit_generator( self.train_gen.flow(x_train, y_train, batch_size=self.batch_size), epochs=self.step_epoch, steps_... | do a training on the given data and return the history | 625941c5ff9c53063f47c204 |
@deliverer_bp.route('/delete/<int:reference_id>', methods=['GET']) <NEW_LINE> @deliverer_bp.route('/delete/<int:reference_id>/confirmed/<int:confirmed>', methods=['GET']) <NEW_LINE> def delete(reference_id, confirmed=False): <NEW_LINE> <INDENT> return CrudAction().delete(view, key_name, reference_id, confirmed) | Delete items | 625941c55e10d32532c5ef37 |
def _process(context, action, data_dict): <NEW_LINE> <INDENT> approve = action == 'approve' <NEW_LINE> state = "active" if approve else "deleted" <NEW_LINE> request_status = "active" if approve else "rejected" <NEW_LINE> user = context.get("user") <NEW_LINE> mrequest_id = data_dict.get("mrequest_id") <NEW_LINE> role = ... | Approve or reject member request.
:param member request: member request id
:type member: string
:param approve: approve or reject request
:type accept: boolean | 625941c5a05bb46b383ec832 |
def load_manifest( self ): <NEW_LINE> <INDENT> load_string = open( self.manifest_path, 'r' ).read() <NEW_LINE> self.manifest_dictionary = yaml_load(load_string) | Initialize manifest_dictionary from the existing manifest_path | 625941c5d164cc6175782d5d |
def __str__(self): <NEW_LINE> <INDENT> return 'SpinPack(value=%s, tags=%s, orbitals=%s, matrices=%s)'%(self.value,self.tags,self.orbitals,self.matrices) | Convert an instance to string. | 625941c5bd1bec0571d9063f |
def _init_storage(self): <NEW_LINE> <INDENT> self._armors = None <NEW_LINE> self._shields = None <NEW_LINE> self._weapons = None <NEW_LINE> self._misc = None <NEW_LINE> self._quantitative = None <NEW_LINE> self._magic_attrs = None <NEW_LINE> self._magic_prefixes = None <NEW_LINE> self._magic_suffixes = None <NEW_LINE> ... | Reads files with data about items.
:raises ValueError:
:return: None | 625941c5711fe17d8254237e |
def still_picture(iso=None, s_speed=None): <NEW_LINE> <INDENT> exp_program = {'manual': 1, 'normal': 2, 'ss': 4, 'iso': 9} <NEW_LINE> if (iso is None) and (s_speed is None): <NEW_LINE> <INDENT> exp_mode = 'normal' <NEW_LINE> <DEDENT> elif (not iso is None) and (not s_speed is None): <NEW_LINE> <INDENT> exp_mode = 'manu... | Take picture with user parameter.
:param int or None iso: the ISO value to be set.
:param int or str or None s_speed: the shutter speed to be set. | 625941c58e7ae83300e4afdc |
def sample(self): <NEW_LINE> <INDENT> t, x, y, ps = self.alea.sample() <NEW_LINE> if (x == 0) and (y == 0): <NEW_LINE> <INDENT> return (-1,-1) <NEW_LINE> <DEDENT> s = (int(x), int(y)) <NEW_LINE> if s != self.prevsample: <NEW_LINE> <INDENT> self.prevsample = copy.copy(s) <NEW_LINE> <DEDENT> return self.prevsample | Returns newest available gaze position
arguments
None
returns
sample -- an (x,y) tuple or a (-1,-1) on an error | 625941c58e05c05ec3eea383 |
def request(self, uri, method='GET', body=None, headers=None, redirections=1, connection_type=None): <NEW_LINE> <INDENT> self.requests.append((uri, method, body, headers)) <NEW_LINE> logging.debug('mock request: request(%s, %s, %s, %s, %s, %s)', method, uri, body, headers, redirections, connection_type) <NEW_LINE> resp... | Override to log request and response. | 625941c507f4c71912b11491 |
def handle_endtag(self, tag): <NEW_LINE> <INDENT> res = '</' + tag + '>' <NEW_LINE> self.out.append(res) | Appends the end tags to the output. | 625941c585dfad0860c3ae6a |
def point(self, v, check=True): <NEW_LINE> <INDENT> from sage.rings.infinity import infinity <NEW_LINE> if v is infinity or (isinstance(v, (list,tuple)) and len(v) == 1 and v[0] is infinity): <NEW_LINE> <INDENT> if self.dimension_relative() > 1: <NEW_LINE> <INDENT> raise ValueError("%s not well defined in dim... | Create a point on this projective space.
INPUT:
- ``v`` -- anything that defines a point
- ``check`` -- boolean (optional, default: ``True``); whether
to check the defining data for consistency
OUTPUT: A point of this projective space.
EXAMPLES::
sage: P2 = ProjectiveSpace(QQ, 2)
sage: P2.point([4,5])
... | 625941c57c178a314d6ef46d |
def download(image_bean): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = requests.get(self.url, stream=True) <NEW_LINE> with open('../Warehouse/1.' + fileType, 'wb') as f: <NEW_LINE> <INDENT> for chunk in r.iter_content(10*1024): <NEW_LINE> <INDENT> f.write(chunk) <NEW_LINE> f.flush() <NEW_LINE> <DEDENT> f.close() <N... | 开始下载
| 625941c5e64d504609d74850 |
def __GetMaxTorque(self): <NEW_LINE> <INDENT> return _Box2D.b2MotorJoint___GetMaxTorque(self) | __GetMaxTorque(b2MotorJoint self) -> float32 | 625941c516aa5153ce362488 |
def test_docstring(self): <NEW_LINE> <INDENT> self.assertTrue(len(Review.__doc__) > 1) <NEW_LINE> self.assertTrue(len(Review.__init__.__doc__) > 1) <NEW_LINE> self.assertTrue(len(Review.__str__.__doc__) > 1) <NEW_LINE> self.assertTrue(len(Review.save.__doc__) > 1) <NEW_LINE> self.assertTrue(len(Review.to_dict.__doc__) ... | Checks for docstring | 625941c59c8ee82313fbb784 |
def test_favicon_404(self): <NEW_LINE> <INDENT> treq = self.mkTreq() <NEW_LINE> response = self.successResultOf(treq.get("http://127.0.0.1:8888/favicon.ico")) <NEW_LINE> self.assertEqual(404, response.code) | Requests to ``/favicon.ico`` produce a 404 error. | 625941c5eab8aa0e5d26db68 |
def get_correlated_data_stats( data: np.array ) -> Dict[str, float]: <NEW_LINE> <INDENT> n_features = data.shape[1] <NEW_LINE> corr = pd.DataFrame(data).corr() <NEW_LINE> corr = np.array(corr) <NEW_LINE> assert corr.shape[0] == corr.shape[1] == n_features <NEW_LINE> pair_correlations = [] <NEW_LINE> for i in range(n_fe... | Calculated correlation statistics of the given dataset
:param data: input data
:return: | 625941c54e4d5625662d43e9 |
def post(self): <NEW_LINE> <INDENT> data = json.loads(self.request.body.decode("utf-8")) <NEW_LINE> current_path = data["current_path"] <NEW_LINE> my_output = self.git.init(current_path) <NEW_LINE> self.finish(my_output) | POST request handler, initializes a repository. | 625941c5d58c6744b4257c70 |
def test_blur(): <NEW_LINE> <INDENT> original = load_image(choose_file()) <NEW_LINE> blurred = blur(original) <NEW_LINE> show(original) <NEW_LINE> show(blurred) | (None) -> None
Test the blur function
>>> test_blur() | 625941c5435de62698dfdc5c |
def compute_fr_loss(K, b, X_in, Y_in, nl_params=np.expand_dims(np.array([1.0, 0.0]), 1)): <NEW_LINE> <INDENT> f = np.exp(np.expand_dims(np.dot(X_in, K), 2) + b) <NEW_LINE> fsum = f.sum(1) <NEW_LINE> fsum = np.power(fsum, nl_params[0, :]) / (nl_params[1, :] * fsum + 1) <NEW_LINE> loss = np.mean(fsum, 0) - np.mean(Y_in *... | Compute firing rate and loss.
Args:
K : # n_pix x #SU
b : # SU x # cells
X_in : T x # pixels
Y_in : T x # cells | 625941c55166f23b2e1a5169 |
def parse_local_resources(config): <NEW_LINE> <INDENT> nodes_conf = Config.EXECUTION_NODES.get(config) <NEW_LINE> if nodes_conf: <NEW_LINE> <INDENT> nodes = [] <NEW_LINE> nodes_list = nodes_conf.split(',') <NEW_LINE> for nidx, node in enumerate(nodes_list): <NEW_LINE> <INDENT> nname, _, ncores = node.rpartition(':') <N... | Parse resources passed in configuration.
The user can specify in configuration "virtual" resources such as number of nodes and cores.
Args:
config (dict): QCG-PilotJob configuration
Returns:
Resources: available resources
Raises:
ValueError: in case of missing node configuration or wrong number of cores... | 625941c5baa26c4b54cb1131 |
def __contains__(self, item): <NEW_LINE> <INDENT> def callback(operator, *args): <NEW_LINE> <INDENT> contains = [] <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if isinstance(arg, bool): <NEW_LINE> <INDENT> contains.append(arg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> contains.append(item in arg) <NEW_LINE> <DED... | Containment test. Accepts whatever RecurrentEvent can
test for containment. | 625941c5d486a94d0b98e155 |
def transform(proto): <NEW_LINE> <INDENT> file_name = os.path.basename(proto.filename) <NEW_LINE> module_name = file_name.replace('.proto', '_pb2') <NEW_LINE> proto_module = types.ModuleType(module_name) <NEW_LINE> proto_module._sym_db = _symbol_database.Default() <NEW_LINE> descriptor = _descriptor.FileDescriptor( nam... | 把load生成的对象转换为原生对象
Args:
proto (Protobuf): load返回对象 | 625941c5be383301e01b5499 |
def load_modules(self): <NEW_LINE> <INDENT> for loader_instance, module_name, is_pkg in pkgutil.iter_modules(modules.__path__, modules.__name__ + "."): <NEW_LINE> <INDENT> if is_pkg: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> module = __import__(module_name, globals(), locals(), ["dummy"]... | Load modules. | 625941c5f9cc0f698b14060d |
def no_fill(): <NEW_LINE> <INDENT> renderer.fill_enabled = False | Disable filling geometry. | 625941c54f6381625f114a4c |
def set_generating_bonuses(): <NEW_LINE> <INDENT> generating_bonuses = input("Souhaitez-vous que le jeu génère des bonus/malus ? (o/n) ") <NEW_LINE> while generating_bonuses.lower() != "o" and generating_bonuses.lower() != "n": <NEW_LINE> <INDENT> generating_bonuses = input("Souhaitez-vous que le jeu génère des bonus/m... | Demande à l'utilisateur s'il veut jouer avec des bonus.
:return bool: Jouer avec des bonus. | 625941c5ac7a0e7691ed40df |
def numMagicSquaresInside(self, grid): <NEW_LINE> <INDENT> row = len(grid) <NEW_LINE> col = len(grid[0]) <NEW_LINE> count = 0 <NEW_LINE> for i in range(row - 2): <NEW_LINE> <INDENT> for j in range(col - 2): <NEW_LINE> <INDENT> if self.isMagicSquares(grid, i, j): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDEN... | :type grid: List[List[int]]
:rtype: int | 625941c5d6c5a1020814405a |
def get_path(game_map, start, goal): <NEW_LINE> <INDENT> np.set_printoptions(threshold=np.inf) <NEW_LINE> closed_set = set() <NEW_LINE> came_from = dict() <NEW_LINE> g_score = {start: 0} <NEW_LINE> f_score = {start: heuristic(start, goal)} <NEW_LINE> open_heap = [] <NEW_LINE> heappush(open_heap, (f_score[start], start)... | Implementation of the A* algorithm to find the shortest path
between two points in the map. | 625941c5a219f33f3462897c |
def report_basic_parameters(self, printout=True): <NEW_LINE> <INDENT> title = "Results of file: {}\n".format(self.filename) <NEW_LINE> if self.treatment_type == IMAGING: <NEW_LINE> <INDENT> string = title + "Log is an Imaging field; no statistics can be calculated" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> avg_rms ... | Print the common parameters analyzed when investigating machine logs:
- Log type
- Average MLC RMS
- Maximum MLC RMS
- 95th percentile MLC error
- Number of beam holdoffs
- Gamma pass percentage
- Average gamma value | 625941c59f2886367277a89e |
def _test_get_assets(self, testVersion, validationCallback=None): <NEW_LINE> <INDENT> import octoprint <NEW_LINE> originalVersion = octoprint.__version__ <NEW_LINE> originalDisplayVersion = octoprint.__display_version__ <NEW_LINE> try: <NEW_LINE> <INDENT> octoprint.__version__ = testVersion <NEW_LINE> octoprint.__displ... | Test the get_assets method under OctoPrint 1.3.9 or older. | 625941c529b78933be1e56be |
def set_parent_specification(self, parent_spec): <NEW_LINE> <INDENT> if not isinstance(parent_spec, BaseSpecification): <NEW_LINE> <INDENT> raise BIValueError('Parent specification should has BaseSpecification type') <NEW_LINE> <DEDENT> t_name = parent_spec.type_name() <NEW_LINE> parent_t_name = self.parent_type_name()... | setup parent specification object | 625941c523849d37ff7b30a0 |
def set_default_provider(self, hub=None, group=None, project=None, overwrite=False): <NEW_LINE> <INDENT> if isinstance(hub, AccountProvider): <NEW_LINE> <INDENT> _temp = hub <NEW_LINE> hub = _temp.credentials.hub <NEW_LINE> group = _temp.credentials.group <NEW_LINE> project = _temp.credentials.project <NEW_LINE> <DEDEN... | Set the default provider for IBM Q systems.
Parameters:
hub (str, AccountProvider): A hub name, or Qiskit provider instance
group (str): A group name.
project (str): A project name.
overwrite (bool): Overwrite if already set.
Raises:
KaleidoscopeError: Input not a valid provider.
KaleidoscopeE... | 625941c5cdde0d52a9e53042 |
def test_get(self): <NEW_LINE> <INDENT> self.assertEqual(200, self.response.status_code) | GET /product/list must return status code 200 | 625941c5046cf37aa974cd59 |
def test_parseLines(self): <NEW_LINE> <INDENT> goodlines = open(self.goodciffile).readlines() <NEW_LINE> badlines = open(self.badciffile).readlines() <NEW_LINE> pfile, ptest = self.pfile, self.ptest <NEW_LINE> stru_check = pfile.parseFile(self.goodciffile) <NEW_LINE> stru = ptest.parseLines(goodlines) <NEW_LINE> self.a... | check P_cif.parseLines()
| 625941c5c432627299f04c55 |
def pc_noutput_items_var(self): <NEW_LINE> <INDENT> return _PHY_swig.conv_encode_tag_sptr_pc_noutput_items_var(self) | pc_noutput_items_var(conv_encode_tag_sptr self) -> float | 625941c54527f215b584c469 |
def count_gird_square_claims(file): <NEW_LINE> <INDENT> squares = read_input(file) <NEW_LINE> counts = np.array([0] * (1000 * 1000)) <NEW_LINE> ids = np.array([np.NaN] * (1000 * 1000)) <NEW_LINE> for sq in squares: <NEW_LINE> <INDENT> start_stop_list = coords_to_squares(sq[1], sq[2], sq[3], sq[4]) <NEW_LINE> for pair i... | Count the number of times each grid square is used (claimed) | 625941c54f88993c3716c079 |
def open_utf_8_file(path): <NEW_LINE> <INDENT> fileObj = codecs_open(path, "w", "utf-8") <NEW_LINE> return fileObj | Returns a file descriptor for writing utf-8 encoded strings. | 625941c507d97122c4178899 |
def train(self, sentences, save_loc=None, nr_iter=5): <NEW_LINE> <INDENT> self._sentences = list() <NEW_LINE> self._make_tagdict(sentences) <NEW_LINE> self.model.classes = self.classes <NEW_LINE> for iter_ in range(nr_iter): <NEW_LINE> <INDENT> c = 0 <NEW_LINE> n = 0 <NEW_LINE> for sentence in self._sentences: <NEW_LIN... | Train a model from sentences, and save it at ``save_loc``. ``nr_iter``
controls the number of Perceptron training iterations.
:param sentences: A list or iterator of sentences, where each sentence
is a list of (words, tags) tuples.
:param save_loc: If not ``None``, saves a pickled model in this location.
:param nr... | 625941c53346ee7daa2b2d7c |
def modify(request, **kwargs): <NEW_LINE> <INDENT> msg = {} <NEW_LINE> print(kwargs) <NEW_LINE> pk = kwargs.get("pk") <NEW_LINE> user = get_object_or_404(User, pk=pk) <NEW_LINE> if request.method == "POST": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = request.POST.dict() <NEW_LINE> print(data) <NEW_LINE> User.ob... | 用户更新:
1.通过ID拿到要更新的数据,并传到前端渲染
2.将修改后的数据提交到后端 | 625941c5d268445f265b4e7f |
def cached_remote_resource(url): <NEW_LINE> <INDENT> cache_dir = os.path.join(os.path.expanduser(os.environ["XDG_CACHE_HOME"] if "XDG_CACHE_HOME" in os.environ else "~/.cache"), "iwebd") <NEW_LINE> if not os.path.isdir(cache_dir): <NEW_LINE> <INDENT> os.mkdir(cache_dir) <NEW_LINE> <DEDENT> cache_name = "%s-%s" % (hashl... | Serve a locally cached version of a remote resource | 625941c50a50d4780f666ea2 |
def findBMU(self, inVect): <NEW_LINE> <INDENT> self.diff = inVect.flat - self.som <NEW_LINE> self.sqdiff = self.diff*self.diff <NEW_LINE> self.sumdiff = sum(self.sqdiff, axis=self.dim) <NEW_LINE> self.BMU = unravel_index(argmin(self.sumdiff), self.sumdiff.shape) <NEW_LINE> return self.BMU | Find the best matching unit for this input.
inVect - numpy ndarry
An input vector. | 625941c5442bda511e8be42b |
def remove_if_matching_title(articles: list[Article], titles: list[str]) -> list[Article]: <NEW_LINE> <INDENT> return [a for a in articles if not _is_similar_string_contained(a.title, titles)] | Return all ``articles`` whose titles are not (close to) any of the passed ``titles``. | 625941c5627d3e7fe0d68e5f |
def __init__(self, config: Union[proto.ConnectionConfig, proto.MetadataStoreClientConfig], enable_upgrade_migration: bool = False): <NEW_LINE> <INDENT> self._max_num_retries = 5 <NEW_LINE> if isinstance(config, proto.ConnectionConfig): <NEW_LINE> <INDENT> self._using_db_connection = True <NEW_LINE> migration_options = ... | Initialize the MetadataStore.
MetadataStore can directly connect to either the metadata database or
the MLMD MetadataStore gRPC server.
Args:
config: `proto.ConnectionConfig` or `proto.MetadataStoreClientConfig`.
Configuration to connect to the database or the metadata store server.
enable_upgrade_migration: ... | 625941c51d351010ab855b2d |
def time_active(commit_committed): <NEW_LINE> <INDENT> first_commit = datetime.datetime.combine(datetime.datetime.now().date(), datetime.datetime.now().time()) <NEW_LINE> last_commit = datetime.datetime.combine(datetime.date.min, datetime.time.min) <NEW_LINE> for element_id in commit_committed.keys(): <NEW_LINE> <INDE... | This funtion returns the years, months and days between the first commit committed and the last by the user in the form of a tuple
It needs to have downloaded the full version of the committs_committed | 625941c54d74a7450ccd41d4 |
def save_to_rfont(self): <NEW_LINE> <INDENT> self.bitmaps = {} <NEW_LINE> if self.font is not None: <NEW_LINE> <INDENT> rfont = self.font.rfont <NEW_LINE> if self.basename in rfont: <NEW_LINE> <INDENT> if "%s.layers" % self.font.libkey in rfont[self.basename].lib.keys(): <NEW_LINE> <INDENT> if self.layers == [] and sel... | Save the ColorGlyph data to the ColorFont's RFont/RGlyph. | 625941c515baa723493c3f85 |
@app.route("/api/v1.0/<start>/<end>") <NEW_LINE> def trip_temps(start,end): <NEW_LINE> <INDENT> if end != None: <NEW_LINE> <INDENT> min_avg_max = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)). filter(Measurement.date >= start).filter(Measurement.dat... | Return minimum temperature, the average temperature, and the max temperature for a given start or start-end | 625941c515fb5d323cde0b1e |
def test_create_namespaced_local_subject_access_review(self): <NEW_LINE> <INDENT> pass | Test case for create_namespaced_local_subject_access_review
| 625941c556ac1b37e62641e2 |
def buildAttributeGroupBox(self): <NEW_LINE> <INDENT> groupBox = QGroupBox("Attribute Policy (Colors)") <NEW_LINE> layout = QVBoxLayout() <NEW_LINE> self.attr_propagate = QCheckBox("Propagate attribute scene " + "information (e.g. color maps) to other modules.") <NEW_LINE> self.attr_propagate.setChecked(self.agent.prop... | Layout/construct the AttributeScene UI for this tab. | 625941c5009cb60464c633c3 |
def GetUnusedPort(): <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> s.bind(('localhost', 0)) <NEW_LINE> _, port = s.getsockname() <NEW_LINE> s.close() <NEW_LINE> return port | Finds and returns an unused port. | 625941c585dfad0860c3ae6b |
def modify_image_attributes(self, image, image_name=None, description=None, **ignore): <NEW_LINE> <INDENT> action = const.ACTION_MODIFY_IMAGE_ATTRIBUTES <NEW_LINE> valid_keys = ['image', 'image_name', 'description'] <NEW_LINE> body = filter_out_none(locals(), valid_keys) <NEW_LINE> if not self.conn.req_checker.check_pa... | Modify image attributes.
@param image: the ID of image whose attributes you want to modify.
@param image_name: Name of the image. It's a short name for the image
that more meaningful than image id.
@param description: The detailed description of the image. | 625941c556ac1b37e62641e3 |
def get(self, request, name, pk): <NEW_LINE> <INDENT> game_class = getattr(core.games, name, None) <NEW_LINE> if game_class is None: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> game = get_object_or_404(Game, pk=pk) <NEW_LINE> players = [ user.username for user in game.players.order_by("gameplayers__order") ] ... | Game page. | 625941c5fbf16365ca6f61d2 |
def export_results(self, button): <NEW_LINE> <INDENT> chooser = Gtk.FileChooserDialog( _("Export results to a text file"), self.uistate.window, Gtk.FileChooserAction.SAVE, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE, Gtk.ResponseType.OK)) <NEW_LINE> chooser.set_do_overwrite_confirmation(True) <NEW_LINE> ... | Export the results to a text file. | 625941c516aa5153ce362489 |
def fetch_task_instance( session: Session, dag_id: str, task_id: str, execution_date: datetime, ) -> TaskInstance: <NEW_LINE> <INDENT> return ( session.query(TaskInstance) .filter( TaskInstance.dag_id == dag_id, TaskInstance.task_id == task_id, TaskInstance.execution_date == execution_date, ) .first() ) | Query airflow database for a specific TaskInstance object
:param session: Session Airflow DB Session object
:param dag_id: str ID for DAG
:param task_id: str Task id for DAG's task
:param execution_date: datetime Execution date for DAG run
:return: TaskInstance (maybe None if not found) | 625941c530c21e258bdfa4ad |
def __init__(self, camera, mesh, vertex_shader=VERTEX_SHADER_BASIC, fragment_shader=FRAGMENT_SHADER_COLOR, clip_near=0.001, clip_far=100.0, background_color=(.0, .0, .0), ambient_light=0.15, directional_light_vector=[0., 0., 0.]): <NEW_LINE> <INDENT> app.Canvas.__init__(self, show=False, size=camera.image_size) <NEW_LI... | Initialize the mesh renderer
:param camera: Camera instance
:param mesh: Mesh containing vertices and faces (e.g. fom PyMesh)
:param vertex_shader: Vertex shader code
:param fragment_shader: Fragment shader code
:param clip_near: Cl... | 625941c5796e427e537b05d5 |
def test_dpp_pkex_hostapd_initiator(dev, apdev): <NEW_LINE> <INDENT> check_dpp_capab(dev[0]) <NEW_LINE> hapd = hostapd.add_ap(apdev[0], { "ssid": "unconfigured", "channel": "6" }) <NEW_LINE> check_dpp_capab(hapd) <NEW_LINE> cmd = "DPP_CONFIGURATOR_ADD" <NEW_LINE> res = dev[0].request(cmd); <NEW_LINE> if "FAIL" in res: ... | DPP PKEX with hostapd as initiator | 625941c566673b3332b920a2 |
def validate_name(self, value): <NEW_LINE> <INDENT> return value.encode("ascii", errors="ignore").decode() | Strips invalid characters from and returns the Device name. OpenVPN has
trouble with names that with non-ASCII characters.
:return: | 625941c571ff763f4b54969a |
def get_report(self): <NEW_LINE> <INDENT> self._report = super(AirshipValidator, self).get_report() <NEW_LINE> store_result(self._logger, self._report) <NEW_LINE> return self._report | Return final report as dict | 625941c5796e427e537b05d6 |
def read_hdf5(filename, ondisk=False, dsetname=DEFAULT_DSETNAME): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = h5py.File(filename, 'r') <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if not Path(filename).exists(): <NEW_LINE> <INDENT> raise FileNotFoundError(2, 'No such file or directory', filename) <... | Read an array with attributes from an HDF5 file.
With parameter "ondisk" True it will not be read into memory. | 625941c5596a897236089ad3 |
def test01(self): <NEW_LINE> <INDENT> self.assertRadii(PathThreadMilling.radiiInternal(20, 18, 2, 0.1), (8, 9.113397)) | Verify internal radii with tool crest. | 625941c55fdd1c0f98dc0244 |
def test_send_email(self): <NEW_LINE> <INDENT> form = contact.ContactForm() <NEW_LINE> form.cleaned_data = {} <NEW_LINE> with patch.object(letter.Letter, 'send') as psend: <NEW_LINE> <INDENT> with patch.object(contact.Site.objects, 'get_current') as psite: <NEW_LINE> <INDENT> psite.domain = 'example.com' <NEW_LINE> for... | Send an email | 625941c5be8e80087fb20c56 |
def fichierscore(nomNiveau, sauvegarde): <NEW_LINE> <INDENT> rmSaveStr = 0 <NEW_LINE> if sauvegarde: <NEW_LINE> <INDENT> rmSaveStr = -4 <NEW_LINE> <DEDENT> if not os.path.isfile("./scores/" + nomNiveau[:-4 + rmSaveStr] + "Scores.txt") and nomNiveau != 'NivAlea.txt': <NEW_LINE> <INDENT> with open("./scores/" + nomNiveau... | Cette fonction crée un fichier score pour le niveau si il n'existe pas | 625941c576d4e153a657eb41 |
def part2(lines): <NEW_LINE> <INDENT> area = defaultdict(lambda: None) <NEW_LINE> height = len(lines) <NEW_LINE> width = len(lines[0]) <NEW_LINE> for y, line in enumerate(lines): <NEW_LINE> <INDENT> for x, c in enumerate(line.strip()): <NEW_LINE> <INDENT> if c == "9": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> ar... | >>> part2(load_example(__file__, "9"))
1134 | 625941c5ac7a0e7691ed40e0 |
def call_dog(self): <NEW_LINE> <INDENT> if self.gender == 'male': <NEW_LINE> <INDENT> print('Here ' + self.name + '! Good boy!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Here ' + self.name + '! Good girl!') | call the dog. | 625941c5d8ef3951e324354e |
def settings(): <NEW_LINE> <INDENT> @mc_states.utils.lazy_subregistry_get(__salt__, __name) <NEW_LINE> def _settings(): <NEW_LINE> <INDENT> grains = __grains__ <NEW_LINE> pillar = __pillar__ <NEW_LINE> locations = __salt__['mc_locations.settings']() <NEW_LINE> local_conf = __salt__['mc_macros.get_local_registry']( 'dhc... | dhcpd registry | 625941c529b78933be1e56bf |
def p_hor_subgroup1(p): <NEW_LINE> <INDENT> p[0] = p[1] | hor_subgroup : br_vertical_group | 625941c5460517430c39419a |
def accuracy(y_true, y_pred, binaryClassMatrix=False, sample_mask=None): <NEW_LINE> <INDENT> if binaryClassMatrix: <NEW_LINE> <INDENT> if sample_mask is not None: <NEW_LINE> <INDENT> y_true = np.argmax(y_true, axis=-1) <NEW_LINE> y_pred = np.argmax(y_pred, axis=-1) <NEW_LINE> y_true[sample_mask == 0] = -1 <NEW_LINE> <D... | Compute the accuracy given true and predicted class labels.
If 'binaryClassMatrix' is true, then both y_true and y_pred are matrices
of shape (numSamples, ..., numClasses). A binary array 'sample_mask' must
also be provided to determine which samples to ignore as filler data, where
a weight of 0 (or False) indicates f... | 625941c53539df3088e2e35c |
def add_schema_dirs( self, dir_paths: List[str], rel_path: str = ".", name: str = ROOT_NAMESPACE, allow_dup: bool = False, ) -> int: <NEW_LINE> <INDENT> return self.add_dirs( DataType.SCHEMA, dir_paths, rel_path, name, allow_dup ) | Add schema-data directories, return the number of directories added. | 625941c58e71fb1e9831d7bb |
def update(self, dt, rot, update_coord=True): <NEW_LINE> <INDENT> if update_coord: <NEW_LINE> <INDENT> self._update_coord(dt, rot) <NEW_LINE> <DEDENT> v = self._get_offset_quat() <NEW_LINE> self._draw_quat = apply_rotation(v, rot) <NEW_LINE> self.dest_quat = self._draw_quat / np.abs(self._draw_quat) | Updates generated coordinate.
Args:
dt (float): Time elapsed since last update() call.
rot (float): Rotation quaternion to same frame as camera. | 625941c530dc7b7665901979 |
def test_get_details_filter_size_min_max(self): <NEW_LINE> <INDENT> extra_fixture = self.get_fixture(id=_gen_uuid(), size=18) <NEW_LINE> db_api.image_create(self.context, extra_fixture) <NEW_LINE> extra_fixture = self.get_fixture(id=_gen_uuid(), disk_format='ami', container_format='ami') <NEW_LINE> db_api.image_create(... | Tests that the /images/detail registry API returns list of
public images that have a size less than or equal to size_max
and greater than or equal to size_min | 625941c5dc8b845886cb5545 |
def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.children = [] <NEW_LINE> self.children_str = [] | :param value:String name of the file | 625941c51f037a2d8b94620f |
def compile(*sources, color=None): <NEW_LINE> <INDENT> if color is None: <NEW_LINE> <INDENT> color = DEFAULT_COLOR <NEW_LINE> <DEDENT> parts = [] <NEW_LINE> parts.append("$color_main: %s;" % color) <NEW_LINE> for source in sources: <NEW_LINE> <INDENT> with source.open() as f: <NEW_LINE> <INDENT> content = f.read() <NEW... | Compile multiple SCSS sources together | 625941c566656f66f7cbc1bc |
def uniqueMorseRepresentations(self, words): <NEW_LINE> <INDENT> codes = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."] <NEW_LINE> morse = set() <NEW_LINE> for word in words: <NEW_... | :type words: List[str]
:rtype: int | 625941c5293b9510aa2c32a9 |
def unit_test_placeholder(): <NEW_LINE> <INDENT> pass | An empty test. Needs replacement with actual tests. | 625941c53d592f4c4ed1d082 |
def __init__(self, d, n): <NEW_LINE> <INDENT> d = Integer(d) <NEW_LINE> n = Integer(n) <NEW_LINE> if d < 0: <NEW_LINE> <INDENT> raise ValueError("Degree d must not be negative") <NEW_LINE> <DEDENT> max_n = PrimitiveGroups(d).cardinality() <NEW_LINE> if n > max_n or n <= 0: <NEW_LINE> <INDENT> raise ValueError("Index n ... | The Python constructor.
INPUT/OUTPUT:
See :class:`PrimitiveGroup`.
TESTS::
sage: TestSuite(PrimitiveGroup(0,1)).run()
sage: TestSuite(PrimitiveGroup(1,1)).run()
sage: TestSuite(PrimitiveGroup(5,2)).run()
sage: PrimitiveGroup(6,5)
Traceback (most recent call last):
...
ValueError: Index n... | 625941c5d268445f265b4e80 |
def ceilDiv(n : int, d : int) -> int: <NEW_LINE> <INDENT> return -(n // -d) | Returns the int from the ceil division of n / d.
ONLY use ints as inputs to this function.
For ints, this is faster and more accurate for numbers
outside the precision range of float. | 625941c5287bf620b61d3a76 |
def OnCloseProject(self,e): <NEW_LINE> <INDENT> app.debug_frame.WriteLine("Menu: File -> Close Project") <NEW_LINE> self.CloseProject() | Checks to see if project has changed, if so prompt to save, else close | 625941c54527f215b584c46a |
def feedback(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> content = request.POST.get("feedback") <NEW_LINE> email = request.POST.get("email") <NEW_LINE> name = request.POST.get("name") <NEW_LINE> content = content + "\n\nThis email was sent from: " + name + "... | A form for the user to submit feedback to the developers, sent via email.
| 625941c5d6c5a1020814405b |
def remove_confidence_for_test_verification(self, response: List[TagModel]): <NEW_LINE> <INDENT> for tag in response: <NEW_LINE> <INDENT> del tag['confidence'] <NEW_LINE> <DEDENT> return response | :param response: Response from method being tested
:return: | 625941c5cc40096d61595962 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.