code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def valid(self): <NEW_LINE> <INDENT> self.okbutton.setEnabled(True) <NEW_LINE> palette = self.paramName.palette() <NEW_LINE> palette.setColor(self.paramName.backgroundRole(), self.validColor) <NEW_LINE> self.paramName.setToolTip("") <NEW_LINE> self.paramName.setPalette(palette)
Called when the name is valid.
625941f576e4537e8c351cbb
def test_04_01_regression(self): <NEW_LINE> <INDENT> np.random.seed(0) <NEW_LINE> s = 10 <NEW_LINE> side = 250 <NEW_LINE> mini_side = side // s <NEW_LINE> ct = 20 <NEW_LINE> labels = np.zeros((side, side), int) <NEW_LINE> pts = np.zeros((s * s * ct, 2), int) <NEW_LINE> index = np.arange(pts.shape[0], dtype=float) / ct ...
The set of points given in this case yielded one in the interior
625941f53539df3088e2e98e
def split(A: Point, B: Point, points: List[Point]) -> Tuple[List[Point], List[Point]]: <NEW_LINE> <INDENT> points_up = [p for p in points if ccw(A, B, p) == 1] <NEW_LINE> points_down = [p for p in points if ccw(A, B, p) == -1] <NEW_LINE> return points_up, points_down
Splits list of points into those above the line AB, and those below AB :param A: on point on line :param B: second point on line :param points: list of Points to split :return: List of points above line, list of points below line
625941f556b00c62f0f14ca0
def h_ignore_preconditions(self, node: Node): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> each_value = list(node.state) <NEW_LINE> if len(each_value) == 12: <NEW_LINE> <INDENT> if each_value[4] != 'T': <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> if each_value[7]!= 'T': <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DED...
This heuristic estimates the minimum number of actions that must be carried out from the current state in order to satisfy all of the goal conditions by ignoring the preconditions required for an action to be executed.
625941f50c0af96317bb882a
def calculate_totals(contributors): <NEW_LINE> <INDENT> if not contributors: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> measures = [('sessions', []), ('total_time', timedelta())] <NEW_LINE> sums = [initial for _, initial in measures] <NEW_LINE> for c in contributors: <NEW_LINE> <INDENT> for i in xrange(0, len(measu...
Given list of contributors, calculates aggregate statistics. :return: Fake Contributor tuple which contains the aggregated stats, or None
625941f516aa5153ce362abc
def intersection(arr1, arr2): <NEW_LINE> <INDENT> print(f'Arr1: {arr1}\nArr2: {arr2}') <NEW_LINE> hashset1 = set(arr1) <NEW_LINE> hashset2 = set(arr2) <NEW_LINE> res = list(hashset1 & hashset2) <NEW_LINE> return res
Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
625941f591af0d3eaac9c060
def many(nombre, factory, **kwargs): <NEW_LINE> <INDENT> for i in range(1, nombre + 1): <NEW_LINE> <INDENT> factory(**kwargs)
range qui commence à 1 au lieu de 0
625941f51f037a2d8b94683f
def _dropped_string(ffi_string): <NEW_LINE> <INDENT> pystring = ffi.string(ffi_string) <NEW_LINE> with _lock: <NEW_LINE> <INDENT> lib.python_agent_drop_string(ffi_string) <NEW_LINE> <DEDENT> return pystring
If a function in libAgent returns a string, the caller must drop the string using python_agent_drop_string(). This function handles the conversion to a python string and calling python_agent_drop_string().
625941f5adb09d7d5db6cdce
def image_info(filepath): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return ( magic.Magic(mime=True).from_file(filepath), Image.open(filepath).size ) <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> if not e.message.startswith('cannot identify image file'): <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> ...
get image info `filepath` path to a file returns a tuple of two values 1. mime/type if an image; otherwise None 2. a tuple of (height, width) if an image; otherwise (0,0)
625941f57c178a314d6efaae
def swapPairs(self, head): <NEW_LINE> <INDENT> dummyHead = ListNode(0) <NEW_LINE> dummyHead.next = head <NEW_LINE> t = dummyHead <NEW_LINE> while t: <NEW_LINE> <INDENT> n1 = t.next <NEW_LINE> if not t.next: <NEW_LINE> <INDENT> return dummyHead.next <NEW_LINE> <DEDENT> n2 = t.next.next <NEW_LINE> if not t.next.next: <NE...
Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
625941f566673b3332b926d4
def _test(eps: float, ntests: int) -> None: <NEW_LINE> <INDENT> import math <NEW_LINE> print('-' * 79) <NEW_LINE> print(f'Test eps={eps} ntests={ntests}') <NEW_LINE> err_cnt = 0 <NEW_LINE> for i in range(ntests): <NEW_LINE> <INDENT> pi_e = estimate_pi(eps) <NEW_LINE> if abs(int(math.pi / eps) * eps - int(pi_e / eps) * ...
Test the `pi` estimation with the given precision.
625941f54f88993c3716c6a3
def determinar_cod_def_cuentas(producto): <NEW_LINE> <INDENT> if isinstance(producto, pclases.ProductoCompra): <NEW_LINE> <INDENT> res = determinar_cod_def_cuentas_pc(producto) <NEW_LINE> <DEDENT> elif isinstance(producto, pclases.ProductoVenta): <NEW_LINE> <INDENT> res = determinar_cod_def_cuentas_pv(producto) <NEW_LI...
En función del tipo de producto devolverá la cadena que identifica su código de definición de cuentas. Grupos a crear en Murano: - FIBRA CEMENTO EMBOLSADA - GEOTEXTIL PES - MERCADERIAS - GEOCOMPUESTOS - OTROS PRODUCTOS - ESCAMA DE PET - GRANZA POLIPROPILENO - ADITIVOS GEOTEXTILES - OTROS ADITIVOS FIBRA - ENSIMAJE GEOCE...
625941f58c0ade5d55d3f004
def get_google_link(): <NEW_LINE> <INDENT> url = 'https://www.google.com/covid19/mobility/' <NEW_LINE> response = requests.get(url) <NEW_LINE> soup = BeautifulSoup(response.text, "html.parser") <NEW_LINE> csv_tag = soup.find('a', {"class": "icon-link"}) <NEW_LINE> link = csv_tag['href'] <NEW_LINE> return link
Get link of Google Community Mobility report file Returns: link (str): link of Google Community report file
625941f57d847024c06be905
def generate(self, dest=None, sep=',', reset=False): <NEW_LINE> <INDENT> if reset: <NEW_LINE> <INDENT> self.CALENDAR_DATA = self._gen_calendar_data_template() <NEW_LINE> <DEDENT> if self.include_holidays: <NEW_LINE> <INDENT> self._get_holidays_from_api() <NEW_LINE> <DEDENT> for date in self._gen_dates(): <NEW_LINE> <IN...
Generates the calendar. If reset is True it will reset the cal. If destination is provided it will save the calendar. You can use the sep argument to define the delimiter.
625941f5b7558d58953c5549
def _carrington_offset(dateobs): <NEW_LINE> <INDENT> if dateobs is None: <NEW_LINE> <INDENT> raise ValueError("To perform this transformation the coordinate" " Frame needs a dateobs Attribute") <NEW_LINE> <DEDENT> return sun.heliographic_solar_center(dateobs)[0]
Calculate the HG Longitude offest based on a time
625941f54527f215b584ca94
@app.route("/pdb/query/v4/nodes", methods=["POST"]) <NEW_LINE> def nodes(): <NEW_LINE> <INDENT> return jsonify(_puppetdb_request('nodes', json=request.json, redacted=True))
Nodes endpoint for POST requests. Accepts any POST query to the nodes endpoint, proxy it to PuppetDB and returns a list of simplified objects {'certname': 'hostname.example.com'}.
625941f557b8e32f52483ae3
def wallsAndGates(self, rooms: List[List[int]]) -> None: <NEW_LINE> <INDENT> dirs = [[-1, 0], [1, 0], [0, 1], [0, -1]] <NEW_LINE> rows = len(rooms) <NEW_LINE> cols = len(rooms[0]) <NEW_LINE> queue = list() <NEW_LINE> for r in range(rows): <NEW_LINE> <INDENT> for c in range(cols): <NEW_LINE> <INDENT> if rooms[r][c] == 0...
Do not return anything, modify rooms in-place instead.
625941f55fcc89381b1e1d08
def __init__(self, targetString, w, k, t): <NEW_LINE> <INDENT> self.targetString = targetString <NEW_LINE> self.w = w <NEW_LINE> self.k = k <NEW_LINE> self.t = t <NEW_LINE> self.minimizerMap = {} <NEW_LINE> self.minmerOccurrences = {} <NEW_LINE> print('Value of t:', self.t) <NEW_LINE> baseSet = set('ACGT') <NEW_LINE> f...
The target string is a string/array of form "[ACGT]*". Stores the lexicographically smallest k-mer in each window of length w, such that w >= k positions. This smallest k-mer is termed a minmer. If a minmer occurs in the target sequence more than t times as a minmer then it is omitted from the index, i.e. if the gi...
625941f56aa9bd52df0373eb
@pytest.mark.skipif("Topology <= 3") <NEW_LINE> def test_pki_server_subsystem_cert_find_clone_ca(ansible_module): <NEW_LINE> <INDENT> clone_ca = ansible_module.command('pki-server subsystem-cert-find ' '-i {} ca'.format(constants.CLONECA1_INSTANCE_NAME)) <NEW_LINE> for result in clone_ca.values(): <NEW_LINE> <INDENT> i...
:id: 520d1ea5-b1db-4adf-afc9-b4b3e886093f :Title: Test pki-server subsystem-cert-find clone ca command :Description: test pki-server subsystem-cert-find command :CaseComponent: \- :Requirement: Pki Server Subsystem :Setup: Use the subsystems setup in ansible to run subsystem commands :Steps: :ExpectedResults: 1. ...
625941f50fa83653e46575fa
def items(self): <NEW_LINE> <INDENT> out = [] <NEW_LINE> for d,cs in self.paths: <NEW_LINE> <INDENT> for x in cs: <NEW_LINE> <INDENT> if x not in out: <NEW_LINE> <INDENT> out.append(x) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return out
Returns A List Of Nodes.
625941f5be383301e01b5abc
def _find_closing_token(self, tag, tokens, pos): <NEW_LINE> <INDENT> embed_count = 0 <NEW_LINE> block_count = 0 <NEW_LINE> lt = len(tokens) <NEW_LINE> while pos < lt: <NEW_LINE> <INDENT> token_type, tag_name, tag_opts, token_text = tokens[pos] <NEW_LINE> if tag.newline_closes and token_type in (self.TOKEN_TAG_START, se...
Given the current tag options, a list of tokens, and the current position in the token list, this function will find the position of the closing token associated with the specified tag. This may be a closing tag, a newline, or simply the end of the list (to ensure tags are closed). This function should return a tuple o...
625941f5de87d2750b8603dd
def save_pid(file='my.pid', encoding='utf-8'): <NEW_LINE> <INDENT> pid = os.getpid() <NEW_LINE> write_file(file, str(pid), encoding=encoding)
Save the current process id to file.
625941f599fddb7c1c9de9d0
def test(root, solution): <NEW_LINE> <INDENT> result = minimax(root, root.maximizing, get_children, evaluate, 100, 0.0000001) <NEW_LINE> if not result == solution: <NEW_LINE> <INDENT> print(str.format("Error lors du test (maximize = {:b}) sur l'arbre : ", root.maximizing)) <NEW_LINE> print(root.display()) <NEW_LINE> pr...
Test si minimax appliqué à root renvoie bien la solution
625941f5ff9c53063f47c833
def __init__(self): <NEW_LINE> <INDENT> self.head = ListNode(-1) <NEW_LINE> self.dummy = self.head <NEW_LINE> self.count = 0
Initialize your data structure here.
625941f5de87d2750b8603de
def __init__(self, url, auth_id='', auth_token='', api_version=__VERSION__): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.auth_id = auth_id <NEW_LINE> self.auth_token = auth_token <NEW_LINE> self.opener = None <NEW_LINE> self.api_version = api_version
initialize a object url: Rest API Url auth_id: Plivo SID/ID auth_token: Plivo token returns a Plivo object
625941f555399d3f05588cfc
def convert_to_hours(player_time): <NEW_LINE> <INDENT> if time.gmtime(float(player_time)).tm_yday > 1: <NEW_LINE> <INDENT> hours = time.gmtime(float(player_time)).tm_hour + ((time.gmtime(float(player_time)).tm_yday - 1) * 24) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hours = time.gmtime(float(player_time)).tm_hour ...
Конвертирует дни в часы @param player_time: текущее время до затопления @return: Общее количество часов
625941f5d18da76e23532b22
def helper1(self, prices): <NEW_LINE> <INDENT> if not prices: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> ans = 0 <NEW_LINE> for i in range(1, len(prices)): <NEW_LINE> <INDENT> for j in range(0, i): <NEW_LINE> <INDENT> tmp_ans = prices[i] - prices[j] <NEW_LINE> if tmp_ans > ans: <NEW_LINE> <INDENT> ans = tmp_ans <...
暴力求解, 枚举全部的买卖可能. Time Limit Exceeded.
625941f5ac7a0e7691ed4703
def get_fine_structure_as_spectrum(self): <NEW_LINE> <INDENT> from hyperspy._signals.eels import EELSSpectrum <NEW_LINE> channels = int(np.floor( self.fine_structure_width / self.energy_scale)) <NEW_LINE> data = np.zeros(self.fine_structure_coeff.map.shape + (channels,)) <NEW_LINE> s = EELSSpectrum( data, axes=self.int...
Returns a spectrum containing the fine structure. Notes ----- The fine structure is corrected from multiple scattering if the model was convolved with a low-loss spectrum
625941f5fff4ab517eb2fa84
def list_printers(): <NEW_LINE> <INDENT> return [str(v) for v in common.get_bus().list_names() if str(v).startswith("org.voxelpress.hardware.")]
List all currently existing Printer Servers.
625941f560cbc95b062c6b87
def Getband_names(self): <NEW_LINE> <INDENT> if not self.ds: <NEW_LINE> <INDENT> basic.outputlogMessage('Please Open the file first') <NEW_LINE> return False <NEW_LINE> <DEDENT> names = [self.ds.GetRasterBand(idx+1).GetDescription() for idx in range(self.ds.RasterCount)] <NEW_LINE> return names
get the all the band names (description) in this raster Returns:
625941f5c432627299f0528e
def test_origin_get_latest_visit_status_filter_type(swh_storage, sample_data): <NEW_LINE> <INDENT> objects = init_storage_with_origin_visits(swh_storage, sample_data) <NEW_LINE> origin1, origin2 = objects["origin"] <NEW_LINE> ov1, ov2 = objects["origin_visit"] <NEW_LINE> ovs11, ovs12, _, ovs22 = objects["origin_visit_s...
Filtering origin visit per types should yield consistent results
625941f597e22403b379d5df
def test_get_ticket_fields_milestone_rename(self): <NEW_LINE> <INDENT> fields = self.ticket_system.get_ticket_fields() <NEW_LINE> milestone_field = self._get_ticket_field('milestone') <NEW_LINE> m2 = Milestone(self.env, 'milestone2') <NEW_LINE> m2.name = 'milestone5' <NEW_LINE> m2.update() <NEW_LINE> updated_fields = s...
Cached ticket fields are updated when milestone is renamed.
625941f5d7e4931a7ee9e563
def clear_snat(self): <NEW_LINE> <INDENT> if self.pg7.has_ip4_config: <NEW_LINE> <INDENT> self.pg7.unconfig_ip4() <NEW_LINE> <DEDENT> interfaces = self.vapi.snat_interface_addr_dump() <NEW_LINE> for intf in interfaces: <NEW_LINE> <INDENT> self.vapi.snat_add_interface_addr(intf.sw_if_index, is_add=0) <NEW_LINE> <DEDENT>...
Clear SNAT configuration.
625941f5796e427e537b0c0f
def calculate_route(self, start_point, addresses): <NEW_LINE> <INDENT> map_distances = {} <NEW_LINE> for address in addresses: <NEW_LINE> <INDENT> if address: <NEW_LINE> <INDENT> distance = self.get_distance_between_two_addresses(f'{self.city} {start_point}', f'{self.city} {address}') <NEW_LINE> map_distances[address] ...
Алгоритм 1) Осуществляем поиск всех расстояний от точки начала, сортируем по возрастанию, делим точки на количество автомобилей Повторяем, но с ближайшеми 5 точками, потом завести тест, в котором будет проверятся сильно ли менялся маршрут после пересчета :param addresses: :param city: str Город где строится маршрут :p...
625941f5d99f1b3c44c67bc6
def add_signal_to_noise_metrics(qc_values, qc_names, ms_run): <NEW_LINE> <INDENT> intensity510, percentile_25_from_500, percentile_50_from_500 = s2n_features_names <NEW_LINE> s2n = ms_run['features_values'][ms_run['features_names'].index(intensity510)] / (ms_run['features_values'][ms_run['features_names'].index(percent...
This method calculates metric of signal to background as follows: intensity at mz510 / ( 50th percentile in [500, 550] - 25th percentile in [500, 550]) .
625941f5d8ef3951e3243b81
def show_animes(gan, batch_size, dim_size, epoch, n=10, save=True): <NEW_LINE> <INDENT> noise = np.random.normal(size=(batch_size, dim_size)) <NEW_LINE> images = gan.z2x(noise, MNIST=False) <NEW_LINE> images = (images+1)/2 <NEW_LINE> canvas = np.empty((64 * n, 64 * n, 3)) <NEW_LINE> for i in range(n): <NEW_LINE> <INDEN...
Creates and saves a 'canvas' of images decoded from a grid in the latent space. :param vae: instance of VAE which performs decoding :param batch_size: little hack to get dimensions right :param epoch: current epoch of training :param n: number of points in each dimension of grid :param bound: samples from [-bound, boun...
625941f50a50d4780f6674db
def setup_vehicle(): <NEW_LINE> <INDENT> vehicle = Vehicle( color='dark blue', make='Toyota', model='Corolla', license_plate='1ABC234', ) <NEW_LINE> vehicle.save() <NEW_LINE> return vehicle
Creates a hypothetical vehicle, saves it, and returns it.
625941f53617ad0b5ed6853a
def plot_mc_event(event_id : int, fnames : str, event_type : str ) -> None : <NEW_LINE> <INDENT> fname = get_fname_with_event(event_id, fnames) <NEW_LINE> if fname == '': <NEW_LINE> <INDENT> print(f"\nEvent id: {event_id} NOT FOUND in input mc files.") <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LIN...
Plots the MC information of the event_id.
625941f5fb3f5b602dac3cde
def relativePath(self): <NEW_LINE> <INDENT> return self.relativePath_
Return the path of the current working directory relative to the root directory of the application.
625941f57047854f462a1a46
def _get_info(self): <NEW_LINE> <INDENT> return dict( memory_testing=self._memory_testing, objective=self._objective, angle=self._objective_angle, target_distance=self._target_distance_last, current_level=self._current_level, x_pos=self._x_pixel, y_pos=self._y_pixel, direction=self._direction, map_location=self._map_lo...
Return the info after a step occurs
625941f5b545ff76a8914459
def clean(ast_tuple): <NEW_LINE> <INDENT> result = [] <NEW_LINE> last = None <NEW_LINE> for couple in _clean(ast_tuple): <NEW_LINE> <INDENT> if couple[0] == token.NAME and last == token.DOT: <NEW_LINE> <INDENT> result[-1][1] += couple[1] <NEW_LINE> <DEDENT> elif couple[0] == token.DOT and last == token.NAME: <NEW_LINE>...
reverse ast tuple to a list of tokens merge sequences (token.NAME, token.DOT, token.NAME)
625941f5090684286d50f335
def parseN(self, x): <NEW_LINE> <INDENT> return self._dict[x]
Returns an iterable containing the neighbours of x
625941f5097d151d1a22349a
def __new__(cls, value, name): <NEW_LINE> <INDENT> if name in cls.names: <NEW_LINE> <INDENT> raise ValueError("There is already an enum called %s" % (name,)) <NEW_LINE> <DEDENT> if value in cls.values: <NEW_LINE> <INDENT> raise ValueError( "Error while creating enum %s of type %s, " "it has already been created as %s" ...
Create a new Enum. @param value: value of the enum @param name: name of the enum
625941f5bf627c535bc13813
def CreatePlatformGomacc(distname, platform): <NEW_LINE> <INDENT> if platform in ('linux', 'mac', 'goobuntu', 'chromeos'): <NEW_LINE> <INDENT> gomacc = list(GOMACC_CMDS) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError(platform) <NEW_LINE> <DEDENT> if platform == 'chromeos': <NEW_LINE> <INDENT> g...
Creates gomacc symlinks in distname. Args: distname: distribution directory platform: platform name
625941f58da39b475bd655c0
def list_to_link(lst): <NEW_LINE> <INDENT> if len(lst) == 0: <NEW_LINE> <INDENT> return Link.empty <NEW_LINE> <DEDENT> elif len(lst) == 1: <NEW_LINE> <INDENT> return Link(lst[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Link(lst[0], list_to_link(lst[1:]))
Takes a Python list and returns a Link with the same elements. >>> link = list_to_link([1, 2, 3]) >>> print(link) <1 2 3>
625941f5091ae35668667597
def invoke(self, context, event): <NEW_LINE> <INDENT> self.enter(context) <NEW_LINE> return {'FINISHED'} <NEW_LINE> wm = context.window_manager <NEW_LINE> wm.modal_handler_add(self) <NEW_LINE> return {'RUNNING_MODAL'}
:type context: bpy.types.Context :type event: bpy.types.Event :rtype: set
625941f5e8904600ed9f257c
def get_members_by_name(self, cgname): <NEW_LINE> <INDENT> contactgroup = self.find_by_name(cgname) <NEW_LINE> if contactgroup is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return contactgroup.get_contacts()
Get all members by name given in parameter :param cgname: name of members :type cgname: str :return: list of contacts with this name :rtype: list[alignak.objects.contact.Contact]
625941f5566aa707497f4ba3
def query_db(query, args=(), one=False): <NEW_LINE> <INDENT> cur = get_db().execute(query, args) <NEW_LINE> rv = cur.fetchall() <NEW_LINE> cur.close() <NEW_LINE> return (rv[0] if rv else None) if one else rv
Send query to DB and return tuples one - Return a single tuple
625941f5099cdd3c635f129c
def foreach(f, l, threads=3, return_=False): <NEW_LINE> <INDENT> if threads > 1: <NEW_LINE> <INDENT> iteratorlock = threading.Lock() <NEW_LINE> exceptions = [] <NEW_LINE> if return_: <NEW_LINE> <INDENT> n = 0 <NEW_LINE> d = {} <NEW_LINE> i = zip(count(), l.__iter__()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = l...
Apply f to each element of l, in parallel
625941f58a43f66fc4b546a2
def __set_state(self, state): <NEW_LINE> <INDENT> for key, (klass, value) in state.items(): <NEW_LINE> <INDENT> if klass is Namespace: <NEW_LINE> <INDENT> self.__set_namespace(key, value) <NEW_LINE> <DEDENT> elif klass is Parameter: <NEW_LINE> <INDENT> self.__set_parameter(key, value)
Sets state of instance while validating incoming state.
625941f5b57a9660fec33ed1
def __init__(self, max_size=0, bit_rate=8000000, max_fps=0, crop='-', libs_path='libs', adb_path=r'adb', ip='127.0.0.1', port=27199, queue_length=5): <NEW_LINE> <INDENT> print("Init Scrcpy client") <NEW_LINE> self.max_size = max_size <NEW_LINE> self.bit_rate = bit_rate <NEW_LINE> self.max_fps = max_fps <NEW_LINE> self....
初始化Scrcpy客户端 :param max_size: frame width that will be broadcast from android server :param bit_rate: :param max_fps: 0 means not max fps :param crop: :param libs_path: path to 'scrcpy-server.jar' :param adb_path: path to ADB :param ip: scrcpy server IP :param port: scrcpy server port
625941f5377c676e912727ea
def chrome(self, channel): <NEW_LINE> <INDENT> if channel in self.chrome_path: <NEW_LINE> <INDENT> url = self.chrome_path[channel] <NEW_LINE> name = 'Chrome ' + channel <NEW_LINE> print("Checking {0}...".format(name)) <NEW_LINE> last_modified = None <NEW_LINE> if name in self.status: <NEW_LINE> <INDENT> last_modified =...
Install the given Chrome channel
625941f5fbf16365ca6f6816
def register_gameover(id, game): <NEW_LINE> <INDENT> game['state'] = 'gameover' <NEW_LINE> r.set(id, json.dumps(game)) <NEW_LINE> score = r.zscore("scores" + game['location'], game["username"]) <NEW_LINE> app.logger.debug("SCORE IN BD: " + str(score)) <NEW_LINE> if score is not None: <NEW_LINE> <INDENT> if score < game...
Register in the db this user score and set the state to gameover :param id: :param game: :return:
625941f5fff4ab517eb2fa85
def test_site_admin(self): <NEW_LINE> <INDENT> url = reverse("site_admin") <NEW_LINE> request = fake_request(url=url, data={}, method="GET",user=self.user) <NEW_LINE> response = views.site_admin(request=request) <NEW_LINE> self.assertEqual(response.status_code, 200, "Can not load admin page")
Test site admin page
625941f53346ee7daa2b33b6
def _sensor_last_update(self): <NEW_LINE> <INDENT> return self._cam.sensors[self._sensor][3]
Extract sensor last update time.
625941f54f88993c3716c6a4
def _bert_add_special_tokens_attention_mask(attention_mask, seq_end_col): <NEW_LINE> <INDENT> attention_mask[:, 1:-1] = attention_mask[:, 0:-2] <NEW_LINE> attention_mask[:, 0] = 1 <NEW_LINE> attention_mask[ cp.arange(0, attention_mask.shape[0], dtype=cp.uint32), seq_end_col ] = 1
Mark attention mask for special tokens ([CLS] and [SEP]) with 1
625941f56e29344779a62c55
def change_start_button(event): <NEW_LINE> <INDENT> img_start_button_mouse_over = PhotoImage( file=r"C:\Users\Owner\PycharmProjects\Module14\buttons\start_new_game_raised_active.png") <NEW_LINE> lbl_start_game.config(image=img_start_button_mouse_over) <NEW_LINE> lbl_start_game.image = img_start_button_mouse_over <NEW_L...
This function performs the first portion of a mouse rollover, changing the image :param event: :return:
625941f57c178a314d6efaaf
def to_instructions(self, data): <NEW_LINE> <INDENT> instructions = [] <NEW_LINE> for send_data, newline, send_after in data: <NEW_LINE> <INDENT> if send_after is not None: <NEW_LINE> <INDENT> instructions.append('p.recvuntil(%s)' % repr(send_after.encode('utf8'))) <NEW_LINE> <DEDENT> if newline: <NEW_LINE> <INDENT> in...
Converts the vulnerability data to instructions. Args: data (:obj:`list` of :obj:`list`): Contains a list of lists of the form [data, newline, sendafter] (e.g. [["1", true, "> "], ["vIaDFd7N", true, "Data: "]]) Results: :obj:`list` of :obj:`str`: A list of the converted instructions.
625941f56e29344779a62c56
def is_archived(self): <NEW_LINE> <INDENT> return self.publication == BaseArticle.ARCHIVED
True if archived
625941f52c8b7c6e89b35dff
def accept_plan(self): <NEW_LINE> <INDENT> for i, ex_no in enumerate(self.plan_list): <NEW_LINE> <INDENT> self.plan[ex_no] = {'WO_ID' : self.plan[self.plan_list[0]]['WO_ID'], 'WO_NAME' : self.wo_name.get(), 'WO_DATE' : self.wo_date.get(), 'EX_NO' : ex_no, 'BO_ID' : self.plan[ex_no]['BO_ID'], '...
accepts and saves workout plan into database
625941f5a8370b7717052ee1
@pytest.mark.tier(3) <NEW_LINE> def test_group_description_required_error_validation(appliance): <NEW_LINE> <INDENT> error_text = "Description can't be blank" <NEW_LINE> group_collection = appliance.collections.groups <NEW_LINE> with pytest.raises(Exception, match=error_text): <NEW_LINE> <INDENT> group_collection.creat...
Polarion: assignee: apagac initialEstimate: 1/8h casecomponent: Configuration tags: rbac
625941f5bde94217f368342f
def openssl( self, action, passwd, base64=True, cipher=None, ): <NEW_LINE> <INDENT> if self.io['infile'] and self.io['infile'] == self.io['outfile']: <NEW_LINE> <INDENT> stderr.write("Same file for both input and output, eh? Is it going " "to work? ... NOPE. Chuck Testa.\n") <NEW_LINE> raise Exception("infile, outfile ...
Build an openssl cmdline and then launch it, saving output appropriately. This method inspects the contents of class attr 'io' -- a dict object that should contain all of the following keys, at least initialized to 0 or '': stdin # Input text for subprocess infile # Input filename for subprocess, in...
625941f5d8ef3951e3243b82
def get_test_handler(self, build_id, test_id, handler_info): <NEW_LINE> <INDENT> return BuildloggerTestHandler(self.config, build_id, test_id, **handler_info)
Return the test handler.
625941f563b5f9789fde772a
def add_meta_entries(self, *args, **kwargs): <NEW_LINE> <INDENT> entries = parse_1_args("add_meta_entries", args, kwargs) <NEW_LINE> for name, value in entries.items(): <NEW_LINE> <INDENT> self.add_meta_entry(name, value)
accepts either - one dict: {name: value, ...} - n kwargs: name=value, ...
625941f5cc0a2c11143dd4d6
def set_sample_rate(self, sample_rate_hz: DQEnums.SampleRate): <NEW_LINE> <INDENT> name = "set_desired_sample_rate" <NEW_LINE> self.log.info(name) <NEW_LINE> self.set_sample_rate_hz = sample_rate_hz <NEW_LINE> dividend = DQEnums.DQ4108.ScanRateLimits.DIVIDEND <NEW_LINE> dec = 10 <NEW_LINE> deca = 1 <NEW_LINE> for rate_...
:param dec: decimation/oversampling value :param deca: decimation/oversampling multiplier :param sample_rate_hz: rate to sample given device limitations. See page 47 of Dataq-Instruments-Protocol.pdf :return:
625941f5d18da76e23532b23
def loss_and_accuracy(self, data, inference=False, max_batch=10000): <NEW_LINE> <INDENT> num_samples = data[0].shape[0] <NEW_LINE> loss_total, acc_total = 0.0, 0.0 <NEW_LINE> ptr = 0 <NEW_LINE> while ptr < num_samples: <NEW_LINE> <INDENT> end_ptr = np.minimum(num_samples, ptr + max_batch) <NEW_LINE> x_data, y_data = da...
Compute losses and accuracies Arguments: data {tuple of np float} -- (images, labels) Keyword Arguments: inference {boolean} -- use EMA average values in batch norm layers (default: {False}) max_batch {int} -- Maximum batch size to feed (for GPU memory) (default: {10000}) Returns: tup...
625941f5cdde0d52a9e5367d
def execute(self): <NEW_LINE> <INDENT> if not self.config.pr: <NEW_LINE> <INDENT> raise NotPullRequestException <NEW_LINE> <DEDENT> logger.debug('Using the following configuration:') <NEW_LINE> for name, value in self.config.as_dict().items(): <NEW_LINE> <INDENT> logger.debug(' - {}={}'.format(name, repr(value))) <NEW...
Executes a new build on a project.
625941f596565a6dacc8fd0d
def test_forcedestroy_connected(self): <NEW_LINE> <INDENT> hostlist_servers = self.hostlist_servers[:1] <NEW_LINE> self.start_servers(self.get_group(self.server_group, hostlist_servers)) <NEW_LINE> self.validate_pool_creation(hostlist_servers, self.server_group) <NEW_LINE> self.assertTrue( self.pool.connect(), "Pool co...
Forcibly destroy pool with connected client. Test destroying a pool that has a connected client with force == true. Should pass. :avocado: tags=all,pr,daily_regression :avocado: tags=pool,destroy,force_destroy_connected
625941f5a8ecb033257d370f
def _endElement(self, name): <NEW_LINE> <INDENT> name = self.__node_stack[-1].getName() <NEW_LINE> if name in list(self.__node_end_visit_dict.keys()): <NEW_LINE> <INDENT> self.__node_end_visit_dict[name](self.__node_stack[-1]) <NEW_LINE> <DEDENT> self.__node_stack = self.__node_stack[:-1]
End element event handler.
625941f5dc8b845886cb5b7b
def countData(var): <NEW_LINE> <INDENT> from sklearn.feature_extraction.text import CountVectorizer <NEW_LINE> import numpy as np <NEW_LINE> import seaborn as sns <NEW_LINE> sns.set_style('whitegrid') <NEW_LINE> count_vectorizer = CountVectorizer(stop_words='english') <NEW_LINE> count_data = count_vectorizer.fit_transf...
Gives word frequencies
625941f5ff9c53063f47c834
def executeJSONRPC(jsonrpccommand): <NEW_LINE> <INDENT> return str()
Execute an JSONRPC command. :param jsonrpccommand: string - jsonrpc command to execute. List of commands: http://wiki.xbmc.org/?title=JSON-RPC_API example:: response = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "JSONRPC.Introspect", "id": 1 }')
625941f523e79379d52eeb9f
def test_qpos_invalid_range(self): <NEW_LINE> <INDENT> sim_scene = MockSimScene(nq=2) <NEW_LINE> with self.assertRaises(AssertionError): <NEW_LINE> <INDENT> RobotGroupConfig( sim_scene, qpos_indices=[0, 1], qpos_range=[(0, 1)]) <NEW_LINE> <DEDENT> with self.assertRaises(AssertionError): <NEW_LINE> <INDENT> RobotGroupCo...
Ensures error when invalid qpos range is given.
625941f5796e427e537b0c10
def get_basis(self, degree, i, knots): <NEW_LINE> <INDENT> if degree == 0: <NEW_LINE> <INDENT> def basis_function(t): <NEW_LINE> <INDENT> t_this = knots[i] <NEW_LINE> t_next = knots[i+1] <NEW_LINE> return t_next >= t > t_this <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> def basis_function(t): <NEW_LINE> <INDE...
Returns a basis_function for the given degree
625941f51f5feb6acb0c518d
@net.connect() <NEW_LINE> def subscription_handler(event, host, port, connection, *args, **kwargs): <NEW_LINE> <INDENT> net.Peer().register_subscriber(event, host, port, connection)
Will register the incoming peer and connection with the local peers subscription of the event passed. This is for internal use only. :param event: event id :param host: foreign peer host :param port: foreign peer port :param connection: connection id
625941f5009cb60464c639f1
def test_1_regex(self, pane): <NEW_LINE> <INDENT> fb = pane.formbuilder(cols=2,datapath='.data') <NEW_LINE> fb.textBox(value='^.test',validate_regex=' ^[AB]*$', lbl='Type text', placeholder='Available characters: ^[AB]*$')
Validation regex mechanism: you can indicate which characters are available
625941f55fc7496912cc3fc2
def GetId(self): <NEW_LINE> <INDENT> return self.id
Gets Id of the Association
625941f592d797404e3047d2
def lock(filepath, passphrase, delete_src=False, save_dir=None, save_as=None, compression=COMPRESS_GZIP): <NEW_LINE> <INDENT> archive = os.path.isdir(filepath) <NEW_LINE> master_key = generate_master_key(passphrase) <NEW_LINE> internal_key = random_bytes(SecretBox.KEY_SIZE) <NEW_LINE> save_dir = save_dir or os.path.dir...
Lock a file using the provided passphrase - filepath: path to the plaintext file - passphrase: the passphrase used to encrypt the file. The same is required to decrypt the file - delete_src: Delete the source file after encryption has completed #FIXME: Not currently implemented - save_dir: Where the data should be...
625941f556b00c62f0f14ca2
def minimum_skew(genome: str) -> list: <NEW_LINE> <INDENT> _skew = skew(genome) <NEW_LINE> minimum_skew = min(_skew) <NEW_LINE> min_skew_positions = [i for i in range(len(genome) + 1) if _skew[i] == minimum_skew] <NEW_LINE> return min_skew_positions
Input: a DNA string genome. Output: All integer(s) i minimizing skew_i(genome) among all values of i (from 0 to len(genome))
625941f55f7d997b871750e3
def im_lind(omega, q, beta, mu): <NEW_LINE> <INDENT> eq = 0.5*q**2.0 <NEW_LINE> e_pl = (eq + omega)**2.0/(4*eq) <NEW_LINE> e_mi = (eq - omega)**2.0/(4*eq) <NEW_LINE> return ( -1.0/(4*sc.pi*beta*q) * np.log((1.0+np.exp(-beta*(e_mi-mu)))/ (1.0+np.exp(-beta*(e_pl-mu)))) )
Imaginary part of free-electron Lindhard density-density response function. Parameters ---------- beta : float Inverse temperature. mu : float Chemical potential. q : float (modulus) of wavevector considered. omega : float frequency Returns ------- im_chi : float Imaginary part of thermal Lindard ...
625941f5f548e778e58cdbc5
def MainBarTypeBend( self, TYPE=None ): <NEW_LINE> <INDENT> if TYPE is None: BBIdx = self.BBIdx <NEW_LINE> else: BBIdx = self.TYPES[ TYPE ] <NEW_LINE> BIdx = np.unique( BBIdx[ BBIdx>=0 ] ) <NEW_LINE> BarBendTypeIdx = -np.ones( BIdx.size, dtype=int ) <NEW_LINE> for i, n in enumerate( BIdx ): <NEW_LINE> <INDENT> Areas = ...
Identify the main bar for a specific bar type for each bend None : Any Kind of Bar 0 : Central 1 : Mixed 2 : Lateral
625941f5dc8b845886cb5b7c
def help_destroy(self): <NEW_LINE> <INDENT> print("Destroys an individual instance of a class") <NEW_LINE> print("[Usage]: destroy <className> <objectId>\n")
Help information for the destroy command
625941f5851cf427c661ab4e
def in_stack(self, root): <NEW_LINE> <INDENT> if root == None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> myStack = [] <NEW_LINE> node = root <NEW_LINE> while node or myStack: <NEW_LINE> <INDENT> while node: <NEW_LINE> <INDENT> myStack.append(node) <NEW_LINE> node = node.lch <NEW_LINE> <DEDENT> node = myStack.pop()...
利用堆栈实现树的中序遍历
625941f591af0d3eaac9c062
def __ne__(self, *args): <NEW_LINE> <INDENT> return _itkVariableLengthVectorPython.itkVariableLengthVectorUS___ne__(self, *args)
__ne__(self, itkVariableLengthVectorUS v) -> bool
625941f55166f23b2e1a579e
def __init__(self, client): <NEW_LINE> <INDENT> self.client = client
Creates JobManagement object :param client: an instance of WSManClient
625941f550485f2cf553d3e1
def evalRPN(self, tokens): <NEW_LINE> <INDENT> s = [] <NEW_LINE> for tkn in tokens: <NEW_LINE> <INDENT> if tkn in ["+", "-","/","*"]: <NEW_LINE> <INDENT> b, a = s.pop(), s.pop() <NEW_LINE> if tkn == "+": <NEW_LINE> <INDENT> s.append(a + b) <NEW_LINE> <DEDENT> if tkn == "-": <NEW_LINE> <INDENT> s.append(a - b) <NEW_LINE...
["2","1","+","3","*"] 2,1, + 3,3* ["4","13","5","/","+"] if op, pop 2 ele, compute append back [4, 13,5 ] / [4,2], + [6]
625941f55e10d32532c5f569
def testV1beta1ResourceAttributes(self): <NEW_LINE> <INDENT> pass
Test V1beta1ResourceAttributes
625941f57d847024c06be906
def __init__(self, data): <NEW_LINE> <INDENT> self.slug = data["channel"]["name"] <NEW_LINE> self._data = data <NEW_LINE> self.info = { "provider": "twitch", "slug": self.slug, "name": data["channel"]["display_name"], "preview": data["preview"]["medium"], "game": data["channel"]["game"], "viewers": data["viewers"], "di...
:param dict data: stream data returned from twitch API
625941f5462c4b4f79d1dd14
def setRecoverOnFailedFlag(self, *args): <NEW_LINE> <INDENT> return _ArnlPy.ArLocalizationTask_setRecoverOnFailedFlag(self, *args)
setRecoverOnFailedFlag(self, bool f)
625941f5507cdc57c6307330
def render_to_response(self, context): <NEW_LINE> <INDENT> return get_json_response(self.convert_context_to_json(context))
Returns a JSON response containing 'context' as payload
625941f5e76e3b2f99f3ae45
def testSelect(self): <NEW_LINE> <INDENT> self.assertEquals(self.o.select()[0], 'OK') <NEW_LINE> self.assertEquals(self.o.select('INBOX')[0], 'OK') <NEW_LINE> self.assertEquals(self.o.select('INBOX', 1)[0], 'OK') <NEW_LINE> self.o.create('testflag') <NEW_LINE> self.o.append('testflag', '\Flagged Userflag', "\" 3-Mar-20...
select([mailbox[, readonly]]) Select a mailbox. Returned data is the count of messages in MAILBOX (`EXISTS' response). The default MAILBOX is `'INBOX''. If the READONLY flag is set, modifications to the mailbox are not allowed.
625941f5d99f1b3c44c67bc7
def enrich(self, column): <NEW_LINE> <INDENT> if column not in self.data: <NEW_LINE> <INDENT> return self.data <NEW_LINE> <DEDENT> self.data["filetype"] = 'Other' <NEW_LINE> reg = "\.c$|\.h$|\.cc$|\.cpp$|\.cxx$|\.c\+\+$|\.cp$|\.py$|\.js$|\.java$|\.rs$|\.go$" <NEW_LINE> self.data.loc[self.data[column].str.contains(reg),...
This method adds a new column depending on the extension of the file. :param column: column where the file path is found :type column: string :return: returns the original dataframe with a new column named as 'filetype' that contains information about its extension :rtype: pandas.DataFrame
625941f57d847024c06be907
def iso_utf8_readlines(ir): <NEW_LINE> <INDENT> for line in ir.content.splitlines(): <NEW_LINE> <INDENT> yield detect_and_decode(line)
Iterator which yields decoded unicode strings for each line in the passed iso record.
625941f59f2886367277aecd
def truncate(self, size=None): <NEW_LINE> <INDENT> if self._fd is None: <NEW_LINE> <INDENT> raise io.UnsupportedOperation("Large object is closed.") <NEW_LINE> <DEDENT> if not self._writable: <NEW_LINE> <INDENT> raise io.UnsupportedOperation("Large object hasn't been " "opened in 'write' mode.") <NEW_LINE> <DEDENT> if ...
Trucate a large object. size (int|None): the desired new size. If None, defaults to current position. return (int): the new actual size.
625941f53c8af77a43ae3ded
def user_service_factory(context, request): <NEW_LINE> <INDENT> return UserService(default_authority=request.authority, session=request.db)
Return a UserService instance for the passed context and request.
625941f5d53ae8145f87a8a7
def deactivate(self, hub): <NEW_LINE> <INDENT> return
This method is called when the preset is discarded from the hub.
625941f5d58c6744b42582a2
def arg_parser(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(prog=__product__, description='Simulate population flowing on a discrete network using directed ' 'edges. ') <NEW_LINE> parser.add_argument("-t", "--time", type=int, dest="input_cycles", required=True, help='Simulation time [int]') <NEW_LINE> parser...
This function parses the arguments passed from the command line to the script :returns It returns an object containing all the recognised arguments properly formatted
625941f5cb5e8a47e48b80e4
@ver_log <NEW_LINE> def soma(a, b): <NEW_LINE> <INDENT> return a + b
Soma dois números.
625941f55510c4643540fa19
def _LOOCV(self, X, Y, p, omega2, U, W): <NEW_LINE> <INDENT> Y_ = Y - np.dot(X, [p] * np.shape(X)[1]) <NEW_LINE> dig1 = ((W**2 + omega2)**(-1)) * W**2 <NEW_LINE> XtX_reg_inv2 = np.dot(np.dot(U, np.diag(dig1)), U.T) <NEW_LINE> P = np.diag(np.ones(len(Y_))) - XtX_reg_inv2 <NEW_LINE> LOOCV_EPE = len(Y_)**-1 * np.dot(np.do...
Leave one out error estimator. Parameters ---------- X : array Feature matrix for the training data. Y : list Target data for the training sample. p : float Define the prior function. omega2 : list Regularization strength. U : array Left hand side of sigular matrix for X (not form XtX). W : array ...
625941f5046cf37aa974d386
def full_info(self): <NEW_LINE> <INDENT> retval = "\n============ System Information ============\n" <NEW_LINE> sys_info = {"os_platform": self.platform, "os_machine": self.machine, "os_release": self.release, "py_conda_version": self.conda_version, "py_implementation": self.py_implementation, "py_version": self.py_ver...
Format system info human readable
625941f5de87d2750b8603df
def get_instance(self, payload): <NEW_LINE> <INDENT> return RoomParticipantInstance(self._version, payload, room_sid=self._solution['room_sid'])
Build an instance of RoomParticipantInstance :param dict payload: Payload response from the API :returns: twilio.rest.video.v1.room.room_participant.RoomParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.RoomParticipantInstance
625941f53d592f4c4ed1d6a1