code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def song_similarity(self, songs, data): <NEW_LINE> <INDENT> data = data[data.media_id.isin(songs)] <NEW_LINE> data = data.drop_duplicates(['media_id'], keep='first') <NEW_LINE> data = data[['media_id', 'genre_id']] <NEW_LINE> data = data.drop_duplicates(['genre_id'], keep='first') <NEW_LINE> if len(data['media_id']) >=...
The function takes in a list of recommended songs and outputs a list of serendipitous songs by genre. If the list of serendipitous songs is too short(<= 5), we output the original recommendations. :param songs: list of recommended songs :return: list of serendipitous songs
625941cf7c178a314d6ef5af
def densenet121(pretrained=False, **kwargs): <NEW_LINE> <INDENT> model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16), **kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> pattern = re.compile(r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var)...
Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
625941cf91af0d3eaac9bb67
def __init__(self, region=None, rotation=None, sys=None, selection=None, keep_original=None): <NEW_LINE> <INDENT> self._region = None <NEW_LINE> self._rotation = None <NEW_LINE> self._sys = None <NEW_LINE> self._selection = None <NEW_LINE> self._keep_original = None <NEW_LINE> self.discriminator = None <NEW_LINE> if re...
RegionRequest - a model defined in Swagger
625941cfa4f1c619b28b0186
def deduplicate(arrs): <NEW_LINE> <INDENT> unique = [] <NEW_LINE> indices = [] <NEW_LINE> inverse = [] <NEW_LINE> for arr in arrs: <NEW_LINE> <INDENT> found = False <NEW_LINE> for idx, seen in enumerate(unique): <NEW_LINE> <INDENT> if np.all(np.array(seen) == np.array(arr)): <NEW_LINE> <INDENT> found = True <NEW_LINE> ...
Find duplicate arrays in arrs Implements a naive O(N**2) comparison of the current element with previous elements. Input: arrs - iterable of arrays Output: unique - unique elements indices - indices into unique that will restore the original array
625941cf63b5f9789fde7234
def __init__(self, method, func): <NEW_LINE> <INDENT> super(MethodDecorator, self).__init__(func) <NEW_LINE> self._config = method.methods, method.options, method.h2g
Initialization :Parameters: - `method`: `Method` instance - `func`: decorated callable :Types: - `method`: `Method` - `func`: ``callable``
625941cfd58c6744b4257dae
def split_catalog(catalog): <NEW_LINE> <INDENT> import copy <NEW_LINE> private_catalog = copy.deepcopy(catalog) <NEW_LINE> private_simulations = copy.deepcopy(catalog['simulations']) <NEW_LINE> public_catalog = { 'catalog_file_description': catalog['catalog_file_description'], 'modified': catalog['modified'], 'records'...
Split catalog four ways: private/public, and complete/simulations This function splits the catalog into four separate parts: 1) The complete catalog for open-access systems 2) The SXS metadata for open-access systems 3) The complete catalog for all systems 4) The SXS metadata for all systems The complete cat...
625941cf046cf37aa974ce96
def __init__(self, sub_store, service_store, connection): <NEW_LINE> <INDENT> super(DBService, self).__init__(sub_store, service_store) <NEW_LINE> self.connection = connection
Create a new DBService that will use the given connection to execute the query. It will create a new session and execute a transaction inside it. :param connection: a :class:`neo4j.v1.GraphDataBase` object :param sub_store: a SubscriptionStore :param service_store: a ServiceStore
625941cfa8ecb033257d321b
def do_disconnect(self): <NEW_LINE> <INDENT> mutex.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> adapter.stop() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> mutex.release() <NEW_LINE> <DEDENT> self.uuid = None <NEW_LINE> self.connected = False <NEW_LINE> self.upd...
Disconnect from the adapter :return:
625941cf82261d6c526ab5ee
def play_music(self, key, state): <NEW_LINE> <INDENT> pg.mixer.music.load(self.music_dict[key]) <NEW_LINE> pg.mixer.music.play() <NEW_LINE> self.state = state
toca musica
625941cf26238365f5f0efbd
def get_table_metadata(self, table_name: str, aligned_volume_name: str = None): <NEW_LINE> <INDENT> if aligned_volume_name is None: <NEW_LINE> <INDENT> aligned_volume_name = self.aligned_volume_name <NEW_LINE> <DEDENT> endpoint_mapping = self.default_url_mapping <NEW_LINE> endpoint_mapping["aligned_volume_name"] = alig...
Get metadata about a table Parameters ---------- table_name (str): name of table to mark for deletion aligned_volume_name: str or None, optional, Name of the aligned_volume. If None, uses the one specified in the client. Returns ------- json metadata about table
625941cf31939e2706e4cfb8
def minDistance(self, houses, k): <NEW_LINE> <INDENT> N = len(houses) <NEW_LINE> if k >= N: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> memo = dict() <NEW_LINE> houses.sort() <NEW_LINE> def dfs(start, end, boxes): <NEW_LINE> <INDENT> if boxes > end-start+1: <NEW_LINE> <INDENT> return float('inf') <NEW_LINE> <DEDEN...
:type houses: List[int] :type k: int :rtype: int
625941cfbd1bec0571d9077e
def tags(parsed_cg3): <NEW_LINE> <INDENT> return [_parsed_tags(s) for s in parsed_cg3]
Return a list of tags (as a list) from the parsed cg3 data.
625941cff548e778e58cd6cc
def get_vanadium_number(self, run_number): <NEW_LINE> <INDENT> if self._normByVanadium: <NEW_LINE> <INDENT> if run_number in self._vanRunNumberDict: <NEW_LINE> <INDENT> van_number = self._vanRunNumberDict[run_number] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('Run number {0} does not exist in vana...
get vanadium run number :return:
625941cf9c8ee82313fbb8c4
def hypothenuse(a, b): <NEW_LINE> <INDENT> return math.sqrt(a**2 + b**2)
returns the length of the hypothenuse when given the lengths of two other sides of a right-angled triangle
625941cf76e4537e8c3517c1
def _create_user(self, username, email, password, is_superuser, **extra_fields): <NEW_LINE> <INDENT> now = timezone.now() <NEW_LINE> if not username: <NEW_LINE> <INDENT> raise ValueError('The given username must be set') <NEW_LINE> <DEDENT> email = self.normalize_email(email) <NEW_LINE> utils.validate_email_unique(emai...
Creates and saves a User with the given username, email, password and superuser status. Adapted from the core ``auth.User`` model's ``UserManager``: we have no use for the ``is_staff`` field.
625941cf596a897236089c0f
def DiscreteGaussian( image1: Image, variance: List[float] = [1] * 3, maximumKernelWidth: int = 32, maximumError: float = 0.01, useImageSpacing: bool = True, ) -> Image: <NEW_LINE> <INDENT> f = DiscreteGaussianImageFilter() <NEW_LINE> f.SetVariance(variance) <NEW_LINE> f.SetMaximumKernelWidth(maximumKernelWidth) <NEW_L...
Blurs an image by separable convolution with discrete gaussian kernels. This filter performs Gaussian blurring by separable convolution of an image and a discrete Gaussian operator (kernel). This function directly calls the execute method of DiscreteGaussianImageFilter in order to support a procedural API. Also ...
625941cfbde94217f3682f3f
def refresh(self) -> None: <NEW_LINE> <INDENT> self.job = self.session.get(self.links["self"]).json()
Refresh the local cache of the serverside job object
625941cf8a43f66fc4b541b3
def falling(n, k): <NEW_LINE> <INDENT> fac_num = 1 <NEW_LINE> while k > 0: <NEW_LINE> <INDENT> fac_num *= n <NEW_LINE> k, n = k - 1, n - 1 <NEW_LINE> <DEDENT> return fac_num
Compute the falling factorial of n to depth k. >>> falling(6, 3) # 6 * 5 * 4 120 >>> falling(4, 0) 1 >>> falling(4, 3) # 4 * 3 * 2 24 >>> falling(4, 1) # 4 4
625941cf67a9b606de4a8008
def test_star(self): <NEW_LINE> <INDENT> g = self.compile("xs = 'x'*") <NEW_LINE> self.assertEqual(g.xs(""), "") <NEW_LINE> self.assertEqual(g.xs("x"), "x") <NEW_LINE> self.assertEqual(g.xs("xxxx"), "xxxx") <NEW_LINE> self.assertRaises(_MaybeParseError, g.xs, "xy")
Input matches can be made on zero or more repetitions of a pattern.
625941cfad47b63b2c50a0ce
def __iter__(self): <NEW_LINE> <INDENT> return self
Return an iterator. @rtype: iterator which yields L{bytes} @return: An iterator over strings.
625941cf9b70327d1c4e0f24
def heur_manhattan_distance(state): <NEW_LINE> <INDENT> sum = 0 <NEW_LINE> center = int((state.width-1)/2) <NEW_LINE> for i in state.xanadus: <NEW_LINE> <INDENT> sum+=(abs(i[0]-center) + abs(i[1]-center)) <NEW_LINE> <DEDENT> return sum
Manhattan distance LunarLockout heuristic
625941cf097d151d1a222fa8
def is_valid_repository(self): <NEW_LINE> <INDENT> p = self._run_git(['ls-remote', self.path, 'HEAD']) <NEW_LINE> errmsg = p.stderr.read() <NEW_LINE> failure = p.wait() <NEW_LINE> if failure: <NEW_LINE> <INDENT> logging.error("Git: Failed to find valid repository %s: %s" % (self.path, errmsg)) <NEW_LINE> return False <...
Checks if this is a valid Git repository.
625941cf3346ee7daa2b2ebb
def SetGuid(self,item_name,*__args): <NEW_LINE> <INDENT> pass
SetGuid(self: GH_IWriter,item_name: str,item_index: int,item_value: Guid) Add a new data item to this chunk. The combination of name and index must be unique or an exception will be thrown. item_name: Name of item to add. item_index: Index of item to add. item_value: Value of item to add. SetGuid(...
625941cf283ffb24f3c55a4f
def can_see(self, target): <NEW_LINE> <INDENT> if not target or not target.position: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return target.position in self.visible_tiles
Returns true if target entity is in sight
625941cfbe383301e01b55d4
def testDrawAndChangeCurrentTime(self): <NEW_LINE> <INDENT> self._testName = 'ProxyShapeDrawTimeSampledTest' <NEW_LINE> mayaSceneFile = '%s.ma' % self._testName <NEW_LINE> mayaSceneFullPath = os.path.abspath(mayaSceneFile) <NEW_LINE> cmds.file(mayaSceneFullPath, open=True, force=True) <NEW_LINE> UsdMaya.LoadReferenceAs...
Tests drawing a USD proxy shape node that references USD with time sampled data. This test ensures that the shape is redrawn correctly when upstream connections are dirtied. The built in "time1" object's "outTime" plug is the source of the connection to the assembly node's "time" plug, which is then the source of the ...
625941cfa219f33f34628ab8
def _items(self, request, do_authz=False, parent_id=None): <NEW_LINE> <INDENT> original_fields, fields_to_add = self._do_field_list( api_common.list_args(request, 'fields')) <NEW_LINE> filters = api_common.get_filters( request, self._attr_info, ['fields', 'sort_key', 'sort_dir', 'limit', 'marker', 'page_reverse'], is_f...
Retrieves and formats a list of elements of the requested entity.
625941cfa934411ee37517e2
def _render_exception(self, error_code, values): <NEW_LINE> <INDENT> assert error_code in [400, 401, 404, 500] <NEW_LINE> values['status_code'] = error_code <NEW_LINE> if (self.payload is not None or self.GET_HANDLER_ERROR_RETURN_TYPE == feconf.HANDLER_TYPE_JSON): <NEW_LINE> <INDENT> self.render_json(values) <NEW_LINE>...
Renders an error page, or an error JSON response. Args: error_code: int. The HTTP status code (expected to be one of 400, 401, 404 or 500). values: dict. The key-value pairs to include in the response.
625941cf0a50d4780f666fe1
def test_data_data_id_export_get(self): <NEW_LINE> <INDENT> response = self.client.open('//data/{data_id}/export'.format(data_id='data_id_example'), method='GET') <NEW_LINE> self.assert200(response, "Response body is : " + response.data.decode('utf-8'))
Test case for data_data_id_export_get def _exportDataProvenance(data_id):
625941cf287bf620b61d3bb2
@click.command("Update the name attribute of a Cadnano JSON file to match its current filename.") <NEW_LINE> @click.argument("jsonfile") <NEW_LINE> @click.option("--include-ext/--no-include-ext", default=True) <NEW_LINE> def reset_cadnano_json_name_cli(jsonfile, include_ext=True): <NEW_LINE> <INDENT> with open(jsonfile...
cadnano-reset-json-name
625941cf6fece00bbac2d88e
def tiles_under(self, x, y): <NEW_LINE> <INDENT> tiles = [] <NEW_LINE> tier = self.top_tier(x, y) <NEW_LINE> if tier: <NEW_LINE> <INDENT> for name in tier.layer_names: <NEW_LINE> <INDENT> tile = tier.layers[name].get_tile(x, y) <NEW_LINE> tiles.append(tile) <NEW_LINE> <DEDENT> <DEDENT> return tiles
Returns a list of tiles on the top tier under the coordinates given, from bottom layer to top.
625941cf99fddb7c1c9de4e0
def main(): <NEW_LINE> <INDENT> args = parse_arguments() <NEW_LINE> if not args.train and not args.test: <NEW_LINE> <INDENT> print("If we are not training, and not testing, what is the point?") <NEW_LINE> <DEDENT> crnn = None <NEW_LINE> if args.train: <NEW_LINE> <INDENT> crnn = CRNN( args.batch_size, args.model_path, a...
Entry point when using CRNN from the commandline
625941cf99cbb53fe6792d35
def quantity(self, asset, include_held=False): <NEW_LINE> <INDENT> if isinstance(asset, str): <NEW_LINE> <INDENT> asset = self.__getitem__(asset) <NEW_LINE> <DEDENT> if isinstance(asset, Currency): <NEW_LINE> <INDENT> assets = self.get_assets(include_positions=False, include_holdings=True, include_held=include_held) <N...
Get owned quantity of asset Args: asset: (Currency | Stock | str) the query currency/stock or symbol include_held: (bool, optional) whether to included held assets in the tally Returns: (Decimal) Quantity of asset owned Raises: UsageError: If the asset is not valid
625941cf3cc13d1c6d3c74c9
def calc_storage(Q, alpha, beta, gamma, lb_correction = 0.1): <NEW_LINE> <INDENT> import scipy.integrate as integrate <NEW_LINE> def int_gQdQ(Q, alpha, beta, gamma): <NEW_LINE> <INDENT> gQ = gQ_fun(Q, alpha, beta, gamma) <NEW_LINE> int_gQ = 1 / gQ <NEW_LINE> return int_gQ <NEW_LINE> <DEDENT> def set_par(param, idx): <N...
Calcate the storage by numerically integrating 1/gQ over [0, Q], using scipy.integrate.quad. This function requires a lower and upper boundary for the integration. Since a value of 0 for the lower boundary will result in an error (when gamma != 0), so a value close to zero is preferred. In this case, the lower boundary...
625941cf4428ac0f6e5ba941
def accepts_drops(self, dragged): <NEW_LINE> <INDENT> return False
Reimplement this to evaluate if this Movable should accept drops from dragged. Default returns False. :param dragged: Item that is being dragged. You may want to look into what kind of object this is and decide from that. :return:
625941cf56b00c62f0f147a9
def read_table_header_top(table): <NEW_LINE> <INDENT> transpose = [[] for key in table[0]] <NEW_LINE> for row in table[1:]: <NEW_LINE> <INDENT> for ncol, val in enumerate(row): <NEW_LINE> <INDENT> transpose[ncol].append(val) <NEW_LINE> <DEDENT> for i in range(len(row), len(transpose)): <NEW_LINE> <INDENT> transpose[i]....
Read a table with header in first row. @param table Matrix format @return dict Dictionary with header as key
625941cf66673b3332b921e0
def cases(self): <NEW_LINE> <INDENT> import pyark.subclients.cases_client <NEW_LINE> if self._cases_client is None: <NEW_LINE> <INDENT> self._cases_client = pyark.subclients.cases_client.CasesClient( url_base=self._url_base, token=self._token, user=self._user, password=self._password) <NEW_LINE> <DEDENT> return self._c...
:return: :rtype: CasesClient
625941cf50812a4eaa59c470
def getTimeList(day, categoryList): <NEW_LINE> <INDENT> timelist = [] <NEW_LINE> for cat in categoryList: <NEW_LINE> <INDENT> time = 0 <NEW_LINE> for event in cat['items']: <NEW_LINE> <INDENT> eventDay, daystr = getDay(event['start']['dateTime']) <NEW_LINE> if eventDay != day: <NEW_LINE> <INDENT> continue <NEW_LINE> <D...
for this day: traverse all category calculate each category's time return timeList store each category's time
625941cf283ffb24f3c55a50
def get_weights(self, weight_tensor): <NEW_LINE> <INDENT> return weight_tensor.eval(self.trainer.session)
Get weights. Get a variable weights. Examples: sgen = SequenceGenerator(...) w = sgen.get_weights(denselayer.W) -- get a dense layer weights Arguments: weight_tensor: `tf.Tensor`. A Variable. Returns: `np.array`. The provided variable weights.
625941cfbe7bc26dc91cd74e
def acquire(self, blocking=False, timeout=None): <NEW_LINE> <INDENT> raise NotImplemented()
Acquire a lock at the Lock's path. Return True if acquired, False otherwise `blocking` (bool) If False, return immediately if we got lock. If True, wait up to `timeout` seconds to acquire a lock `timeout` (int) number of seconds. By default, wait indefinitely
625941cf460517430c3942d3
def load_data(file_path): <NEW_LINE> <INDENT> raw_data = pd.read_csv(DATA_FILE_PATH) <NEW_LINE> raw_data.fillna(0, inplace=True) <NEW_LINE> raw_data.columns = [col.lower() for col in raw_data.columns] <NEW_LINE> with open(file_path) as file: <NEW_LINE> <INDENT> json_file = json.load(file) <NEW_LINE> <DEDENT> return raw...
Loads X and y data from resources using predetermined features Returns two DataFrames, X and y data :param string file_path: specifies which model's final values to utilize :return: tuple(DataFrame, DataFrame)
625941cf73bcbd0ca4b2c1c5
def temperature_elevation(self, link_area_m: float) -> float: <NEW_LINE> <INDENT> return (self.emission_quantity() / 3600 / link_area_m) * (0.8 / 100)
Get the expected ambient temperature elevation for this link due to vehicle exhaust. Parameters: link_area_m (float): Square area of link in meters^2. Returns: Ambient temperature elevation for this link, in degrees Celcius.
625941cf5fc7496912cc3acd
def execute_yara_task(mqueue): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> yara_task = mqueue.get(True) <NEW_LINE> if yara_task is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result = yara_task.execute() <NEW_LINE> if result: <NEW_LINE> <INDENT> result = yara_task.apply_r...
Special dedicated YARA worker. Dispatches newly created yara rules on the samples pool. There is no analysis in this case, nor priority considerations, that's why it has been separated.
625941cf2eb69b55b151c9ff
def SetParticleImage(self, *args): <NEW_LINE> <INDENT> return _itkSmoothColorFieldImageFilterPython.itkSmoothColorFieldImageFilterIUS2ICVF22_SetParticleImage(self, *args)
SetParticleImage(self, itkImageUS2 arg0) -> int
625941cfa219f33f34628ab9
def editor_test(): <NEW_LINE> <INDENT> app = qapplication() <NEW_LINE> dialog = CollectionsEditor() <NEW_LINE> dialog.setup(get_test_data()) <NEW_LINE> dialog.show() <NEW_LINE> app.exec_() <NEW_LINE> print("out:", dialog.get_value())
Collections editor test
625941cf7d43ff24873a2df0
def printBoard(self): <NEW_LINE> <INDENT> currBoard = numpy.full((8, 8), 0) <NEW_LINE> currKings = numpy.full((8, 8), 0) <NEW_LINE> print("\tBoard:\n") <NEW_LINE> index = 0 <NEW_LINE> for piece in self.currPlayer.pieces: <NEW_LINE> <INDENT> x, y, isKing = piece <NEW_LINE> loc = x, y <NEW_LINE> currBoard[loc] = self.cur...
Print the board i.e. prints the positions of the player and the opposition and also returns the pieces remaining
625941cfb57a9660fec339d3
def n(self): <NEW_LINE> <INDENT> return self.__nx
returns the number of frames
625941cf5166f23b2e1a52a8
def find_nearest_color_hexstr(hexdigits, color_table=None): <NEW_LINE> <INDENT> triplet = [] <NEW_LINE> try: <NEW_LINE> <INDENT> if len(hexdigits) == 3: <NEW_LINE> <INDENT> for digit in hexdigits: <NEW_LINE> <INDENT> digit = int(digit, 16) <NEW_LINE> triplet.append((digit * 16) + digit) <NEW_LINE> <DEDENT> <DEDENT> eli...
Given a three or six-character hex digit string, return the nearest color index. Arguments: hexdigits: a three/6 digit hex string, e.g. 'b0b' Returns: int, None: index, or None on error.
625941cf5166f23b2e1a52a9
def disable_snmp(self, snmp_community, action_map=None, error_map=None): <NEW_LINE> <INDENT> return CommandTemplateExecutor(cli_service=self._cli_service, command_template=aireos_enbl_disbl_snmp.DISABLE_SNMP, action_map=action_map, error_map=error_map).execute_command(snmp_community=snmp_community)
Disable SNMP on the device :param snmp_community: community name :param action_map: actions will be taken during executing commands, i.e. handles yes/no prompts :param error_map: errors will be raised during executing commands, i.e. handles Invalid Commands errors
625941cf23e79379d52ee6b3
def setFirstEvent(self, firstEv): <NEW_LINE> <INDENT> self.data.firstEvent = CfgTypes.untracked( CfgTypes.uint32(int(firstEv)))
set first event number
625941cf8e05c05ec3eea4c5
@cached_for_request <NEW_LINE> @requires_login <NEW_LINE> def can_create_organizations(user): <NEW_LINE> <INDENT> if user.is_superuser: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> result = plugins.first('has_perm', user, 'add_organization') <NEW_LINE> if result is False: <NEW_LINE> <INDENT> return result <NEW_L...
Returns a boolean describing whether a user has the ability to create new organizations.
625941cf293b9510aa2c33e5
def find_email(self, email): <NEW_LINE> <INDENT> emailIsStr = type(email) == str <NEW_LINE> if(emailIsStr): <NEW_LINE> <INDENT> result = db.session.query(User).filter(User.email==email).all() <NEW_LINE> return(result) <NEW_LINE> <DEDENT> return([])
@brief Funcion que realiza la busqueda del usuario cuyo email sea "email" @param email: Correo del usuario a buscar. @return lista con la consulta solicitada.
625941cfe5267d203edcddec
def balance_samples(x_samples, y_samples): <NEW_LINE> <INDENT> pass
Balances samples between OTHER output token and the rest. As it turns out, most samples don't have punctuation in the middle, so we need to weigh training more heavily towards punctuation-rich samples so the model learns that.
625941cf4e696a04525c959b
def get_audio_video_urls(dom_tree): <NEW_LINE> <INDENT> urls = [] <NEW_LINE> for el in dom_tree('video, audio, embed, source'): <NEW_LINE> <INDENT> src = el.attrib.get('src', '').strip() <NEW_LINE> if src: <NEW_LINE> <INDENT> urls.append(src) <NEW_LINE> <DEDENT> <DEDENT> return urls
Return urls listed in video/audio/embed/source tag src attributes.
625941cf099cdd3c635f0dab
def release_all_connection(self, delete=False): <NEW_LINE> <INDENT> self._condition.acquire() <NEW_LINE> for connection in self._active_connection[:]: <NEW_LINE> <INDENT> self._active_connection.remove(connection) <NEW_LINE> if delete is False: <NEW_LINE> <INDENT> self._idle_connection.append(connection) <NEW_LINE> <DE...
The method can be used to release all the connection from the connection pool. If the delete flag is passed as True, the connections inside the active connection will be release and deleted and will not be added inside the idle connection list. If the delete flag is false, the connections will be released from the acti...
625941cf0c0af96317bb8338
def undo_pending_song_deletion(self, coresong, position): <NEW_LINE> <INDENT> self._songs_todelete.remove(coresong) <NEW_LINE> self._model.insert(position, coresong) <NEW_LINE> self.props.count += 1
Removes song from the list of songs to delete :param CoreSong coresong: song to delete :param int position: Song position in the playlist
625941cf99cbb53fe6792d36
def p_loop3(p): <NEW_LINE> <INDENT> pass
loop3 : TO_LLAABRE bloque TO_LLACIERRA
625941cfe76e3b2f99f3a95a
def do_OPTIONS(self): <NEW_LINE> <INDENT> self.send_response(200, "ok") <NEW_LINE> self.send_header('Access-Control-Allow-Origin', '*') <NEW_LINE> self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS, POST, HEAD') <NEW_LINE> self.send_header("Access-Control-Allow-Headers", "*") <NEW_LINE> self.end_headers()
Enable CORS while running on a different host
625941cf56ac1b37e626431e
def plot_lstm_prediction(actual, prediction, chart_name='Plot.png', title='Actual vs Prediction', y_label='Price USD', x_label='Trading Days'): <NEW_LINE> <INDENT> title = chart_name <NEW_LINE> fig = plt.figure() <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> plt.ylabel(y_label) <NEW_LINE> plt.xlabel(x_label) <NEW_LIN...
Plots train, test and prediction :param chart_name: Name of the chart being plotted :param actual: DataFrame containing actual data :param prediction: DataFrame containing predicted values :param title: Title of the plot :param y_label: yLabel of the plot :param x_label: xLabel of the plot :return: prints a Pyplot aga...
625941cf71ff763f4b5497dc
def test_day_init() -> None: <NEW_LINE> <INDENT> p = Player("bob", 5000) <NEW_LINE> nyc = Day("NYC", p) <NEW_LINE> assert len(nyc._drugs) == 10 <NEW_LINE> for _, drug in nyc._drugs.items(): <NEW_LINE> <INDENT> assert isinstance(drug, Drug)
Tests that day initializes properly
625941cf8e7ae83300e4b11d
def generate_sftp_file(username, password, direcories=None): <NEW_LINE> <INDENT> file_content = generate_sftp_user_line(username, password, direcories) <NEW_LINE> create_or_replace_config_file(EDIT_FILES['sftp_users'], file_content)
Generates a sftp password file :username: username to use :password: password that will be used :directories: list of directories which the user should have
625941cfb7558d58953c5063
def test_http_head(self): <NEW_LINE> <INDENT> self.spy_on(self.client.build_http_request) <NEW_LINE> response = self.client.http_head( url='http://example.com', headers={ 'Foo': 'bar', }, username='username', password='password') <NEW_LINE> self.assertIsInstance(response, HostingServiceHTTPResponse) <NEW_LINE> self.ass...
Testing HostingServiceClient.http_head
625941cf94891a1f4081bbfa
def wd_get_left_hand_guv(): <NEW_LINE> <INDENT> return np.array([0, -1, 0])
Returns the gravity unit vector for the wearable device placed on the left hand wrist. Syntax: guv = wd_get_left_hand_guv() Parameters: None Returns: the three axis vector for the wearable device properly placed on the left hand wrist, which is [0, -1, 0]. This is because of how the axis of the 3D...
625941cf3317a56b86939da8
def get_total(self): <NEW_LINE> <INDENT> fee = 0 <NEW_LINE> self.base_price = self.get_base_price() <NEW_LINE> fee += self.get_date_time_surge_fee() <NEW_LINE> if self.species == "christmas": <NEW_LINE> <INDENT> self.base_price = 1.5 * self.base_price <NEW_LINE> <DEDENT> if self.order_type == 'international' and self.q...
Calculate price, including tax.
625941cfadb09d7d5db6c8e0
def choose_desktop(self, swipe, current_desktop, total_desktop): <NEW_LINE> <INDENT> total = total_desktop - 1 <NEW_LINE> action = current_desktop + swipe <NEW_LINE> if action < 0: <NEW_LINE> <INDENT> return total <NEW_LINE> <DEDENT> elif action > total: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE>...
Calculate the desktop to move to. :param swipe: number (-1 or 1, swipe left or right) :param current_desktop: number :param total_desktop: total number of desktops
625941cf76d4e153a657ec81
def build(): <NEW_LINE> <INDENT> includes = ['static', 'templates', 'transwarp', 'favicon.ico', '*.py'] <NEW_LINE> excludes = ['test', '.*', '*.pyc', '*.pyo'] <NEW_LINE> local('rm -f dist/%s' % _TAR_FILE) <NEW_LINE> with lcd(os.path.join(_current_path(), 'www')): <NEW_LINE> <INDENT> cmd = ['tar', '--dereference', '-czv...
Build dist package.
625941cf3cc13d1c6d3c74ca
def __statistics_submenu(self): <NEW_LINE> <INDENT> menu_string = "Statistics submenu\n" <NEW_LINE> menu_string += "\t1. Students enrolled at a discipline\n" <NEW_LINE> menu_string += "\t2. Students failing at a discipline\n" <NEW_LINE> menu_string += "\t3. Students with best school situation\n" <NEW_LINE> menu_string ...
Submenu for the statistics functionality. Prints the available options and then reads the command from the user and calls the corresponding method :return:
625941cf091ae356686670ae
def push(self, entry): <NEW_LINE> <INDENT> LOGGER.debug("push(%r)", entry) <NEW_LINE> if self.on_push: <NEW_LINE> <INDENT> self.on_push(self, entry) <NEW_LINE> <DEDENT> ck = hashlib.sha256() <NEW_LINE> self.stack.append((entry, ck))
Adds an empty subdirectory at the end of the stack, with a new cksum. >>> ds = DirHashStack() >>> ds.push(b'a') >>> ds.push(b'b') >>> ds.entries() # doctest: +NORMALIZE_WHITESPACE [(b'a', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'), (b'b', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca4959...
625941cf7d847024c06be40c
def get_version(self, revision, required=False): <NEW_LINE> <INDENT> for version in reversed(self.versions): <NEW_LINE> <INDENT> if version.identifier == revision: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if required: <NEW_LINE> <INDENT> raise exceptions.VersionNotFoundError(revi...
Find a version with identifier revision :returns: FileVersion or None :raises: VersionNotFoundError if required is True
625941cf38b623060ff0af3e
def get_search_results(query): <NEW_LINE> <INDENT> global index, doc_names <NEW_LINE> result = ranked = list() <NEW_LINE> doc_list = set(doc_names.keys()) <NEW_LINE> flag = 0 <NEW_LINE> for word in query: <NEW_LINE> <INDENT> if word in index: <NEW_LINE> <INDENT> flag = 1 <NEW_LINE> doc_list = doc_list.intersection(inde...
Search for the query in the positional index. Args - query: List of processed words Return - ranked: List of (doc_id, start_position) for the query.
625941cf8c0ade5d55d3eb0c
def __init__(self, action_size, buffer_size, batch_size, seed, alpha, beta): <NEW_LINE> <INDENT> self.action_size = action_size <NEW_LINE> self.memory = {} <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done" ,"prior...
Initialize a ReplayBuffer object. Params ====== action_size (int): dimension of each action buffer_size (int): maximum size of buffer batch_size (int): size of each training batch seed (int): random seed alpha (float): sampling exponent (between 0 and 1) beta(float): importance sampling exponen...
625941cf046cf37aa974ce98
def convert_nodes(context, graph): <NEW_LINE> <INDENT> for node in _tqdm(graph.nodes, desc="Converting Frontend ==> MIL Ops", unit=" ops"): <NEW_LINE> <INDENT> _add_op = _TORCH_OPS_REGISTRY.get(node.kind, None) <NEW_LINE> _logging.info("Converting op {} : {}".format(node.name, node.kind)) <NEW_LINE> if _add_op is None:...
Iterate over the nodes of a graph or block and convert to MIL. Arguments: context: A TranscriptionContext object to pull node inputs and assign node outputs. graph: An InternalTorchIRGraph or InternalTorchIRBlock object.
625941cf26238365f5f0efbf
def test_is_in_set(): <NEW_LINE> <INDENT> trials = 10000 <NEW_LINE> count = 0 <NEW_LINE> j = 5 <NEW_LINE> for i in range(trials): <NEW_LINE> <INDENT> if is_in_set(1,i,j,seed=0): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> assert abs((count/trials) - 2**(-j)) < (1/math.sqrt(trials)) <NEW_LINE> count = 0 ...
Test if is_in_set works properly (If produces correct probabilities).
625941cffbf16365ca6f6316
def migration_exchange( self, *, users: List[str], **kwargs ) -> Union[Future, SlackResponse]: <NEW_LINE> <INDENT> kwargs.update({"users": users}) <NEW_LINE> return self.api_call("migration.exchange", http_verb="GET", params=kwargs)
For Enterprise Grid workspaces, map local user IDs to global user IDs Args: users (list): A list of user ids, up to 400 per request. e.g. ['W1234567890', 'U2345678901', 'U3456789012']
625941cf507cdc57c6306e2c
def get_var_name(ins, allow_empty=False): <NEW_LINE> <INDENT> name = '' <NEW_LINE> d = skip_white_read(ins).upper() <NEW_LINE> if not (d >= 'A' and d <= 'Z'): <NEW_LINE> <INDENT> ins.seek(-len(d), 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> while (d>='A' and d<='Z') or (d>='0' and d<='9') or d=='.': <NEW_LINE> <IN...
Get variable name from token stream.
625941cf379a373c97cfac95
def fourUp(image): <NEW_LINE> <INDENT> newImage = image.copy() <NEW_LINE> pixels = newImage.load() <NEW_LINE> minX, minY, width, height = image.getbbox() <NEW_LINE> for y in range(0, height, 2): <NEW_LINE> <INDENT> for x in range(0, width, 2): <NEW_LINE> <INDENT> rgb = pixels[x,y] <NEW_LINE> pixels[x/2,y/2] = pixels[x,...
Takes in an image and returns a image that has four 1/4 sized versions of the original in it.
625941cf596a897236089c11
def get_biases(ckpt): <NEW_LINE> <INDENT> tf.reset_default_graph() <NEW_LINE> with tf.Session() as sess: <NEW_LINE> <INDENT> saver = tf.train.import_meta_graph('{}.meta'.format(ckpt)) <NEW_LINE> saver.restore(sess, tf.train.latest_checkpoint(os.path.dirname(ckpt))) <NEW_LINE> biases = tf.get_collection(tf.GraphKeys.BIA...
ckptに保存された学習結果networkのバイアス情報を取得する
625941cfbde94217f3682f41
def setCursor(echo_visibility = False): <NEW_LINE> <INDENT> if echo_visibility: <NEW_LINE> <INDENT> curses.echo() <NEW_LINE> curses.curs_set(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> curses.noecho() <NEW_LINE> curses.curs_set(0)
Convenience function to turn echo and cursor visibility on/off. Arguments: echo_visibility: [Boolean] True for echo on/cursor visible, false otherwise.
625941cf2c8b7c6e89b35911
def check_name_availability( self, location, name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> digital_twins_instance_check_name = models.CheckNameRequest(name=name) <NEW_LINE> url = self.check_name_availability.metadata['url'] <NEW_LINE> path_format_arguments = { 'subscriptionId': self._se...
Check if a DigitalTwinsInstance name is available. :param location: Location of DigitalTwinsInstance. :type location: str :param name: Resource name. :type name: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :...
625941cf67a9b606de4a800a
def process_event(event, assistant): <NEW_LINE> <INDENT> if event.type == EventType.ON_CONVERSATION_TURN_STARTED: <NEW_LINE> <INDENT> print("Listening ...") <NEW_LINE> bell() <NEW_LINE> amixer.set_low_sound_level() <NEW_LINE> <DEDENT> l.info(event) <NEW_LINE> if event.type == EventType.ON_RECOGNIZING_SPEECH_FINISHED: <...
Pretty prints events. Prints all events that occur with two spaces between each new conversation and a single space between turns of a conversation. Args: event(event.Event): The current event to process.
625941cfc4546d3d9de72b85
def update_fileswitcher_dlg(self): <NEW_LINE> <INDENT> if self.fileswitcher_dlg: <NEW_LINE> <INDENT> self.fileswitcher_dlg.setup()
Synchronize file list dialog box with editor widget tabs
625941cf1b99ca400220ac02
def __init__(self, api_version=None, kind=None, metadata=None, spec=None, status=None): <NEW_LINE> <INDENT> self._api_version = None <NEW_LINE> self._kind = None <NEW_LINE> self._metadata = None <NEW_LINE> self._spec = None <NEW_LINE> self._status = None <NEW_LINE> self.discriminator = None <NEW_LINE> if api_version is...
V1beta1DaemonSet - a model defined in Swagger
625941cf16aa5153ce3625c8
def refraction(n1, n2, θ1): <NEW_LINE> <INDENT> θ2 = arcsind(n1 / n2 * sind(θ1)) <NEW_LINE> return θ2
Return the refracted angle of light (degrees) where n1 is the refractive index of incident medium (units), n2 is the refractive index of the transmission medium (units) and θ1 is the incident angle to the normal
625941cf91af0d3eaac9bb6a
def __init__(self, sprite, life, position, velocity, acceleration): <NEW_LINE> <INDENT> self.life = life <NEW_LINE> self.sprite = sprite <NEW_LINE> self.position = position <NEW_LINE> self.velocity = velocity <NEW_LINE> self.acceleration = acceleration <NEW_LINE> self.angle = 0
:param sprite: graphical representation for the particle :type sprite: type of your choice :param life: lifetime of the particle in frames :type life: int :param position: initial vector for position of a particle :type position: 2d list :param velocity: velocity vector :type velocity: 2d list :param acceleration: init...
625941cf0383005118ecf733
def find_next_action(self, child): <NEW_LINE> <INDENT> found = False <NEW_LINE> for dchild in self.children(): <NEW_LINE> <INDENT> if found: <NEW_LINE> <INDENT> if isinstance(dchild, WxAction): <NEW_LINE> <INDENT> return dchild.widget <NEW_LINE> <DEDENT> if isinstance(dchild, WxActionGroup): <NEW_LINE> <INDENT> acts = ...
Locate the wxAction object which logically follows the child. Parameters ---------- child : WxToolkitObject The child object of interest. Returns ------- result : wxAction or None The wxAction which logically follows the position of the child in the list of children. None will be returned if a relevan...
625941cf8a43f66fc4b541b6
def test_less_0(self): <NEW_LINE> <INDENT> self.assertEqual(get_sequence(-10), [])
test with numbers less than 0
625941cf63f4b57ef0001269
def lrange(self, name, start, end): <NEW_LINE> <INDENT> return self.server.lrange(name, start, end)
This method returns a slice of the redis list between the slice bounds.
625941cf287bf620b61d3bb4
def __init__(self, callback): <NEW_LINE> <INDENT> super(ThreadedXMLRPCServer, self).__init__(callback) <NEW_LINE> self._rpc_thread = None <NEW_LINE> self._xmlrpc_server = None
Initialize a threaded RPC server. Args: callback (function): callback function to invoke on get status RPC request.
625941cf99fddb7c1c9de4e2
def all_segments(n): <NEW_LINE> <INDENT> return [(_i, _j) for _i in range(1, n) for _j in range(_i + 2, n)]
Generate all pair nodes combinations :param n: :return:
625941cf4e4d5625662d4528
def build(self, x, x_mask, C, C_mask, h_init=None): <NEW_LINE> <INDENT> self._input = x <NEW_LINE> self._input_mask = x_mask <NEW_LINE> self._input_context = C <NEW_LINE> self._input_context_mask = C_mask <NEW_LINE> if x_mask is None: <NEW_LINE> <INDENT> x_mask = T.ones_like(x, dtype='float32') <NEW_LINE> <DEDENT> x_W ...
Function to build the GRU using the initialized parameters :param x: the input to the layer :param x_mask: the input mask :param C: context matrix for each sample (3-D tensor), to use attention on. dim = #timesteps x #samles x context_dim
625941cf21bff66bcd684aa3
def spinbox(self, title, value=None, *args, **kwargs): <NEW_LINE> <INDENT> return self.spinBox(title, value, *args, **kwargs)
simpleGUI - shortner for spinBox()
625941cf21a7993f00bc7e41
@pytest.mark.parametrize('code', [ raise_not_implemented_method, raise_not_implemented_function, raise_not_implemented_raw, raise_not_implemented_property, ]) <NEW_LINE> @pytest.mark.parametrize('exception', [ 'NotImplementedError', 'NotImplementedError()', ]) <NEW_LINE> def test_raise_not_implemented_error( assert_err...
Testing that `raise NotImplementedError` is allowed.
625941cf236d856c2ad4492c
def iter_available_types(self, name, bp_args, bp_kwargs): <NEW_LINE> <INDENT> if name not in self._reg: <NEW_LINE> <INDENT> return iter([]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for prim in self._reg[name].values(): <NEW_LINE> <INDENT> if prim.gradable(bp_args, bp_kwargs): <NEW_LINE> <INDENT...
Find primitives of the given name that have gradients defined for the arguments. Parameters ---------- name : str Primitive name. bp_args : tuple Positional arguments that need back propagation. bp_kwargs : tuple Keyword arguments that need back propagation. Returns ------- Primitives that satisfy the req...
625941cf187af65679ca5270
def result(self): <NEW_LINE> <INDENT> for value in self.__result.itervalues(): <NEW_LINE> <INDENT> value.sort(key = _humanSortKey) <NEW_LINE> <DEDENT> return self.__result
Formats the result.
625941cf30dc7b7665901ab7
def AddCustomPersonImage(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("AddCustomPersonImage", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.AddCustomPersonImag...
增加自定义人脸图片,每个自定义人物最多可包含10张人脸图片 请注意,与创建自定义人物一样,图片数据优先级优于图片URL优先级 :param request: Request instance for AddCustomPersonImage. :type request: :class:`tencentcloud.ivld.v20210903.models.AddCustomPersonImageRequest` :rtype: :class:`tencentcloud.ivld.v20210903.models.AddCustomPersonImageResponse`
625941cf73bcbd0ca4b2c1c7
def test_fit_notallzeros(lfrfitmodel): <NEW_LINE> <INDENT> expected = False <NEW_LINE> all_zeros = not np.any(lfrfitmodel) <NEW_LINE> print("allzeros:" + str(all_zeros)) <NEW_LINE> assert all_zeros == expected
Should not be all zeros.
625941cfd164cc6175782e9f
@app.route("/update/<building>") <NEW_LINE> def update(building): <NEW_LINE> <INDENT> logger.info("更新" + building + "数据") <NEW_LINE> fc = factory(db) <NEW_LINE> controller = fc.getController(building) <NEW_LINE> return controller.update()
测试用 :param building: 宿舍楼 :return: 更新成功与否
625941cf57b8e32f524835ec
def __rmul__(self, other): <NEW_LINE> <INDENT> return multiply(other, self)
Multiply other by self, and return a new masked array.
625941cf63f4b57ef000126a
def url2pathname(url): <NEW_LINE> <INDENT> from . import urllib_red as urllib <NEW_LINE> if not '|' in url: <NEW_LINE> <INDENT> if url[:4] == '////': <NEW_LINE> <INDENT> url = url[2:] <NEW_LINE> <DEDENT> components = url.split('/') <NEW_LINE> return urllib.parse.unquote('\\'.join(components)) <NEW_LINE> <DEDENT> comp =...
Convert a URL to a DOS path. ///C|/foo/bar/spam.foo becomes C:\foo\bar\spam.foo
625941cfa4f1c619b28b0189
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.00015, num_epochs = 25000, minibatch_size = 2041, print_cost = True): <NEW_LINE> <INDENT> ops.reset_default_graph() <NEW_LINE> (n_x, m) = X_train.shape <NEW_LINE> n_y = Y_train.shape[0] <NEW_LINE> costs = [] <NEW_LINE> learning_rate_origin = learning_rate <N...
Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX. Arguments: X_train -- training set, of shape (input size = 17, number of training examples = 2113) Y_train -- test set, of shape (output size = 5, number of training examples = 2113) X_test -- training set, of shape (input...
625941cf7b25080760e395aa
def handle(self, *args, **options): <NEW_LINE> <INDENT> sample_object = User.objects.create(id=id, real_name=real_name, tz=tz) <NEW_LINE> sample_object.activity_periods.set(ap)
:param args: arguments. :param options: options if necessary :return: creates user objects
625941cf956e5f7376d70fbe