code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_avg(coin: str, currency: str = CURRENCY, exchange: str = 'CCCAGG') -> Optional[Dict]: <NEW_LINE> <INDENT> response = _query_cryptocompare(_URL_AVG.format( coin, currency, _format_parameter(exchange))) <NEW_LINE> if response: <NEW_LINE> <INDENT> return response['RAW'] <NEW_LINE> <DEDENT> return None
Get the average price :param coin: symbolic name of the coin (e.g. BTC) :param currency: short hand description of the currency (e.g. EUR) :param exchange: exchange to use (default: 'CCCAGG') :returns: dict of coin and currency price pairs
625941bb07f4c71912b11341
def resetPosition(self): <NEW_LINE> <INDENT> self.setQuadraturePosition(0, 0)
This function resets the encoder position to 0
625941bb2ae34c7f2600cfeb
def getQValue(self, state, action): <NEW_LINE> <INDENT> qvalue = 0 <NEW_LINE> value = 0 <NEW_LINE> features= self.featExtractor.getFeatures(state,action) <NEW_LINE> for key in self.getWeights(): <NEW_LINE> <INDENT> value = self.getWeights()[key] * features[key] <NEW_LINE> qvalue = value + qvalue <NEW_LINE> <DEDENT> return qvalue
Should return Q(state,action) = w * featureVector where * is the dotProduct operator
625941bb76d4e153a657e9ea
def get_selected_keys(self, selection: int) -> list[str]: <NEW_LINE> <INDENT> return [k for k, b in self._lookup.items() if b & selection]
Return a list of keys for the given selection.
625941bb57b8e32f5248335a
def _collect_testlibs(config, server_match, client_match=[None]): <NEW_LINE> <INDENT> def expand_libs(config): <NEW_LINE> <INDENT> for lib in config: <NEW_LINE> <INDENT> sv = lib.pop('server', None) <NEW_LINE> cl = lib.pop('client', None) <NEW_LINE> yield lib, sv, cl <NEW_LINE> <DEDENT> <DEDENT> def yield_testlibs(base_configs, configs, match): <NEW_LINE> <INDENT> for base, conf in zip(base_configs, configs): <NEW_LINE> <INDENT> if conf: <NEW_LINE> <INDENT> if not match or base['name'] in match: <NEW_LINE> <INDENT> platforms = conf.get('platforms') or base.get('platforms') <NEW_LINE> if not platforms or platform.system() in platforms: <NEW_LINE> <INDENT> yield merge_dict(base, conf) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> libs, svs, cls = zip(*expand_libs(config)) <NEW_LINE> servers = list(yield_testlibs(libs, svs, server_match)) <NEW_LINE> clients = list(yield_testlibs(libs, cls, client_match)) <NEW_LINE> return servers, clients
Collects server/client configurations from library configurations
625941bb8a43f66fc4b53f23
def filter_gdf( gdf, rel_orbit_numbers=None, footprint_overlaps=None, start_date=None, end_date=None): <NEW_LINE> <INDENT> if len(gdf) and start_date is not None: <NEW_LINE> <INDENT> mask = gdf['sensing_end'] >= start_date <NEW_LINE> gdf = gdf[mask] <NEW_LINE> <DEDENT> if len(gdf) and end_date is not None: <NEW_LINE> <INDENT> mask = gdf['sensing_start'] <= end_date <NEW_LINE> gdf = gdf[mask] <NEW_LINE> <DEDENT> if len(gdf) and rel_orbit_numbers is not None: <NEW_LINE> <INDENT> mask = gdf.apply((lambda d: d['relative_orbit_number'] in rel_orbit_numbers), axis=1) <NEW_LINE> gdf = gdf[mask] <NEW_LINE> <DEDENT> if len(gdf) and footprint_overlaps is not None: <NEW_LINE> <INDENT> mask = gdf.intersects(footprint_overlaps) <NEW_LINE> gdf = gdf[mask] <NEW_LINE> <DEDENT> return gdf
Filter S1 metadata GeoDataFrame Parameters ---------- gdf : GeoDataFrame S1 metadata rel_orbit_numbers : list of int relative orbit numbers footprint_overlaps : shapely.geometry.Polygon AOI polygon start_date, end_date : datetime.datetime or datestr date interval
625941bb4d74a7450ccd407c
def test_set_new(self): <NEW_LINE> <INDENT> c = Context() <NEW_LINE> c.set_new('foo', {}) <NEW_LINE> self.assertEqual(c['foo'], {}) <NEW_LINE> c.set_new('foo', 100) <NEW_LINE> self.assertEqual(c['foo'], {})
Test setting values if not present
625941bb004d5f362079a1f0
def __format_param(param): <NEW_LINE> <INDENT> bool_list = ['removemargin', 'flagshadow', 'flagstroke', 'opaqueavatar', 'darktriangles', 'darkheader', 'rankedscore'] <NEW_LINE> xp = ['xpbar', 'xpbarhex'] <NEW_LINE> int_list = ['avatarrounding', 'onlineindicator'] <NEW_LINE> res = '' <NEW_LINE> if xp[0] in param and xp[1] in param and param[xp[0]] is True and param[xp[1]] is True: <NEW_LINE> <INDENT> res += "&{}&{}".format(xp[0], xp[1]) <NEW_LINE> <DEDENT> elif xp[0] in param and xp[1] not in param and xp[0] is True: <NEW_LINE> <INDENT> res += '&{}'.format(xp[0]) <NEW_LINE> <DEDENT> for key, val in param.items(): <NEW_LINE> <INDENT> if key in bool_list and val is True: <NEW_LINE> <INDENT> res += '&{}'.format(key) <NEW_LINE> <DEDENT> if key in int_list and isinstance(val, int): <NEW_LINE> <INDENT> res += '&{}={}'.format(key, str(val)) <NEW_LINE> <DEDENT> <DEDENT> return res
Clean up the advanced parameter from generate() :param param: the advanced parameter from generate() :return: string of formatted parameters
625941bb090684286d50eb9b
def manage_existing_get_size(self, volume, existing_ref): <NEW_LINE> <INDENT> pass
Return size of volume to be managed by manage_existing. When calculating the size, round up to the next GB. :param volume: Cinder volume to manage :param existing_ref: Dictionary with keys 'source-id', 'source-name' with driver-specific values to identify a backend storage object. :raises: ManageExistingInvalidReference If the existing_ref doesn't make sense, or doesn't refer to an existing backend storage object.
625941bb32920d7e50b28086
def updateModeless(self, refreshAxes=False): <NEW_LINE> <INDENT> if refreshAxes: <NEW_LINE> <INDENT> self.dd.aPanel.drawAxisLabels() <NEW_LINE> <DEDENT> r = self.limitLineMovement(self.x1, self.y1, self.x2, self.y2) <NEW_LINE> self.x1 = r[0] <NEW_LINE> self.y1 = r[1] <NEW_LINE> self.x2 = r[2] <NEW_LINE> self.y2 = r[3] <NEW_LINE> self.updateLineProfile() <NEW_LINE> self.resetAbelParameters() <NEW_LINE> self.updateMeans()
Called when Pixel Display Type (actual/normalized) is changed or when new image is loaded.
625941bbd486a94d0b98e004
def push(self): <NEW_LINE> <INDENT> self._stack.append({}) <NEW_LINE> self._cur += 1
Push a new frame onto the stack.
625941bb63d6d428bbe443a9
def get(access_token, media_id, **kwargs): <NEW_LINE> <INDENT> api = 'https://api.weixin.qq.com/cgi-bin/media/get' <NEW_LINE> params = {'access_token': access_token, 'media_id': media_id} <NEW_LINE> params.update(**kwargs) <NEW_LINE> return requests_get(api, params)
获取临时素材
625941bb0c0af96317bb80a3
def test_reload_with_changed_fields(self): <NEW_LINE> <INDENT> class User(Document): <NEW_LINE> <INDENT> name = StringField() <NEW_LINE> number = IntField() <NEW_LINE> <DEDENT> User.drop_collection() <NEW_LINE> user = User(name="Bob", number=1).save() <NEW_LINE> user.name = "John" <NEW_LINE> user.number = 2 <NEW_LINE> self.assertEqual(user._get_changed_fields(), ['name', 'number']) <NEW_LINE> user.reload('number') <NEW_LINE> self.assertEqual(user._get_changed_fields(), ['name']) <NEW_LINE> user.save() <NEW_LINE> user.reload() <NEW_LINE> self.assertEqual(user.name, "John")
Ensures reloading will not affect changed fields
625941bb4e696a04525c9306
def exclusive() -> Callable[[Observable[Observable[_T]]], Observable[_T]]: <NEW_LINE> <INDENT> from ._exclusive import exclusive_ <NEW_LINE> return exclusive_()
Performs a exclusive waiting for the first to finish before subscribing to another observable. Observables that come in between subscriptions will be dropped on the floor. .. marble:: :alt: exclusive -+---+-----+-------| +-7-8-9-| +-4-5-6-| +-1-2-3-| [ exclusive() ] ---1-2-3-----7-8-9-| Returns: An exclusive observable with only the results that happen when subscribed.
625941bb60cbc95b062c6403
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PageDtoDiscoveredVendorDto): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941bb796e427e537b047c
def connect_JSON(config): <NEW_LINE> <INDENT> testnet = config.get('testnet', '0') <NEW_LINE> testnet = (int(testnet) > 0) <NEW_LINE> if not 'rpcport' in config: <NEW_LINE> <INDENT> config['rpcport'] = 51475 if testnet else 50051 <NEW_LINE> <DEDENT> connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport']) <NEW_LINE> try: <NEW_LINE> <INDENT> result = ServiceProxy(connect) <NEW_LINE> if result.getmininginfo()['testnet'] != testnet: <NEW_LINE> <INDENT> sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n") <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> sys.stderr.write("Error connecting to RPC server at "+connect+"\n") <NEW_LINE> sys.exit(1)
Connect to a send JSON-RPC server
625941bb4f6381625f1148f8
def P_S_arrival_T_common(epi_val, evdp): <NEW_LINE> <INDENT> P_WAVE_VELOCITY = 6.10 <NEW_LINE> S_WAVE_VELOCITY = 3.55 <NEW_LINE> hypo_dist = np.sqrt(epi_val**2 + evdp**2) <NEW_LINE> P_arrival_T = hypo_dist/P_WAVE_VELOCITY <NEW_LINE> S_arrival_T = hypo_dist/S_WAVE_VELOCITY <NEW_LINE> return P_arrival_T, S_arrival_T
p and s travel time for common model
625941bb55399d3f0558856d
def get_url(self, url): <NEW_LINE> <INDENT> return self.session.get(url, timeout=15).json()
Flat wrapper for fetching URL directly
625941bb10dbd63aa1bd2a68
def read_dict(self, where): <NEW_LINE> <INDENT> out = {} <NEW_LINE> nd = self.get_group(where) <NEW_LINE> for prpnm, prp in nd.attrs.iteritems(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> out[prpnm] = pkl.loads(prp) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> out[prpnm] = prp <NEW_LINE> <DEDENT> <DEDENT> return out
Read a dictionary object at `where`.
625941bb6fb2d068a760ef54
def update_options(self, *args): <NEW_LINE> <INDENT> args = args <NEW_LINE> self.update_path()
Update path
625941bb4c3428357757c1e4
def test_new_user_email_normalized(self): <NEW_LINE> <INDENT> email = "mmoraru@gGMAIL.COM" <NEW_LINE> user = get_user_model().objects.create_user(email, 'test123') <NEW_LINE> self.assertEqual(user.email, email.lower())
Test the email for the new uesr is normalized
625941bb45492302aab5e17a
def update_database(self, images): <NEW_LINE> <INDENT> conn = sqlite3.connect(self.db_path) <NEW_LINE> cur = conn.cursor() <NEW_LINE> images_to_insert = [] <NEW_LINE> for image in images: <NEW_LINE> <INDENT> count_selector = "SELECT count FROM images WHERE url = '%s'" % image['url'] <NEW_LINE> current_count = cur.execute(count_selector).fetchone() <NEW_LINE> if current_count: <NEW_LINE> <INDENT> current_count = current_count[0] <NEW_LINE> new_count = current_count + image['count'] <NEW_LINE> if current_count > 1: <NEW_LINE> <INDENT> update_statement = "UPDATE images " "SET count = '%i' " "WHERE url = '%s'" % (new_count, image['url']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> update_statement = "UPDATE images " "SET count = '%i', " "share_text = 'shares'" "WHERE url = '%s'" % (new_count, image['url']) <NEW_LINE> <DEDENT> cur.execute(update_statement) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> images_to_insert.append(image) <NEW_LINE> <DEDENT> <DEDENT> if images_to_insert: <NEW_LINE> <INDENT> insert_list = ["('%s','%s','%s')" % (i['url'], i['count'], i['share_text']) for i in images_to_insert] <NEW_LINE> insert_statement = "INSERT INTO images VALUES %s" % ','.join(insert_list) <NEW_LINE> cur.execute(insert_statement) <NEW_LINE> <DEDENT> conn.commit()
Take a list of images and update the database to reflect them :param db_path: Path to database to update :param images: List of image distionaries
625941bb1b99ca400220a96b
def send_to_model_server(path_to_model, url): <NEW_LINE> <INDENT> shutil.make_archive("/output/model", 'zip', path_to_model) <NEW_LINE> r = requests.post(url, data=open("/output/model.zip"), headers={'content-type': 'application/zip'} )
Send an existing model to an external server. Parameters: ---------- path_to_model: str Path from which the model will be loaded url: str Url to which the model will be send a zip file
625941bb7cff6e4e8111783f
def get_test_descriptors(): <NEW_LINE> <INDENT> resp = requests.get(env.test_descriptors_api, timeout=env.timeout, headers=env.header) <NEW_LINE> env.set_return_header(resp.headers) <NEW_LINE> if resp.status_code != 200: <NEW_LINE> <INDENT> LOG.debug("Request for test descriptors returned with " + (str(resp.status_code))) <NEW_LINE> return False, [] <NEW_LINE> <DEDENT> descriptors = json.loads(resp.text) <NEW_LINE> descriptors_res = [] <NEW_LINE> for descriptor in descriptors: <NEW_LINE> <INDENT> platforms = "" <NEW_LINE> for platform in descriptor['testd']['service_platforms']: <NEW_LINE> <INDENT> print (platform) <NEW_LINE> if platforms == "": <NEW_LINE> <INDENT> platforms = platform <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> platforms = platforms + "," + platform <NEW_LINE> <DEDENT> <DEDENT> dic = {'uuid': descriptor['uuid'], 'name': descriptor['testd']['name'], 'vendor': descriptor['testd']['vendor'], 'version': descriptor['testd']['version'], 'platforms': platforms, 'status': descriptor['status'], 'updated_at': descriptor['updated_at']} <NEW_LINE> LOG.debug(str(dic)) <NEW_LINE> descriptors_res.append(dic) <NEW_LINE> <DEDENT> return True, descriptors_res
Returns info on all available test descriptors. :returns: A tuple. [0] is a bool with the result. [1] is a list of dictionaries. Each dictionary contains a test descriptor.
625941bbbaa26c4b54cb0fdd
def __init__(self, lifespan=None): <NEW_LINE> <INDENT> BaseWorld.__init__(self, lifespan) <NEW_LINE> self.name = 'grid_1D_chase' <NEW_LINE> print("Entering", self.name) <NEW_LINE> self.size = 7 <NEW_LINE> self.n_sensors = self.size + 2 * (self.size - 1) <NEW_LINE> self.n_actions = 2 * (self.size - 1) <NEW_LINE> self.reward = 0. <NEW_LINE> self.action = np.zeros(self.n_actions) <NEW_LINE> self.jump_fraction = .1 <NEW_LINE> self.energy = 0. <NEW_LINE> self.energy_cost = 1e-2 <NEW_LINE> self.sensors = np.zeros(self.n_sensors) <NEW_LINE> self.position = 2 <NEW_LINE> self.target_position = 1 <NEW_LINE> self.visualize_interval = 1e6
Initialize the world. Parameters ---------- lifespan : int The number of time steps to continue the world.
625941bb6fece00bbac2d5f6
def generate_timestamp(): <NEW_LINE> <INDENT> now = datetime.datetime.utcnow() <NEW_LINE> ts = now.strftime('%Y-%m-%dT%H:%M:%SZ') <NEW_LINE> return ts
Generates timestamp of the format 2014-08-18T12:00:00Z.
625941bb26238365f5f0ed24
def calc_last_modified(request, *args, **kwargs): <NEW_LINE> <INDENT> assert "cache_name" in kwargs, "Must specify cache_name as a keyword arg." <NEW_LINE> try: <NEW_LINE> <INDENT> cache = get_cache(kwargs["cache_name"]) <NEW_LINE> assert isinstance(cache, FileBasedCache) or isinstance(cache, LocMemCache), "requires file-based or mem-based cache." <NEW_LINE> <DEDENT> except InvalidCacheBackendError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> key = django_get_cache_key(request, cache=cache) <NEW_LINE> if key is None or not cache.has_key(key): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(cache, FileBasedCache): <NEW_LINE> <INDENT> fname = cache._key_to_file(cache.make_key(key)) <NEW_LINE> if not os.path.exists(fname): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> last_modified = datetime.datetime.fromtimestamp(os.path.getmtime(fname)) <NEW_LINE> <DEDENT> elif isinstance(cache, LocMemCache): <NEW_LINE> <INDENT> creation_time = cache._expire_info[cache.make_key(key)] - settings.CACHE_TIME <NEW_LINE> last_modified = datetime.datetime.fromtimestamp(creation_time) <NEW_LINE> <DEDENT> return last_modified
Returns the file's modified time as the last-modified date
625941bb293b9510aa2c3152
def build_params(self, codestring): <NEW_LINE> <INDENT> params = super(AztecCode._Renderer, self).build_params(codestring) <NEW_LINE> cbbox = self._code_bbox(codestring) <NEW_LINE> params['bbox'] = '%d %d %d %d' %(self._boundingbox(cbbox, cbbox)) <NEW_LINE> return params
>>> AztecCode._Renderer({}).build_params('abcd') {'yscale': 1.0, 'codestring': '<61626364>', 'bbox': '0 0 30 30', 'codetype': {}, 'xscale': 1.0, 'options': '<>'}
625941bbe8904600ed9f1de3
def print_sorted(self): <NEW_LINE> <INDENT> print(sorted(self))
Prints the list in ascending order
625941bbd10714528d5ffb9a
def __init__(self, parent: Optional['SymbolNode'], character: int): <NEW_LINE> <INDENT> self.__children: CharReferenceMap = None <NEW_LINE> self.__token_type: TokenType = TokenType.Unknown <NEW_LINE> self.__valid: bool = None <NEW_LINE> self.__ancestry: str = None <NEW_LINE> self.__parent: SymbolNode = parent <NEW_LINE> self.__character: int = character
Constructs a SymbolNode with the given parent, representing the given character. :param parent: This node's parent :param character: This node's associated character.
625941bb07d97122c4178745
def get_damage(unit): <NEW_LINE> <INDENT> return unit[1]
a = make_unit( 'zerg', 12 ) get_catchphrase(a) 'zerg' get_damage(a) 12
625941bbbde94217f3682cb5
def get_update_list(fp_update): <NEW_LINE> <INDENT> update_list = [] <NEW_LINE> for item in fp_update: <NEW_LINE> <INDENT> temp = item.strip().split() <NEW_LINE> temp_item = [temp[0], temp[5], temp[-1]] <NEW_LINE> update_list.append(temp_item) <NEW_LINE> <DEDENT> return update_list
Divide the fp update based on sync-client
625941bb187af65679ca4fd7
def parse_enemies(current_chunk): <NEW_LINE> <INDENT> global enemies <NEW_LINE> global frenemy <NEW_LINE> current_chunk = strip_ansi(current_chunk) <NEW_LINE> m = re_enemies.search(current_chunk) <NEW_LINE> enemies = m.groups()[0].split("\r\n") <NEW_LINE> c.echo(f"enemies: {' '.join(enemies)}") <NEW_LINE> frenemy.notify("enemies", enemies)
You have the following enemies: Farrah Mezghar You have currently used 2 enemy slots of your 20 maximum.
625941bb15fb5d323cde09c4
def test_get_node_health_with_invalid_id(self): <NEW_LINE> <INDENT> request_id = "xxxxxxxxxxx" <NEW_LINE> self.assertRaises( DiscoveryError, Discovery.get_node_health, request_id)
Check for node health backend url with invalid id.
625941bb26068e7796caeb93
def join(): <NEW_LINE> <INDENT> t = threading.Thread(name = 'process', target= worker2, args=(3,)) <NEW_LINE> t.start() <NEW_LINE> t.join() <NEW_LINE> t2 = threading.Thread(name = 'process2', target= worker2, args=(3,)) <NEW_LINE> t2.start()
阻塞线程
625941bb30c21e258bdfa355
def brand_info_counts(self): <NEW_LINE> <INDENT> return { 'no_brand': self.active_issues().filter(no_brand=True).count(), 'unknown': self.active_issues().filter(no_brand=False, brand__isnull=True).count(), }
Simple method for the UI to use, as the UI can't pass parameters.
625941bb91af0d3eaac9b8cf
def classFactory(iface): <NEW_LINE> <INDENT> from .ImportPhotos import ImportPhotos <NEW_LINE> return ImportPhotos(iface)
Load ImportPhotos class from file ImportPhotos. :param iface: A QGIS interface instance. :type iface: QgsInterface
625941bb63b5f9789fde6fa0
def eta_func(r_list, param_dict, func_type='well-behaved', scaled=False): <NEW_LINE> <INDENT> if func_type == 'power law': <NEW_LINE> <INDENT> rScale, rc, etaScale, betaDelta = get_eta_powerlaw_params(param_dict) <NEW_LINE> r = np.array(r_list) <NEW_LINE> w = (r-rc)/rScale <NEW_LINE> return etaScale*w**(betaDelta) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rScale, rc, etaScale, lambdaH, B, F = get_eta_params(param_dict) <NEW_LINE> r = np.array(r_list) <NEW_LINE> w = (r-rc)/rScale <NEW_LINE> if func_type == 'truncated': <NEW_LINE> <INDENT> eta = (etaScale*np.exp(-lambdaH/w) * (B+(1/w)) ** (-F+B*lambdaH)) <NEW_LINE> if scaled: <NEW_LINE> <INDENT> eta = np.exp(-B**2*w*lambdaH)*eta <NEW_LINE> <DEDENT> return eta <NEW_LINE> <DEDENT> elif func_type == 'well-behaved': <NEW_LINE> <INDENT> eta = (etaScale*np.exp(-B*F*w-lambdaH/w) * w ** (-B*lambdaH+F)) <NEW_LINE> if scaled: <NEW_LINE> <INDENT> eta = np.exp(B**2*w*lambdaH)*eta <NEW_LINE> <DEDENT> return eta <NEW_LINE> <DEDENT> elif func_type == 'pitchfork': <NEW_LINE> <INDENT> exponential_piece = (np.exp(-(F/w)-(lambdaH/(2*w**2)) - np.sqrt(B) * F * np.arctan(np.sqrt(B)*w))) <NEW_LINE> powerlaw_piece = (w**(-B*lambdaH) * (1+B*w**2) ** (B*lambdaH/2)) <NEW_LINE> return etaScale*exponential_piece*powerlaw_piece <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("functional type not recognized,", " using 'well-behaved' form") <NEW_LINE> eta = (etaScale*np.exp(-B*F*w-lambdaH/w) * w ** (-B*lambdaH+F)) <NEW_LINE> return eta
Nonlinear scaling variable function determined from the flow equations of the disorder, w, and field, h Input: r_list - list of r values param_dict - dictionary of parameters on which eta(r) is dependent func_type - which form of eta(r) to use. Options: 'power law' - eta(r) derived with dw/dl = (1/nu) w 'truncated' - eta(r) derived with dw/dl = w^2 + B w^3 'well-behaved' - eta(r) derived with dw/dl = w^2 / (1 + B w) 'pitchfork' - eta(r) derived with dw/dl = w^3 + B w^5 scaled - flag for whether to use the eta derived with the 'truncated' dw/dl scaled for comparison with the 'well-behaved' form at small r Output: eta(r) values for the given inputs
625941bb7cff6e4e81117840
def main(): <NEW_LINE> <INDENT> T = int(input()) <NEW_LINE> for case in range(T): <NEW_LINE> <INDENT> num = int(input()) <NEW_LINE> solve(num, 1, int(math.sqrt(num * 2)))
이게 최대 n 값 찾기 x = n * (2 * a1 + n - 1) / 2 x = n * (2 * a1 + -(n - 1)) / 2
625941bb2ae34c7f2600cfec
def test_edit_full(self) -> None: <NEW_LINE> <INDENT> self.submit_form('edit_address', 'input_id_submit', send_form_keys={ 'id_address_line_1': '2986 Heron Way', 'id_address_line_2': 'Attn. Anna Freytag', 'id_city': 'Portland', 'id_zip': '97205', 'id_state': 'Oregon' }, select_dropdowns={ 'id_country': ('US',) }) <NEW_LINE> self.assert_url_equal('edit_address', 'Check that we stayed on the right page') <NEW_LINE> address = self.user.alumni.address <NEW_LINE> self.assertEqual(address.address_line_1, '2986 Heron Way') <NEW_LINE> self.assertEqual(address.address_line_2, 'Attn. Anna Freytag') <NEW_LINE> self.assertEqual(address.city, 'Portland') <NEW_LINE> self.assertEqual(address.zip, '97205') <NEW_LINE> self.assertEqual(address.state, 'Oregon') <NEW_LINE> self.assertEqual(address.country.name, 'United States of America')
Tests that adding a full address works
625941bb85dfad0860c3ad13
def receive_weather(self, weather_id): <NEW_LINE> <INDENT> path = self._compose_path("integrations/weather/{0}".format(weather_id)) <NEW_LINE> return self._get(path)
Get data from the Adafruit IO Weather Forecast Service NOTE: This service is avaliable to Adafruit IO Plus subscribers only. :param int weather_id: ID for retrieving a specified weather record.
625941bb4c3428357757c1e5
def resize(self, size): <NEW_LINE> <INDENT> return type(self)(self._data.name, size=size, index=self._index)
Returns a new copy of this font in a different size
625941bb2c8b7c6e89b3567d
def _stepwise_interp(xi, yi, x): <NEW_LINE> <INDENT> end = np.atleast_1d(xi.searchsorted(x)) <NEW_LINE> end[end == 0] += 1 <NEW_LINE> start = end - 1 <NEW_LINE> end[end == len(xi)] -= 1 <NEW_LINE> try: <NEW_LINE> <INDENT> xi_smallest_diff = 20 * np.finfo(xi.dtype).resolution <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> xi_smallest_diff = 0 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> x_smallest_diff = 20 * np.finfo(x.dtype).resolution <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> x_smallest_diff = 0 <NEW_LINE> <DEDENT> smallest_diff = max(x_smallest_diff, xi_smallest_diff) <NEW_LINE> equal_or_just_below = xi[end] - x < smallest_diff <NEW_LINE> start[equal_or_just_below] = end[equal_or_just_below] <NEW_LINE> start = np.reshape(start, np.shape(x)) <NEW_LINE> return yi[start]
Step-wise interpolate (or extrapolate) (xi, yi) values to x positions. Given a set of N ``(x, y)`` points, provided in the *xi* and *yi* arrays, this will calculate ``y``-coordinate values for a set of M ``x``-coordinates provided in the *x* array, using step-wise (zeroth-order) interpolation and extrapolation. The input *x* coordinates are compared to the fixed *xi* values, and the largest *xi* value smaller than or approximately equal to each *x* value is selected. The corresponding *yi* value is then returned. For *x* values below the entire set of *xi* values, the smallest *xi* value is selected. The steps of the interpolation therefore start at each *xi* value and extends to the right (above it) until the next bigger *xi*, except for the first step, which extends to the left (below it) as well, and the last step, which extends until positive infinity. Parameters ---------- xi : array, shape (N,) Array of fixed x-coordinates, sorted in ascending order and with no duplicate values yi : array, shape (N,) Corresponding array of fixed y-coordinates x : float or array, shape (M,) Array of x-coordinates at which to do interpolation of y-values Returns ------- y : float or array, shape (M,) Array of interpolated y-values Notes ----- The equality check of *x* values is approximate on purpose, to handle some degree of numerical imprecision in floating-point values. This is important for step-wise interpolation, as there are potentially large discontinuities in *y* at the *xi* values, which makes it sensitive to small mismatches in *x*. For continuous interpolation (linear and up) this is unnecessary.
625941bb45492302aab5e17b
def stop_vm(self, vmname): <NEW_LINE> <INDENT> sms = ServiceManagementService(self.__subscription, self.__certSelection) <NEW_LINE> result = sms.shutdown_role(self.getVmService(vmname), self.getVmService(vmname), vmname) <NEW_LINE> if result: <NEW_LINE> <INDENT> return self.wait_operation(result.request_id) <NEW_LINE> <DEDENT> return False
starts vm role
625941bb9f2886367277a74b
def ssr(self, x, y): <NEW_LINE> <INDENT> J = np.ones((y.shape[0], y.shape[0])) <NEW_LINE> G = np.linalg.inv(np.dot(x.T, x)) <NEW_LINE> H = np.dot(x, np.dot(G, x.T)) <NEW_LINE> Qr = H - (1/y.shape[0])*J <NEW_LINE> SSR = np.dot(y.T, np.dot(Qr, y)) <NEW_LINE> return SSR
Compute the regression sum of squares. Parameters: - - - - - x: feature matrix y: response matrix
625941bbde87d2750b85fc49
def trainer(self, classes=None): <NEW_LINE> <INDENT> self.logger.info('Running trainer method') <NEW_LINE> if classes is None: <NEW_LINE> <INDENT> classes = ['ok'] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.cleaned = self.data.copy() <NEW_LINE> self.cleaned = self.data[self.selection + self.codes] <NEW_LINE> self.cleaned = self.cleaned.dropna(how='any') <NEW_LINE> for col in self.categories: <NEW_LINE> <INDENT> encoder = LabelEncoder() <NEW_LINE> encoder.fit(self.cleaned[col]) <NEW_LINE> self.cleaned.loc[:, col] = encoder.transform(self.cleaned.loc[:, col]) <NEW_LINE> <DEDENT> self.target_encoder.fit(self.cleaned['target']) <NEW_LINE> self.cleaned['target'] = self.target_encoder.transform(self.cleaned['target']) <NEW_LINE> bin_true = self.target_encoder.transform(classes) <NEW_LINE> targets_numeric = [1 if x in bin_true else 0 for x in self.cleaned['target']] <NEW_LINE> self.cleaned['target'] = targets_numeric <NEW_LINE> self.cleaned.drop('respondent_id', axis=1, inplace=True) <NEW_LINE> assert self.cleaned.shape[0] > 0 <NEW_LINE> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> self.logger.error('self.cleaned did not return any rows') <NEW_LINE> raise <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.logger.error('Error while running trainer method') <NEW_LINE> raise
Prepare the data for training
625941bb94891a1f4081b963
def optimize(self, network, data_X, data_Y): <NEW_LINE> <INDENT> optimize_start_time = time.time() <NEW_LINE> indexes = np.arange(len(data_X)) <NEW_LINE> if self.verbosity > 0: <NEW_LINE> <INDENT> c = network.cost(data_X, data_Y) <NEW_LINE> print("Cost before epochs: {}".format(c)) <NEW_LINE> <DEDENT> for epoch in range(self.n_epochs): <NEW_LINE> <INDENT> epoch_start_time = time.time() <NEW_LINE> np.random.shuffle(indexes) <NEW_LINE> shuffle_X = np.asarray([data_X[i] for i in indexes]) <NEW_LINE> shuffle_Y = np.asarray([data_Y[i] for i in indexes]) <NEW_LINE> mdiv = len(data_X) // self.mini_batch_size <NEW_LINE> for m in range(mdiv): <NEW_LINE> <INDENT> mb_start_time = time.time() <NEW_LINE> mini_X = shuffle_X[m*self.mini_batch_size:(m+1)*self.mini_batch_size] <NEW_LINE> mini_Y = shuffle_Y[m*self.mini_batch_size:(m+1)*self.mini_batch_size] <NEW_LINE> if self.n_threads > 1: <NEW_LINE> <INDENT> self.cost_gradient_parallel(network, mini_X, mini_Y) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.dc_db, self.dc_dq, self.dc_dr, self.dc_dn, self.dc_dm = network.cost_gradient(mini_X, mini_Y) <NEW_LINE> <DEDENT> self.weight_update_func(network) <NEW_LINE> if self.alpha_decay is not None: <NEW_LINE> <INDENT> self.alpha *= 1.0 - self.alpha_decay <NEW_LINE> <DEDENT> if self.verbosity > 1 and m % self.cost_freq == 0: <NEW_LINE> <INDENT> c = network.cost(data_X, data_Y) <NEW_LINE> print("Cost at epoch {} mini-batch {}: {:g}".format(epoch, m, c)) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> elif self.verbosity == 1 and m % self.cost_freq == 0: <NEW_LINE> <INDENT> c = network.cost(mini_X, mini_Y) <NEW_LINE> mt = time.time() - mb_start_time <NEW_LINE> emt = mt * (mdiv-1 - m) <NEW_LINE> print("Estimated cost at epoch {:2d} mini-batch {:4d}: {:.6f} mini-batch time: {:.2f} estimated epoch time remaining: {:.2f}".format( epoch, m, c, mt, emt)) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> <DEDENT> if self.verbosity > 0: <NEW_LINE> <INDENT> c = network.cost(data_X, data_Y) <NEW_LINE> print("Cost after epoch {}: {:g}".format(epoch, c)) <NEW_LINE> print("Epoch time: {:g} s".format(time.time() - epoch_start_time)) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> <DEDENT> if self.verbosity > 0: <NEW_LINE> <INDENT> c = network.cost(data_X, data_Y) <NEW_LINE> print("\n\nCost after optimize run: {:g}".format(c)) <NEW_LINE> print("Optimize run time: {:g} s".format(time.time() - optimize_start_time)) <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> return network
:return: optimized network
625941bbd164cc6175782c08
def talk_m10_02_x21(): <NEW_LINE> <INDENT> ClearNpcMenuResults() <NEW_LINE> if GetEventFlag(102181) != 0: <NEW_LINE> <INDENT> assert talk_m10_02_x23() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert talk_m10_02_x22() <NEW_LINE> <DEDENT> """State 4: End state""" <NEW_LINE> return 0
Retired fire prevention woman 1: Conversation
625941bb8c3a873295158279
def isLoading(self): <NEW_LINE> <INDENT> return self.__isLoading
Public method to get the loading state. @return flag indicating the loading state (boolean)
625941bbcb5e8a47e48b7969
def put_inst(self, byte): <NEW_LINE> <INDENT> self._inst(byte)
Write an instruction byte.
625941bb26068e7796caeb94
def order_limit_sell(self, disable_validation=False, timeInForce=TIME_IN_FORCE_GTC, **params): <NEW_LINE> <INDENT> params.update({ 'side': SIDE_SELL }) <NEW_LINE> return self.order_limit(disable_validation=disable_validation, timeInForce=timeInForce, **params)
Send in a new limit sell order :param symbol: required :type symbol: str :param quantity: required :type quantity: decimal :param price: required :type price: decimal :param timeInForce: default Good till cancelled :type timeInForce: enum :param newClientOrderId: A unique id for the order. Automatically generated if not sent. :type newClientOrderId: str :param stopPrice: Used with stop orders :type stopPrice: decimal :param icebergQty: Used with iceberg orders :type icebergQty: decimal :param disable_validation: disable client side order validation, default False :type disable_validation: bool :returns: API response .. code-block:: python { "symbol":"LTCBTC", "orderId": 1, "clientOrderId": "myOrder1" # Will be newClientOrderId "transactTime": 1499827319559 } :raises: BinanceResponseException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException
625941bb0a366e3fb873e6d2
def find_or_create(community, teamJSON): <NEW_LINE> <INDENT> if 'name' in teamJSON: <NEW_LINE> <INDENT> return TeamService.find_by_name(community, teamJSON['name']) <NEW_LINE> <DEDENT> elif 'goalkeeper' in teamJSON and 'forward' in teamJSON: <NEW_LINE> <INDENT> gk_id = teamJSON['goalkeeper'] <NEW_LINE> fw_id = teamJSON['forward'] <NEW_LINE> return TeamService.find_by_player_ids(community, gk_id, fw_id) <NEW_LINE> <DEDENT> return None
Find team using provided team json: by name or by players.
625941bbfbf16365ca6f6078
def testProcess(self): <NEW_LINE> <INDENT> use_context = True <NEW_LINE> conn0, child_conn0 = mp.Pipe() <NEW_LINE> conn1, child_conn1 = mp.Pipe() <NEW_LINE> if use_context: <NEW_LINE> <INDENT> context = mp.get_context("fork") <NEW_LINE> proc0 = context.Process(target=worker, args=(child_conn0,)) <NEW_LINE> proc1 = context.Process(target=worker, args=(child_conn1,)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> proc0 = mp.Process(target=worker, args=(child_conn0,)) <NEW_LINE> proc1 = mp.Process(target=worker, args=(child_conn1,)) <NEW_LINE> <DEDENT> proc0.start() <NEW_LINE> proc1.start() <NEW_LINE> conn0.recv() <NEW_LINE> conn1.recv() <NEW_LINE> conn0.send(COMMAND_ACTION) <NEW_LINE> conn1.send(COMMAND_ACTION) <NEW_LINE> obs0 = conn0.recv() <NEW_LINE> obs1 = conn1.recv() <NEW_LINE> screen0 = obs0["screen"] <NEW_LINE> self.assertEqual( (84,84,3), screen0.shape ) <NEW_LINE> screen1 = obs1["screen"] <NEW_LINE> self.assertEqual( (84,84,3), screen1.shape ) <NEW_LINE> conn0.send(COMMAND_TERMINATE) <NEW_LINE> conn1.send(COMMAND_TERMINATE)
env_dummy = rodentia.Environment(width=84, height=84, bg_color=[0.0, 0.0, 0.0]) env_dummy.close() env_dummy = None
625941bba934411ee3751555
def _expr(self): <NEW_LINE> <INDENT> expr_value = self._or() <NEW_LINE> while self._accept('XOR'): <NEW_LINE> <INDENT> return self.graph.addOperator('XOR', leftNode=expr_value, rightNode=self._expr(), side=self.side) <NEW_LINE> <DEDENT> return expr_value
<expr> ::= <or> {'^' <expr>}
625941bbab23a570cc25003a
def t350190_x14(): <NEW_LINE> <INDENT> Quit() <NEW_LINE> return 0
State 0
625941bbb57a9660fec3373b
def _createProtoQuery(self): <NEW_LINE> <INDENT> protoObj = LeveldbServerMessages.ActualData() <NEW_LINE> protoObj.timestamp = arrow.now().timestamp <NEW_LINE> protoObj.type = LeveldbServerMessages.ActualData.QUERY <NEW_LINE> return protoObj
helper method that creates the LeveldbServerMessages.ActualData object for us, sets the timestamp and the type, and then returns it for us this is for a ServerQuery @return a ActualData protobuf object
625941bb92d797404e304044
def test_check_failure(self): <NEW_LINE> <INDENT> results = Run(["grep", "--asdfghjk"])() <NEW_LINE> results = Check(AssertExitFailure())(results) <NEW_LINE> self.assertEqual(results.returncode, 0)
Check should set results to successful by asserting exit failure.
625941bb4f88993c3716bf28
def astimezone(self, tz=LOCAL): <NEW_LINE> <INDENT> if tz is None: <NEW_LINE> <INDENT> tz = LOCAL <NEW_LINE> <DEDENT> tz = parser.get_timezone(tz) <NEW_LINE> return self.datetime.astimezone(tz)
Return datetime shifted to timezone `tz`. Note: This returns a native datetime object. Args: tz (None|str|tzinfo, optional): Timezone to shift to. Defaults to `"local"` which uses the local timezone. Returns: :class:`datetime`
625941bb63f4b57ef0000fdb
def generate_template(tmpl, dest, config): <NEW_LINE> <INDENT> with open(tmpl) as tmpl: <NEW_LINE> <INDENT> with open(dest, 'w') as dest: <NEW_LINE> <INDENT> dest.write(render_template(tmpl.read(), config))
generate file
625941bb9c8ee82313fbb630
def seg_ctc_ent_cost(out, targets, sizes, target_sizes, uni_rate=1.5): <NEW_LINE> <INDENT> Time = out.size(0) <NEW_LINE> loss_func = seg_ctc_ent_loss_log <NEW_LINE> offset = 0 <NEW_LINE> batch = target_sizes.size(0) <NEW_LINE> uniform_mask = Variable(T.zeros(Time, batch).type(byteX)) <NEW_LINE> for index, (target_size, size) in enumerate(zip(target_sizes, sizes)): <NEW_LINE> <INDENT> offset += target_size.item() <NEW_LINE> uni_length = int(uni_rate * (size.data.item() / (target_size.data.item() + 1))) <NEW_LINE> uniform_mask[-uni_length:, index] = 1 <NEW_LINE> <DEDENT> if not cuda: <NEW_LINE> <INDENT> H, costs = loss_func(out.cpu(), sizes.data.type(longX), targets, target_sizes.data.type(longX), uniform_mask) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> H, costs = loss_func(out, sizes.data.type(longX), targets, target_sizes.data.type(longX), uniform_mask) <NEW_LINE> <DEDENT> return H, costs
out = out.cpu() targets = targets.cpu() sizes = sizes.cpu() target_sizes = target_sizes.cpu()
625941bbcdde0d52a9e52eea
def _find_existing_inputs(in_bam): <NEW_LINE> <INDENT> sr_file = "%s-sr.bam" % os.path.splitext(in_bam)[0] <NEW_LINE> disc_file = "%s-disc.bam" % os.path.splitext(in_bam)[0] <NEW_LINE> if utils.file_exists(sr_file) and utils.file_exists(disc_file): <NEW_LINE> <INDENT> return in_bam, sr_file, disc_file <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None, None, None
Check for pre-calculated split reads and discordants done as part of alignment streaming.
625941bbff9c53063f47c0b0
def repeat_last_operation(calc): <NEW_LINE> <INDENT> if calc['history']: <NEW_LINE> <INDENT> return calc['history'][-1][-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Return passed calculator's last operation result.
625941bb30bbd722463cbc7e
def filter_by_regex(self, kind=None, value=None, exclude=False): <NEW_LINE> <INDENT> self.loggit.debug('Filtering indices by regex') <NEW_LINE> if kind not in [ 'regex', 'prefix', 'suffix', 'timestring' ]: <NEW_LINE> <INDENT> raise ValueError('{0}: Invalid value for kind'.format(kind)) <NEW_LINE> <DEDENT> if value == 0: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif not value: <NEW_LINE> <INDENT> raise ValueError( '{0}: Invalid value for "value". ' 'Cannot be "None" type, empty, or False' ) <NEW_LINE> <DEDENT> if kind == 'timestring': <NEW_LINE> <INDENT> regex = settings.regex_map()[kind].format(utils.get_date_regex(value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> regex = settings.regex_map()[kind].format(value) <NEW_LINE> <DEDENT> self.empty_list_check() <NEW_LINE> pattern = re.compile(regex) <NEW_LINE> for index in self.working_list(): <NEW_LINE> <INDENT> self.loggit.debug('Filter by regex: Index: {0}'.format(index)) <NEW_LINE> match = pattern.search(index) <NEW_LINE> if match: <NEW_LINE> <INDENT> self.__excludify(True, exclude, index) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__excludify(False, exclude, index)
Match indices by regular expression (pattern). :arg kind: Can be one of: ``suffix``, ``prefix``, ``regex``, or ``timestring``. This option defines what kind of filter you will be building. :arg value: Depends on `kind`. It is the strftime string if `kind` is ``timestring``. It's used to build the regular expression for other kinds. :arg exclude: If `exclude` is `True`, this filter will remove matching indices from `indices`. If `exclude` is `False`, then only matching indices will be kept in `indices`. Default is `False`
625941bb50812a4eaa59c1df
def ll_copyfile(self, src, dst, *, follow_symlinks=True): <NEW_LINE> <INDENT> if shutil._samefile(src, dst): <NEW_LINE> <INDENT> raise shutil.SameFileError("{!r} and {!r} are the same file".format(src, dst)) <NEW_LINE> <DEDENT> for fn in [src, dst]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> st = os.stat(fn) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if shutil.stat.S_ISFIFO(st.st_mode): <NEW_LINE> <INDENT> raise shutil.SpecialFileError("`%s` is a named pipe" % fn) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not follow_symlinks and os.path.islink(src): <NEW_LINE> <INDENT> os.symlink(os.readlink(src), dst) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> size = os.stat(src).st_size <NEW_LINE> with open(src, 'rb') as fsrc: <NEW_LINE> <INDENT> with open(dst, 'wb') as fdst: <NEW_LINE> <INDENT> self.copyfileobj(fsrc, fdst, total=size) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return dst
Copy data from src to dst. If follow_symlinks is not set and src is a symbolic link, a new symlink will be created instead of copying the file it points to.
625941bb3346ee7daa2b2c25
def generateRandomKey(): <NEW_LINE> <INDENT> key = list(LETTERS) <NEW_LINE> random.shuffle(key) <NEW_LINE> return ''.join(key)
Generate and return a random encryption key.
625941bbd18da76e2353238d
def test_approx_freq_pattern_finder(self): <NEW_LINE> <INDENT> for DNA, pat_len, dist, freq in self.known_approx_freq: <NEW_LINE> <INDENT> result = freq_finder.find_most_approx_freq(DNA, pat_len, dist) <NEW_LINE> self.assertCountEqual(freq, result)
Most-frequent approximate patterns should be found correctly
625941bbe1aae11d1e749b6f
def predict(image_path, model, topk=5): <NEW_LINE> <INDENT> model.eval() <NEW_LINE> img = process_image(image_path) <NEW_LINE> img = torch.from_numpy(np.array(img)).float() <NEW_LINE> img = img.to(device) <NEW_LINE> img.unsqueeze_(0) <NEW_LINE> output = model.forward(img) <NEW_LINE> probs, classes = torch.exp(output).topk(topk) <NEW_LINE> probs = probs.cpu() <NEW_LINE> probs = probs.detach().numpy()[0] <NEW_LINE> classes = classes.cpu() <NEW_LINE> classes = classes.numpy()[0] <NEW_LINE> return probs, classes
Predict the class (or classes) of an image using a trained deep learning model.
625941bb6fb2d068a760ef55
def _create_hash(self): <NEW_LINE> <INDENT> sha = hashlib.sha256() <NEW_LINE> for index in self.collect_package_indices(): <NEW_LINE> <INDENT> sha.update(index.encode()) <NEW_LINE> <DEDENT> return sha.hexdigest()[:32]
Creates a hash based on the configuration of this Source. The hash should uniquely identify a source configuration, without having to store a massive string.
625941bb090684286d50eb9c
def PlotResult(model,x_test,y_test): <NEW_LINE> <INDENT> x = [i+1 for i in range(len(y_test))][:100] <NEW_LINE> y_pred = model.predict(x_test) <NEW_LINE> plt.rcParams['font.family'] = ['sans-serif'] <NEW_LINE> plt.rcParams['font.sans-serif'] = ['SimHei'] <NEW_LINE> fig = plt.figure(figsize=(12,6)) <NEW_LINE> plt.plot(x,y_test[:100],c='green',label='y_true') <NEW_LINE> plt.plot(x,y_pred[:100],c='red',label='y_pred') <NEW_LINE> plt.legend() <NEW_LINE> plt.xlabel("预测\真实") <NEW_LINE> plt.ylabel("值大小") <NEW_LINE> plt.title("预测值与真实值变化趋势图") <NEW_LINE> plt.show()
预测值\真实值可视化.
625941bb925a0f43d2549d2f
def upload_test_results(self): <NEW_LINE> <INDENT> project_id = self.config_dict.get_config('project_id') <NEW_LINE> self.qtest_project_id = project_id <NEW_LINE> auto_api = swagger_client.TestlogApi() <NEW_LINE> auto_req = self._generate_auto_request() <NEW_LINE> try: <NEW_LINE> <INDENT> response = auto_api.submit_automation_test_logs_0(project_id=self._qtest_project_id, body=auto_req, type='automation') <NEW_LINE> <DEDENT> except ApiException as e: <NEW_LINE> <INDENT> raise RuntimeError("The qTest API reported an error!\n" "Status code: {}\n" "Reason: {}\n" "Message: {}".format(e.status, e.reason, e.body)) <NEW_LINE> <DEDENT> if response.state == 'FAILED': <NEW_LINE> <INDENT> raise RuntimeError("The qTest API failed to process the job!\nJob ID: {}".format(response.id)) <NEW_LINE> <DEDENT> self._requirement_link_facade.link() <NEW_LINE> return int(response.id)
Construct a 'AutomationRequest' qTest resource and upload the test results to the desired project in qTest Manager. Returns: int: The queue processing ID for the job. Raises: RuntimeError: Failed to upload test results to qTest Manager.
625941bb5fc7496912cc3841
def index_search(self, wait=True): <NEW_LINE> <INDENT> if not self.driver: <NEW_LINE> <INDENT> self.logger.error("Not connected.") <NEW_LINE> return False <NEW_LINE> <DEDENT> if self._index_searched: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for i, axis in enumerate(self.axes): <NEW_LINE> <INDENT> self.logger.info("Index search index_search axis %d..." % i) <NEW_LINE> axis.requested_state = AXIS_STATE_ENCODER_INDEX_SEARCH <NEW_LINE> <DEDENT> if wait: <NEW_LINE> <INDENT> for i, axis in enumerate(self.axes): <NEW_LINE> <INDENT> while axis.current_state != AXIS_STATE_IDLE: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> <DEDENT> <DEDENT> for i, axis in enumerate(self.axes): <NEW_LINE> <INDENT> if axis.error != 0: <NEW_LINE> <INDENT> self.logger.error("Failed index_search with axis error 0x%x, motor error 0x%x" % (axis.error, axis.motor.error)) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._index_searched = True <NEW_LINE> return True
Finding index, requires full rotation on motor
625941bbff9c53063f47c0b1
def off(self): <NEW_LINE> <INDENT> if self.state == OFF: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.process.terminate() <NEW_LINE> self.state = OFF
выключает видео
625941bb6e29344779a624d0
def _get_sal_config(self, channel): <NEW_LINE> <INDENT> if 'channels' not in self.config['sal']: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> if channel not in self.config['sal']['channels']: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> return self.config['sal']['channels'][channel]
Get SAL configuration for given channel.
625941bb2c8b7c6e89b3567e
def image_gradient_T(x): <NEW_LINE> <INDENT> if isinstance(x, np.ndarray): <NEW_LINE> <INDENT> x_h = x[0] <NEW_LINE> x_v = x[1] <NEW_LINE> x_h_ext = np.hstack((x_h, x_h[:, :1])) <NEW_LINE> x_v_ext = np.vstack((x_v, x_v[:1])) <NEW_LINE> d_x = x_h_ext[:, :-1] - x_h_ext[:, 1:] <NEW_LINE> d_y = x_v_ext[:-1] - x_v_ext[1:] <NEW_LINE> return d_x + d_y <NEW_LINE> <DEDENT> elif isinstance(x, ctorch.ComplexTensor): <NEW_LINE> <INDENT> x_h = x[0] <NEW_LINE> x_v = x[1] <NEW_LINE> x_h_ext = ctorch.cat((x_h, x_h[:, :1]), dim=1) <NEW_LINE> x_v_ext = ctorch.cat((x_v, x_v[:1]), dim=0) <NEW_LINE> d_x = x_h_ext[:, :-1] - x_h_ext[:, 1:] <NEW_LINE> d_y = x_v_ext[:-1] - x_v_ext[1:] <NEW_LINE> return d_x + d_y <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('Input must be a numpy.ndarray ' + 'or a ctorch.ComplexTensor.')
Transpose of the operator that function image_gradient implements. Computes the transpose of the matrix given by function image_gradient. Parameters ---------- x : numpy.ndarray or ctorch.ComplexTensor stack of two identically shaped arrays Returns ------- numpy.ndarray or ctorch.ComplexTensor result of applying to x the transpose of function image_gradient
625941bb76d4e153a657e9eb
def _IsTestMethod(attrname, test_case_class): <NEW_LINE> <INDENT> attr = getattr(test_case_class, attrname) <NEW_LINE> return callable(attr) and attrname.startswith('test')
Checks whether this is a valid test method. Args: attrname: the method name. test_case_class: the test case class. Returns: True if test_case_class.'attrname' is callable and it starts with 'test'; False otherwise.
625941bbb57a9660fec3373c
def get_lpm_len_from_node(self, node, dst_addr): <NEW_LINE> <INDENT> cur_lpm_len = 0 <NEW_LINE> dst_addr = ipaddress.ip_address(dst_addr) <NEW_LINE> is_ipv4 = isinstance(dst_addr, ipaddress.IPv4Address) <NEW_LINE> for cur_prefix in self.get_node_prefixes(node, is_ipv4): <NEW_LINE> <INDENT> if dst_addr in ipaddress.ip_network(cur_prefix): <NEW_LINE> <INDENT> cur_len = int(cur_prefix.split("/")[1]) <NEW_LINE> cur_lpm_len = max(cur_lpm_len, cur_len) <NEW_LINE> <DEDENT> <DEDENT> return cur_lpm_len
return the longest prefix match of dst_addr in node's advertising prefix pool
625941bb0fa83653e4656e78
def norm1(self, x): <NEW_LINE> <INDENT> return self._get_module_by_name(self.norm1_name)(x)
Apply norm1.
625941bb2eb69b55b151c767
def pc_output_buffers_full(self, *args): <NEW_LINE> <INDENT> return _Interfaces_swig.ax25_sink_b_sptr_pc_output_buffers_full(self, *args)
pc_output_buffers_full(ax25_sink_b_sptr self, int which) -> float pc_output_buffers_full(ax25_sink_b_sptr self) -> pmt_vector_float
625941bb7b180e01f3dc46c0
def test_clean_name_string(self): <NEW_LINE> <INDENT> self.assertEqual('this is a full name', baidu.clean_name_string('this is a full name')) <NEW_LINE> self.assertEqual('this is a full ,. pz', baidu.clean_name_string('this is a full ;,.$&[{{}}(=*)+]pz')) <NEW_LINE> self.assertEqual('', baidu.clean_name_string(''))
bibauthorid - test cleaning of name strings
625941bb167d2b6e31218a52
def last_record(): <NEW_LINE> <INDENT> out_record = dict() <NEW_LINE> out_record['date'] = "2014-12-08" <NEW_LINE> out_record['time'] = "21:38" <NEW_LINE> out_record['celsius'] = -4 <NEW_LINE> out_record['fahrenheit'] = int(round(out_record['celsius']*9/5.0 + 32)) <NEW_LINE> out_record['humidity'] = 50 <NEW_LINE> return out_record
Returns the last temperature and humidity record data. The returned object is a dict with keys ts, fahrenheit, celsius and humidity. In the mockup, there is no real temperature sensor to query, so an arbitrary result is returned.
625941bb56ac1b37e6264091
def variant(bg): <NEW_LINE> <INDENT> fullname = epp.literal(misc.normalize(bg.name)) <NEW_LINE> shortname = epp.literal(misc.normalize(bg.shortname)) <NEW_LINE> eff = epp.effect(lambda val, st: val.update({Capture.BACKGROUND: bg})) <NEW_LINE> return epp.chain( [epp.branch([fullname, shortname], save_iterator=False), eff], save_iterator=False)
Make a parser for the background.
625941bb379a373c97cfaa06
def get(self, request, format=None): <NEW_LINE> <INDENT> an_apiview = [ 'Uses HTTP methods as function (get, post, put, patch, delete).', 'It is similar to a traditional django view', 'Gives you the most control over your logic', 'Is mapped manually to URLs', ] <NEW_LINE> return Response({'message': 'Hello world', 'an_apiview': an_apiview })
Returns a list of APIView feature.
625941bbac7a0e7691ed3f94
def output_multiple(self): <NEW_LINE> <INDENT> return _trellis.trellis_viterbi_combined_fi_sptr_output_multiple(self)
output_multiple(self) -> int
625941bb21a7993f00bc7ba6
def delete_extra_channel(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.delete_extra_channel_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.delete_extra_channel_with_http_info(id, **kwargs) <NEW_LINE> return data
DeleteExtraChannel deletes the extra channel matching the given id. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_extra_channel(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: (required) :return: ApiDeleteExtraChannelResponse If the method is called asynchronously, returns the request thread.
625941bb66673b3332b91f4c
def to_basic_block(self): <NEW_LINE> <INDENT> return _gnuradio_core_general.gr_multiply_ff_sptr_to_basic_block(self)
to_basic_block(self) -> gr_basic_block_sptr
625941bba219f33f34628830
def generate_access_config(access, psecurity = False): <NEW_LINE> <INDENT> result_cmd_list = [] <NEW_LINE> access_template = [ 'switchport mode access', 'switchport access vlan', 'switchport nonegotiate', 'spanning-tree portfast', 'spanning-tree bpduguard enable' ] <NEW_LINE> port_security = [ 'switchport port-security maximum 2', 'switchport port-security violation restrict', 'switchport port-security' ] <NEW_LINE> for intf, vlan_num in access.items(): <NEW_LINE> <INDENT> result_cmd_list.append('interface {}'.format(intf)) <NEW_LINE> for cmd in access_template: <NEW_LINE> <INDENT> if cmd.endswith('access vlan'): <NEW_LINE> <INDENT> result_cmd_list.append(' {} {}'.format(cmd, vlan_num)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result_cmd_list.append(' {}'.format(cmd)) <NEW_LINE> <DEDENT> <DEDENT> if psecurity: <NEW_LINE> <INDENT> for cmd in port_security: <NEW_LINE> <INDENT> result_cmd_list.append(cmd) <NEW_LINE> <DEDENT> <DEDENT> result_cmd_list.append('!') <NEW_LINE> <DEDENT> return result_cmd_list
из задания 9.1а access - словарь access-портов, для которых необходимо сгенерировать конфигурацию, вида: { 'FastEthernet0/12':10, 'FastEthernet0/14':11, 'FastEthernet0/16':17 } psecurity - контролирует нужна ли настройка Port Security. По умолчанию значение False - если значение True, то настройка выполняется с добавлением шаблона port_security - если значение False, то настройка не выполняется Возвращает список всех команд, которые были сгенерированы на основе шаблона
625941bb627d3e7fe0d68d0a
def randomNetwork(sites, cmin=1, cmax=10): <NEW_LINE> <INDENT> sites = list(sites) <NEW_LINE> c = {} <NEW_LINE> for i in xrange(len(sites)): <NEW_LINE> <INDENT> a = sites[i] <NEW_LINE> c[a, a] = 0 <NEW_LINE> for j in xrange(i + 1, len(sites)): <NEW_LINE> <INDENT> b = sites[j] <NEW_LINE> c[b, a] = c[a, b] = randint(cmin, cmax) <NEW_LINE> <DEDENT> <DEDENT> return c
sites: names of the sites
625941bb8a43f66fc4b53f25
@csrf_exempt <NEW_LINE> def logUser(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> objJson = json.loads(request.body.decode('utf-8')) <NEW_LINE> login = objJson['login'] <NEW_LINE> password = objJson['password'] <NEW_LINE> user = authenticate(username=login, password=password) <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> if user.is_active: <NEW_LINE> <INDENT> logger.debug(str(user) + " authenticated !") <NEW_LINE> prof = Profile.objects.filter(id_user=user)[0] <NEW_LINE> p = ProfileDTO(prof, prof.pourcentage) <NEW_LINE> return myDumpJson(p.toJson()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error(str(user) + " is not active !") <NEW_LINE> return HttpResponse(status=401) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.error("Can't authenticate " + str(user) + "!") <NEW_LINE> return HttpResponse(status=400) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return HttpResponse(content="Not a POST request", status=400)
Connecte un utilisateur
625941bb2ae34c7f2600cfed
def get_list_example(): <NEW_LINE> <INDENT> return [ [1, '2017-11-01'], [2, '2017-11-08'], [3, '2017-11-15'] ]
获取某一类监控数据的列表,分页显示 :return: [ [1, '2017-11-01'], [2, '2017-11-08'], [3, '2017-11-15'] ]
625941bb1d351010ab8559d9
def test_assembly_fails_for_incompatible_dimensions(self): <NEW_LINE> <INDENT> from bempp.api import BlockedOperator <NEW_LINE> op = BlockedOperator(2, 1) <NEW_LINE> op[0, 0] = self._slp <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> op[1, 0] = self._hyp
Assembly fails for incompatible dimensions.
625941bb6aa9bd52df036c5e
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ReportCampaignsGroup): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
625941bbcc40096d6159580e
def __str__(self): <NEW_LINE> <INDENT> return self.outfit_name
String for representing the Outfit object.
625941bba17c0f6771cbdf0f
def _load_location(location, element): <NEW_LINE> <INDENT> location.file = element.get('file') <NEW_LINE> line = element.get('line') <NEW_LINE> if line is None: <NEW_LINE> <INDENT> line = element.get('linenr') <NEW_LINE> <DEDENT> if line is None: <NEW_LINE> <INDENT> line = '0' <NEW_LINE> <DEDENT> location.linenr = int(line) <NEW_LINE> location.column = int(element.get('column', '0'))
Load location from element/dict
625941bb60cbc95b062c6405
def __init__(self, title=None, description=None, visible=None, type=None, order=None, width=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._title = None <NEW_LINE> self._description = None <NEW_LINE> self._visible = None <NEW_LINE> self._type = None <NEW_LINE> self._order = None <NEW_LINE> self._width = None <NEW_LINE> self.discriminator = None <NEW_LINE> if title is not None: <NEW_LINE> <INDENT> self.title = title <NEW_LINE> <DEDENT> if description is not None: <NEW_LINE> <INDENT> self.description = description <NEW_LINE> <DEDENT> if visible is not None: <NEW_LINE> <INDENT> self.visible = visible <NEW_LINE> <DEDENT> if type is not None: <NEW_LINE> <INDENT> self.type = type <NEW_LINE> <DEDENT> if order is not None: <NEW_LINE> <INDENT> self.order = order <NEW_LINE> <DEDENT> if width is not None: <NEW_LINE> <INDENT> self.width = width
TopicGraphCreateRequest - a model defined in OpenAPI
625941bb796e427e537b047e
def test_baidu_search(self): <NEW_LINE> <INDENT> home_page = HomePage(self.driver) <NEW_LINE> home_page.search("selenium")
# 1 self.driver.find_element_by_id("kw").send_keys("selenium"+Keys.RETURN) time.sleep(2) assert "selenium" in self.driver.title
625941bb4527f215b584c316
def get_keywords(self, keyword_part='', current_dict=None): <NEW_LINE> <INDENT> keywords = dict() <NEW_LINE> if current_dict is None: <NEW_LINE> <INDENT> current_dict = self.keyword_trie_dict <NEW_LINE> <DEDENT> for char in current_dict: <NEW_LINE> <INDENT> if char == self._keyword_flag: <NEW_LINE> <INDENT> keywords[keyword_part] = current_dict[self._keyword_flag] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> keywords_ = self.get_keywords(keyword_part+char, current_dict[char]) <NEW_LINE> keywords.update(keywords_) <NEW_LINE> <DEDENT> <DEDENT> return keywords
获取所有的keywords Returns: keywords: list
625941bb10dbd63aa1bd2a6a
def __init__(self, id=None, label=None, data_type=None, input=None, values=None, operators=None): <NEW_LINE> <INDENT> self.swagger_types = { 'id': 'str', 'label': 'str', 'data_type': 'str', 'input': 'str', 'values': 'list[SchemeValueType]', 'operators': 'list[str]' } <NEW_LINE> self.attribute_map = { 'id': 'id', 'label': 'label', 'data_type': 'dataType', 'input': 'input', 'values': 'values', 'operators': 'operators' } <NEW_LINE> self._id = id <NEW_LINE> self._label = label <NEW_LINE> self._data_type = data_type <NEW_LINE> self._input = input <NEW_LINE> self._values = values <NEW_LINE> self._operators = operators
SchemeField - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941bb73bcbd0ca4b2bf39
def __setitem__ (self, name, newValue): <NEW_LINE> <INDENT> comp = self.fun <NEW_LINE> if isinstance( newValue, FunctionWrapper): <NEW_LINE> <INDENT> comp[name] = newValue.fun <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> comp[name] = newValue
Called from array-like access on LHS **It should not be called directly.** :param name: name or index in the [] :param newValue: new value for item
625941bbd8ef3951e32433f9
def __init__(self, client_id=None, event=None): <NEW_LINE> <INDENT> self._client_id = None <NEW_LINE> self._event = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.client_id = client_id <NEW_LINE> self.event = event
Log - a model defined in Swagger
625941bb30bbd722463cbc7f
def validate_date(self, date): <NEW_LINE> <INDENT> if isinstance(date, datetime.datetime) and date.date() < timezone.now().date(): <NEW_LINE> <INDENT> raise ValidationError("Please verify the end dates are not in the past.")
Validate that end dates are not in the past.
625941bb5166f23b2e1a5015