query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Generates mapping from water measurements column names to values of the given CSV row.
def get_water_value_map(row, column_names_map): column_values_map = column_names_map.copy() row_length = len(row) empty = True for key, index in column_names_map.items(): # Check if non-empty value exist for given index. if -1 < index < row_length: value = row[index].strip() if value: column_values_map[key] = value empty = False continue # Else NULL is inserted in db. column_values_map[key] = 'NULL' return None if empty else column_values_map
[ "def create_deft_table_csv_mappings():\n mappings = list()\n mappings.append(CsvColumnMapping(columnName=\"rownumber\", cslDataType=\"int\", ordinal=0))\n mappings.append(CsvColumnMapping(columnName=\"rowguid\", cslDataType=\"string\", ordinal=1))\n mappings.append(CsvColumnMapping(colum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate water measurements table for selected `archive`, `directory` and `stations`.
def populate_water_measurements(cursor, archive, directory, station): csv_path = get_data_path( 'water', 'raw', archive, directory, f'{station}.csv' ) with open(csv_path, 'r', encoding='utf-8') as file: reader = csv.reader(file, delimiter=';') header = next(reader) column_names_map = get_water_index_map(archive, header) if not column_names_map: return False water_body = get_water_definitions(archive)['body'] for row in reader: column_values_map = get_water_value_map(row, column_names_map) if column_values_map: date = datetime.strptime(row[0], '%d.%m.%Y').date() data_columns = ', '.join(column_values_map.keys()) data_values = ', '.join(column_values_map.values()) cursor.execute(f'''INSERT INTO {water_body}_measurements (station_id, date, {data_columns}) VALUES ({station}, '{str(date)}', {data_values})''') return True
[ "def populate_water_tables(connection):\n metadata = load_metadata('water')\n cursor = connection.cursor()\n\n # Check if tables are already populated.\n cursor.execute('SELECT count(*) FROM watercourses')\n watercourse_count = cursor.fetchone()[0]\n cursor.execute('SELECT count(*) FROM aquifers')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate watercourse and aquifer related data tables.
def populate_water_tables(connection): metadata = load_metadata('water') cursor = connection.cursor() # Check if tables are already populated. cursor.execute('SELECT count(*) FROM watercourses') watercourse_count = cursor.fetchone()[0] cursor.execute('SELECT count(*) FROM aquifers') aquifer_count = cursor.fetchone()[0] if watercourse_count and aquifer_count: print('Water tables already populated!') return station_data = get_station_data() for archive in metadata.keys(): print(f'{archive}-water:'.upper()) water_body = get_water_definitions(archive)['body'] # 1. Populate watercourses/aquifers: stations = {} for water_body_name in metadata[archive].keys(): print(f'\tPopulating {water_body}: "{water_body_name}"') cursor.execute(f'''INSERT INTO {water_body}s(location_id, name) VALUES (0, '{water_body_name}')''') water_body_id = cursor.lastrowid # 2. Populate watercourse_stations/aquifer_stations: for station_id in metadata[archive][water_body_name]['stations']: station_name = clean_name(metadata[archive][water_body_name]['stations'][station_id]['name']) if station_id in stations: # Prefer watercourses/aquifer with more stations current_len = len(metadata[archive][water_body_name]['stations']) previous_len = len(metadata[archive][stations[station_id]]['stations']) if current_len < previous_len: print(f'\t\tStation already exists: {station_id} - "{station_name}" ("{water_body_name}")') continue else: cursor.execute(f'''DELETE FROM {water_body}_stations WHERE id = {station_id}''') print(f'\t\tRemoved station: {station_id} - "{station_name}" from "{stations[station_id]}")') stations[station_id] = water_body_name print(f'\t\tPopulating station: {station_id} - "{station_name}"') # Insert station location if station data exists. location_id = 0 station_row = station_data.query(f'ŠIFRA == "{station_id}"') if not station_row.empty: index = station_row.index[0] lat = station_row.at[index, 'LAT'] lng = station_row.at[index, 'LON'] if not np.isnan(lat) and not np.isnan(lng): name = f"{station_row.at[index, 'VODOMERNA POSTAJA']} ({station_row.at[index, 'VODOTOK']})" cursor.execute(f'''INSERT INTO locations(name, lat, lng) VALUES ('{name}', {lat}, {lng})''') location_id = cursor.lastrowid # Insert station. cursor.execute(f'''INSERT INTO {water_body}_stations(id, {water_body}_id, location_id, name) VALUES ({station_id}, {water_body_id}, {location_id}, '{station_name}')''') # 3. Populate watercourse_measurements/aquifer_measurements: if not populate_water_measurements(cursor, archive, metadata[archive][water_body_name]['dir'], station_id): cursor.execute(f'''DELETE FROM {water_body}_stations WHERE id = {station_id}''') print(f'\t\tRemoved station with useless data: {station_id} - "{station_name}"') # Remove empty watercourses/aquifers. cursor.execute(f'''SELECT w.id, w.name FROM {water_body}s w WHERE NOT EXISTS ( SELECT s.id FROM {water_body}_stations s WHERE w.id = s.{water_body}_id )''') for row in cursor.fetchall(): cursor.execute(f'''DELETE FROM {water_body}s WHERE id = {row[0]}''') print(f'\tRemoved empty {water_body}: "{row[1]}"')
[ "def populate_database(self):\n self.insert_products()\n self.insert_categories()\n self.insert_products_categories()\n self.insert_stores()\n self.insert_products_stores()", "def populate_db():\n stdout.write('Emptying the tables...\\n')\n empty_tables()\n stdout.write...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate locations data table.
def populate_locations(connection): print('Populating locations...') cursor = connection.cursor() with open(get_data_path('locations', 'locations.json'), 'r', encoding='utf-8') as json_file: locations = json.load(json_file) for station_id, location in locations.items(): cursor.execute(f'''SELECT id FROM watercourse_stations WHERE id = {station_id}''') if len(cursor.fetchall()): cursor.execute(f'''INSERT INTO locations(name, lat, lng) VALUES ('{location['name']}', {location['lat']}, {location['lng']})''') cursor.execute(f'''UPDATE watercourse_stations SET location_id = {cursor.lastrowid} WHERE id = {station_id}''')
[ "def __createData(self):\n self.locations = []\n\n # open whitespace-delimited file from url and read lines from it:\n data = pd.read_csv('cities.csv')\n path_first = pd.read_csv('sample_submission.csv')\n first_path = [id for id in path_first[\"Path\"]]\n index_cities = [c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if given forecast dictionary contains a numeric value with provided key.
def is_forecast_number(key, forecast): return key in forecast and type(forecast[key]) in [float, int]
[ "def missing_value_detector(mvd_key, mvd_dict):\n\tif mvd_dict.get(mvd_key):\n\t\treturn 0\n\telse:\n\t\treturn 1", "def moreThanOne(dict, key):\n\treturn key in dict and dict[key] > 0", "def checkandConvertToFloat(dictionary: Dict, key: str) -> float:\n convertedValue = 0.0\n try:\n if key in dict...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate weather data tables.
def populate_weather(connection): metadata = load_metadata('weather') cursor = connection.cursor() water_defs = get_water_definitions() # Check if tables are already populated. cursor.execute('SELECT count(*) FROM weather') weather_count = cursor.fetchone()[0] if weather_count: print('Weather tables already populated!') return print('WEATHER:') # Darksky data for dir_name, location in metadata.items(): print(f'\tPopulating weather: "{location["name"]}".') # Insert location. cursor.execute(f'''INSERT INTO locations(name, lat, lng) VALUES ('{location['name']}', {location['lat']}, {location['lng']})''') location_id = cursor.lastrowid # Set weather locations for watercourses/aquifers. for water_body in [d['body'] for d in water_defs.values()]: if water_body in location: cursor.execute(f'''UPDATE {water_body}s SET location_id = {location_id} WHERE name IN ('{"','".join(location[water_body])}')''') break dir_path = get_data_path('weather', 'raw', dir_name) for json_file_name in os.listdir(dir_path): json_path = os.path.join(dir_path, json_file_name) with open(json_path, 'r', encoding='utf-8') as json_file: print(f'\t\tPopulating year: {json_file_name[0:-5]}') year_forecasts = json.load(json_file) for date, date_forecast in year_forecasts.items(): hourly_forecasts = date_forecast['hourly'] if not hourly_forecasts: print(f'\t\tNo hourly forecasts for {date}!') continue daily_forecast = { 'location_id': location_id, 'time': date_forecast['time'], 'day_time': date_forecast['sunset_time'] - date_forecast['sunrise_time'], 'precipitation': 0, 'snow_accumulation': 0 } # List of value names with `avg`, `min` and `max` values value_names = { 'temperature': 'temperature', 'cloud_cover': 'cloudCover', 'dew_point': 'dewPoint', 'humidity': 'humidity', 'pressure': 'pressure', 'uv_index': 'uvIndex', 'precipitation_probability': 'precipProbability', 'precipitation_intensity': 'precipIntensity' } # Value name counters, which indicate how many times (out of 24) # certain value appears in hourly data. value_counts = {k: 0 for k in value_names.keys()} for value_name in value_names.keys(): daily_forecast[f'{value_name}_avg'] = 0.0 daily_forecast[f'{value_name}_min'] = float('inf') daily_forecast[f'{value_name}_max'] = float('-inf') # Calculate daily forecast values from hourly forecasts. for hourly_forecast in hourly_forecasts: for value_name in value_names.keys(): orig_value_name = value_names[value_name] if is_forecast_number(orig_value_name, hourly_forecast): daily_forecast[f'{value_name}_avg'] += hourly_forecast[orig_value_name] daily_forecast[f'{value_name}_min'] = min( hourly_forecast[orig_value_name], daily_forecast[f'{value_name}_min'] ) daily_forecast[f'{value_name}_max'] = max( hourly_forecast[orig_value_name], daily_forecast[f'{value_name}_max'] ) value_counts[value_name] += 1 if is_forecast_number('precipAccumulation', hourly_forecast) \ and hourly_forecast['precipType'] == 'snow': daily_forecast['snow_accumulation'] += hourly_forecast['precipAccumulation'] elif is_forecast_number('precipIntensity', hourly_forecast) \ and is_forecast_number('precipProbability', hourly_forecast): daily_forecast['precipitation'] += \ hourly_forecast['precipIntensity'] * hourly_forecast['precipProbability'] for value_name, value_count in value_counts.items(): if value_count: # Calculate average. daily_forecast[f'{value_name}_avg'] = daily_forecast[f'{value_name}_avg'] / value_count else: # If value never appeared daily_forecast[f'{value_name}_avg'] = 'NULL' daily_forecast[f'{value_name}_min'] = 'NULL' daily_forecast[f'{value_name}_max'] = 'NULL' cursor.execute(f'''INSERT INTO weather({', '.join(daily_forecast.keys())}) VALUES ({', '.join([str(v) for v in daily_forecast.values()])})''') # IOT data: for location in SETTINGS['weather_locations_iot']: print(f'\tPopulating weather: "{location["name"]}".') # Insert location. cursor.execute(f'''INSERT INTO locations(name, lat, lng) VALUES ('{location['name']}', {location['lat']}, {location['lng']})''') location_id = cursor.lastrowid # Set weather locations for watercourses/aquifers. for water_body in [d['body'] for d in water_defs.values()]: if water_body in location: cursor.execute(f'''UPDATE {water_body}s SET location_id = {location_id} WHERE name IN ('{"', '".join(location[water_body])}')''') # Set locations for all stations on given water body to match its location. cursor.execute(f'''SELECT id FROM {water_body}s WHERE location_id = {location_id}''') ids = [row[0] for row in cursor.fetchall()] if len(ids): cursor.execute(f'''UPDATE {water_body}_stations SET location_id = {location_id} WHERE {water_body}_id IN ({', '.join([str(v) for v in ids])})''') break file_name = f'''{location['lat']}-{location['lng']}.json''' json_path = get_data_path('weather', 'raw', file_name) # If data file doesn't exist, download it first. if not os.path.isfile(json_path): with open(json_path, 'wb', encoding="utf-8") as file: file.write(read_from_url(location['url'], decode=False)) with open(json_path, 'r', encoding='utf-8') as json_file: row_names = { "Sun_duration": "sun_duration", "CloudCover": "cloud_cover_avg", "Percipitation": "precipitation", "New_snow_blanket": "snow_accumulation", "Snow_blanket": "snow_depth", "TemperatureAvg": "temperature_avg", "TemperatureMin": "temperature_min", "TemperatureMax": "temperature_max" } forecasts = json.load(json_file) for forecast in forecasts: f = {row_names[k]: forecast[k] for k in row_names.keys()} f['location_id'] = location_id f['time'] = round(forecast['LastUpdatedEpoch'] / 1000) cursor.execute(f'''INSERT INTO weather({', '.join(f.keys())}) VALUES ({', '.join([str(v) for v in f.values()])})''')
[ "def populate_water_tables(connection):\n metadata = load_metadata('water')\n cursor = connection.cursor()\n\n # Check if tables are already populated.\n cursor.execute('SELECT count(*) FROM watercourses')\n watercourse_count = cursor.fetchone()[0]\n cursor.execute('SELECT count(*) FROM aquifers')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to construct multidimensional dictionaries e.g myhash = _makehash() myhash[1][2] = 4 myhash[2][5][8] = 17
def _makehash(): return defaultdict(_makehash)
[ "def hashMap(self,arr):\r\n n = len(arr)\r\n dict1 = {}\r\n i = 1\r\n for i in range(n): \r\n if(i > 0): \r\n key=arr[i]\r\n value=arr[0]\r\n dict1[key] = value\r\n return dict1", "def _make_hash(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert headers of fetched tickers to same format for convenient data storage in Database. This method assumes that parser's headers are configured properly(headers_dict), if one of the headers is missing in config file exception raised
def convert_headers(self, tickers): result = _makehash() for pair_name, fetched_values_dict in list(tickers.items()): for header, value in list(fetched_values_dict.items()): result[pair_name][self.config['headers'][header]] = value return result
[ "def _parse_headers(headers):\n\n headers_new = []\n # reformat column headers if needed\n for j, hd in enumerate(headers):\n # rename so always have T1/2 (s)\n if hd == \"T1/2 (num)\" or hd == \"T1/2 (seconds)\":\n hd = \"T1/2 (s)\"\n # for uncertainties, add previous colum...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the similarity based on Cosine Similarity between two CTRDMs
def cosinesimilarity_cal(CTRDM1, CTRDM2): # get number of conditions n_cons = np.shape(CTRDM1)[0] # calculate the number of value above the diagonal in RDM n = n_cons * (n_cons - 1) # initialize two vectors to store the values above the diagnal of two RDMs v1 = np.zeros([n], dtype=np.float64) v2 = np.zeros([n], dtype=np.float64) # assignment nn = 0 for i in range(n_cons): for j in range(n_cons): if i != j: v1[nn] = CTRDM1[i, j] v2[nn] = CTRDM2[i, j] nn = nn + 1 # calculate the Cosine Similarity V1 = np.mat(v1) V2 = np.mat(v2) num = float(V1 * V2.T) denom = np.linalg.norm(V1) * np.linalg.norm(V2) cos = num / denom similarity = 0.5 + 0.5 * cos return similarity
[ "def _compute_cosine_similarity(d1: np.ndarray, d2: np.ndarray) -> float:\n assert d1.shape == d2.shape\n\n # To avoid dividing by zero. This edge case occurs when both vectors share\n # no common elements\n if (np.linalg.norm(d1) * np.linalg.norm(d2)) == 0:\n return 0\n\n # Computing cosine s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds basic_vector to the basic vectors. If there are at least 3 arrays in _basic_vectors, then add a new array to _featureVector. This added array is composed of the basic vectors and its 2 first central derivatives basic_vector must be the array returned by the mfcc.
def build_feature_vector(self, basic_vector): basic_vector = basic_vector - np.mean(basic_vector) self._basic_vectors.append(basic_vector) if len(self._basic_vectors) > 2: #if there are at least 3 basic vectors we can calculate the central derivative for the vector before this one first_derivative = (basic_vector - self._basic_vectors[-3])/(2*self.seconds_to_next_vector) second_derivative = (basic_vector - 2*self._basic_vectors[-2] + self._basic_vectors[-3])/(self.seconds_to_next_vector**2) feature_vector = np.concatenate((basic_vector, first_derivative, second_derivative)) self._feature_vectors.append(feature_vector)
[ "def feature_vector(features, vector):\n clean_features = set(features)\n new_features_vector = featurize(vector,clean_features)\n return new_features_vector", "def _add_support_vectors(self, x: np.ndarray, y: np.ndarray) -> None:\n\n n_vectors = x.shape[0]\n\n self.support_vectors = np.vst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If there is at least an feature vector then returns it, else returns None
def get_last_feature_vectors(self): if len(self._feature_vectors): return self._feature_vectors[-1] return None
[ "def get_feature_vector(name):\n pass", "def test_get_feature(self):\n # Checking context features\n feature_tensor = self.parser.get_feature(\n self.feature_config.get_feature(\"query_text\"),\n extracted_features=({\"query_text\": tf.zeros((3, 4, 6))}, {}),\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function used for marking deducted Late checkin request.
def action_payslip_done(self): for recd in self.late_check_in_ids: recd.state = 'deducted' return super(PayslipLateCheckIn, self).action_payslip_done()
[ "def checkin(self):\n folio = self.folio_id\n if folio.payment_deposits <= 0:\n raise UserError(_(\"\"\"No record of security deposit found on folio {}\n \"\"\".format(folio.name)))\n if folio.state != 'on_queue':\n raise UserError(_(\n 'Folio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decode next layer protocol.
def _decode_next_layer(self, *args, **kwargs): # pylint: disable=signature-differs raise UnsupportedCall(f"'{self.__class__.__name__}' object has no attribute '_decode_next_layer'")
[ "def _decode_next_layer(self, dict_, length=None):\n # make next layer protocol name\n proto = str(self._prot or 'Raw').lower()\n\n # make BytesIO from frame package data\n bytes_ = io.BytesIO(self._file.read(dict_['len']))\n info, protochain = self._import_next_layer(bytes_, leng...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import next layer extractor.
def _import_next_layer(self, *args, **kwargs): # pylint: disable=signature-differs raise UnsupportedCall(f"'{self.__class__.__name__}' object has no attribute '_import_next_layer'")
[ "def _next_layer(self, layer):\n return self.layers[layer + 1]", "def _import_next_layer(self, file_, length):\n if self._prot == 'Ethernet':\n from .link import Ethernet as Protocol\n elif self._prot == 'IPv4':\n from .internet import IPv4 as Protocol\n elif self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build QA data dict from the nights
def build_data(self): from desiutil.io import combine_dicts # Loop on exposures odict = {} for qanight in self.qa_nights: for qaexp in qanight.qa_exps: # Get the exposure dict idict = write_qa_exposure('foo', qaexp, ret_dict=True) odict = combine_dicts(odict, idict) # Finish self.data = odict
[ "def champion_features():\n\n rv = {}\n with open('../data/all_weeks.csv') as handle:\n reader = csv.DictReader(handle, ['Week', 'Name', 'Difficulty', 'Since', 'Times', 'RiotMeta'])\n\n for line in reader:\n name = line['Name']\n difficulty = line['Difficulty']\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for add_or_update_case
def test_add_or_update_case(self): pass
[ "def test_update_case(self):\n pass", "def test_update_record(self):\n pass", "def test_update(self):\n pass", "def test_update_entry(self):\n pass", "def test_update_scenario(self):\n pass", "def test_add_or_update_state_for_state_in_storage(self):\n def test_upd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for delete_case
def test_delete_case(self): pass
[ "def test_cases_delete(self):\n pass", "def test_delete_run(self):\n pass", "def test_unit_delete(self):\n pass", "def test_delete(self):\n pass", "def test_delete1(self):\n pass", "def test_delete_record(self):\n pass", "def test_delete7(self):\n pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_case_by_id
def test_get_case_by_id(self): pass
[ "def test_filter_by_case_id(self):\r\n one = self.factory.create(name=\"Foo 1\")\r\n rs = self.F.RunSuiteFactory.create(run=one)\r\n sc = self.F.SuiteCaseFactory.create(suite=rs.suite)\r\n self.factory.create(name=\"Foo 2\")\r\n\r\n res = self.get(params={\"filter-case\": str(sc.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_cases_for_dict
def test_get_cases_for_dict(self): pass
[ "def test_map(self):\n\n test_cases = [\n Case(\n description=\"lists of objects\",\n val=[{\"title\": \"foo\"}, {\"title\": \"bar\"}, {\"title\": \"baz\"}],\n args=[\"title\"],\n kwargs={},\n expect=[\"foo\", \"bar\", \"ba...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_sync_history
def test_get_sync_history(self): pass
[ "def test_tracker_getHistory():\n\n trackers, cap = init_tracker()\n tr = trackers[0]\n tr.addHistory([1, 1, 1, 1])\n\n assert tr.getHistory()[1] == [1, 1, 1, 1]", "def test_add_history(self):\n pass", "def test_update_task_runner_history(self):\n pass", "def test_get_team_history(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for update_case
def test_update_case(self): pass
[ "def test_cases_update(self):\n pass", "def test_update_scenario(self):\n pass", "def test_update(self):\n pass", "def test_add_or_update_case(self):\n pass", "def test_update_record(self):\n pass", "def test_update(self):\n # this is tested graphically, as it is ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unset key from the encryptor and decryptor
def unset_cipher(self, key_name=None): if key_name is None: if self.key_name is not None: message_key_types.unset_cipher(self.key_name) if self.pending_key_name is not None: message_key_types.unset_cipher(self.pending_key_name) else: message_key_types.unset_cipher(key_name)
[ "def CryptDestroyKey(self):\n\n return self.__del__()", "def clear_key(self, key):\r\n return self.handler.clear_key(key_to_code(key))", "def stop_crypto(self):\n self.clear_bitmask(0x08, 0x08)\n self.authed = False", "def test_decrypt_key(self):\n key = b'0' * 32\n\n enc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set timer for key revocation
def _set_delete_timer(self, key_name, timeout): if key_name is not None: #print("(%d) _set_delete_timer:" % int(time.time()), key_name.hex()[:10], timeout) query_management.QueryEntry(expire_after=timeout, callback_expire=remove_old_key, data={KeyType.hint: key_name}, retry_count=0)
[ "def __updateElapsedTime(self):\n if self._keyCodeTime != 0.0 and \\\n (globalClock.getFrameTime() - self._keyCodeTime) >= self._timeout:\n self.notify.debug(\"Key code timed out. Resetting...\")\n self.reset()\n messenger.send(KeyCodes.CLEAR_CODE_E...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the presence for this channel
def presence(self, params=None, timeout=None): params = params or {} path = '/channels/%s/presence' % self.__name return self.__ably._get(path, params=params, timeout=timeout).json()
[ "def presence(self):\n return self.slack_client.api_call(\"users.getPresence?user=\"+self.user_id)", "def presence(self, *args, **kwargs):\n return self.send(xmpp.Presence(*args, **kwargs))", "def get_presence(self):\n present_path = \"{}{}{}\".format(CPLD_I2C_PATH, 'present_', self.fan_ind...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing Assessment resource's state with the given name, id, and optional extra properties used to qualify the lookup.
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Assessment': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = AssessmentArgs.__new__(AssessmentArgs) __props__.__dict__["additional_data"] = None __props__.__dict__["display_name"] = None __props__.__dict__["links"] = None __props__.__dict__["metadata"] = None __props__.__dict__["name"] = None __props__.__dict__["partners_data"] = None __props__.__dict__["resource_details"] = None __props__.__dict__["status"] = None __props__.__dict__["type"] = None return Assessment(resource_name, opts=opts, __props__=__props__)
[ "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None) -> 'Assessment':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = dict()\n\n __props__[\"additional_data\"] = None\n __pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Links relevant to the assessment
def links(self) -> pulumi.Output['outputs.AssessmentLinksResponse']: return pulumi.get(self, "links")
[ "def links(self) -> 'outputs.AssessmentLinksResponse':\n return pulumi.get(self, \"links\")", "def review_links():", "def test_view(self):\n response = self.client.get(reverse('makeReports:assessment-summary',kwargs={'report':self.rpt.pk}))\n self.assertEquals(response.status_code,200)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Details of the resource that was assessed
def resource_details(self) -> pulumi.Output[Any]: return pulumi.get(self, "resource_details")
[ "def resource_details(self) -> Any:\n return pulumi.get(self, \"resource_details\")", "def resource(self):\n return self.__resource", "def Description(self):\n return self.Resource.Description", "def resource(self):\n return self._resource", "def __str__(self):\n return self._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test get_type_for_key_path with Simple Key Path
def test_get_type_for_key_path_simple_path(test_schema): assert get_type_for_key_path(test_schema, "Age") == "integer"
[ "def test_get_type_for_key_path_multi_level(test_schema):\n assert (\n get_type_for_key_path(test_schema, \"EmploymentInformation.Beneficiary.Name\")\n == \"string\"\n )", "def test_get_type_for_key_path_invalid_key_path(test_schema):\n assert get_type_for_key_path(test_schema, \"foo.bar\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test get_type_for_key_path with key path of one level deep
def test_get_type_for_key_path_depth_one_level(test_schema): assert ( get_type_for_key_path(test_schema, "EmploymentInformation.OriginalHireDate") == "string" )
[ "def test_get_type_for_key_path_multi_level(test_schema):\n assert (\n get_type_for_key_path(test_schema, \"EmploymentInformation.Beneficiary.Name\")\n == \"string\"\n )", "def test_get_type_for_key_path_simple_path(test_schema):\n assert get_type_for_key_path(test_schema, \"Age\") == \"int...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test get_type_for_key_path with multi level key path
def test_get_type_for_key_path_multi_level(test_schema): assert ( get_type_for_key_path(test_schema, "EmploymentInformation.Beneficiary.Name") == "string" )
[ "def test_get_type_for_key_path_simple_path(test_schema):\n assert get_type_for_key_path(test_schema, \"Age\") == \"integer\"", "def test_get_type_for_key_path_depth_one_level(test_schema):\n assert (\n get_type_for_key_path(test_schema, \"EmploymentInformation.OriginalHireDate\")\n == \"strin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test get_type_for_key_path with invalid key path
def test_get_type_for_key_path_invalid_key_path(test_schema): assert get_type_for_key_path(test_schema, "foo.bar") == None
[ "def test_get_type_for_key_path_simple_path(test_schema):\n assert get_type_for_key_path(test_schema, \"Age\") == \"integer\"", "def test_get_type_for_key_path_multi_level(test_schema):\n assert (\n get_type_for_key_path(test_schema, \"EmploymentInformation.Beneficiary.Name\")\n == \"string\"\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate and apply formatting on template, apply any art if provided. Any additional parameters are passed as extra variables to the template. The extra variables have priority when there's conflicting variable names.
def run(self, template: str, art: Optional[str] = None, **kwargs: Any) -> str: variables = self.__dict__ variables.update(kwargs) template = CustomFormats().format(template, **variables) if art: art = art.format(nfo=template) template = art for m in re.finditer(r"<\?([01])\?([\D\d]*?)\?>", template): # TODO: This if check is quite yucky, look into alternative options. # Ideally a custom format spec would be great. template = template.replace( m.group(0), m.group(2) if int(m.group(1)) else "" ) template = "\n".join(map(str.rstrip, template.splitlines(keepends=False))) return template
[ "def render( text, options, processed = None ):\n output = unicode(text)\n expr = re.compile( '(\\[+([^\\[\\]]+)\\]\\]?)' )\n results = expr.findall( output )\n curr_date = datetime.datetime.now()\n options_re = re.compile('(\\w+)\\(?([^\\)]+)?\\)?')\n \n if ( processed == No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an IMDB ID from either the media's global tags, or the config. Since IMDB IDs are required for this project, it will bug the user for one interactively if not found.
def get_imdb_id(self, imdb_id: Any) -> str: if not imdb_id: general_track = self.media_info.general_tracks[0].to_data() imdb_id = general_track.get("imdb") if not imdb_id: print("No IMDB ID was provided but is required...") while not imdb_id or not isinstance(imdb_id, str): user_id = input("IMDB ID (e.g., 'tt0487831'): ") if not self.IMDB_ID_T.match(user_id): print(f"The provided IMDB ID {user_id!r} is not valid...") print("Expected e.g., 'tt0487831', 'tt10810424', (include the 'tt').") else: imdb_id = user_id return imdb_id
[ "def alternative_media_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"alternative_media_id\")", "def imdb_id(title):\n pass", "def get_mediatype_id(self, name: str) -> Optional[str]:\n result = self.conn.mediatype.get(filter={'name': name.strip()})\n\n if len(result...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a TMDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid.
def get_tmdb_id(self, tmdb_id: Any) -> Optional[str]: if not tmdb_id: general_track = self.media_info.general_tracks[0].to_data() tmdb_id = general_track.get("tmdb") if not tmdb_id: print("Warning: No TMDB ID was provided...") return None if not self.TMDB_ID_T.match(tmdb_id) or not isinstance(tmdb_id, str): print(f"The provided TMDB ID {tmdb_id!r} is not valid...") print("Expected e.g., 'tv/2490', 'movie/14836', (include the 'tv/' or 'movie/').") raise ValueError("Invalid TMDB ID") return tmdb_id
[ "def get_tvdb_id(self, tvdb_id: Any) -> Optional[int]:\n if not tvdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tvdb_id = general_track.get(\"tvdb\")\n if not tvdb_id:\n print(\"Warning: No TVDB ID was provided...\")\n return None\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a TVDB ID from either the media's global tags, or the config. It will raise a ValueError if the provided ID is invalid.
def get_tvdb_id(self, tvdb_id: Any) -> Optional[int]: if not tvdb_id: general_track = self.media_info.general_tracks[0].to_data() tvdb_id = general_track.get("tvdb") if not tvdb_id: print("Warning: No TVDB ID was provided...") return None if isinstance(tvdb_id, int): tvdb_id = str(tvdb_id) if not self.TVDB_ID_T.match(tvdb_id) or not isinstance(tvdb_id, str): print(f"The provided TVDB ID {tvdb_id!r} is not valid...") print("Expected e.g., '79216', '1395', (not the url slug e.g., 'the-office-us').") raise ValueError("Invalid TVDB ID") return int(tvdb_id)
[ "def get_tmdb_id(self, tmdb_id: Any) -> Optional[str]:\n if not tmdb_id:\n general_track = self.media_info.general_tracks[0].to_data()\n tmdb_id = general_track.get(\"tmdb\")\n if not tmdb_id:\n print(\"Warning: No TMDB ID was provided...\")\n return None\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scrape Title Name and Year (including e.g. 2019) from IMDB
def get_title_name_year(self) -> Tuple[str, str]: r = self.session.get(f"https://www.imdb.com/title/{self.imdb}") if r.status_code != 200: raise ValueError(f"An unexpected error occurred getting IMDB Title Page [{r.status_code}]") imdb_page = html.unescape(r.text) imdb_title = re.search( # testing ground: https://regex101.com/r/bEoEDn/1 r"<title>(?P<name>.+) \(((?P<type>TV (Movie|Series|Mini[- ]Series|Short|Episode) |Video |Short |)" r"(?P<year>(\d{4})(|– |–\d{4})))\) - IMDb</title>", imdb_page ) if not imdb_title: raise ValueError(f"Could not scrape Movie Title or Year for {self.imdb}...") return imdb_title.group("name").strip(), imdb_title.group("year").strip()
[ "def scrape_movie_page(dom):\n # to save the information\n info = []\n\n # find the information block needed\n header = dom.find(\"div\", \"title_wrapper\")\n\n # find the title and strip the string\n name_dom = header.h1.get_text().encode(\"utf-8\")\n name = str(name_dom)[2:-16]\n info.appe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate total episode count based on neighbouring sameextension files.
def get_tv_episodes(self) -> int: return len(glob.glob(os.path.join( os.path.dirname(self.file), f"*{os.path.splitext(self.file)[-1]}" )))
[ "def increase_count_episodes(self):\n return self.sess.run(self.count_episodes_increase)", "def calculate_how_many_episodes_to_play(self):\n episodes_to_play = self.hyperparameters[\"epsilon_decay_rate_denominator\"] / self.grammar_induction_iteration\n episodes_to_play = max(self.min_num_epi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the release name based on the file used during MediaInfo. If a season was specified, but an episode number was not, it presumes the release is a Pack. Hence when pack, it uses the parent folder's name as the release name.
def get_release_name(self) -> str: if self.season is not None and self.episode is None: return os.path.basename(os.path.dirname(self.file)) return os.path.splitext(os.path.basename(self.file))[0]
[ "def extract_season(file_name):\n logging.debug(\"Extracting season from {0}\".format(file_name))\n\n season_part = file_name.split(\".\")[0].split(\"_\")[-1]\n season_out = season_part[:2] + \"/\" + season_part[-2:]\n\n return season_out", "def get_distro_release_name():\n\n release = \"\"\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a wide banner image from fanart.tv. Currently restricts banners to Englishonly.
def get_banner_image(self, tvdb_id: int) -> Optional[str]: if not tvdb_id: return None if not self.fanart_api_key: raise ValueError("Need Fanart.tv api key for TV titles!") r = self.session.get(f"http://webservice.fanart.tv/v3/tv/{tvdb_id}?api_key={self.fanart_api_key}") if r.status_code == 404: return None res = r.json() error = res.get("error message") if error: if error == "Not found": return None raise ValueError(f"An unexpected error occurred while calling Fanart.tv, {res}") banner = next(( x["url"] for x in (res.get("tvbanner") or []) if x["lang"] == sorted(self.audio, key=lambda x: x.streamorder)[0].language ), None) return banner
[ "def render_banner(self, width=300, height=85):\n img_path = IMG_PATH + os.sep + CARD_BANNER\n banner_img = Image.open(img_path)\n banner_img = banner_img.resize((width, height))\n return banner_img", "def banner_img(self, instance):\n if instance.banner:\n url = inst...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of a brief subtitle overview persubtitle. e.g. English, Forced, SubRip (SRT) English, SubRip (SRT) English, SDH, SubRip (SRT) Spanish, Latin American (SDH), SubRip (SRT) The bit of text between the Language and the Subtitle format is the Track Title. It can be of any format, but it is recommended to be used as shown above. It will be returned as a list of strings with the ` ` already prepended to each entry.
def get_subtitle_print(subs: List[Track]) -> List[str]: data = [] if not subs: data.append("--") for sub in subs: line_items = [] # following sub.title tree checks and supports three different language and title scenarios # The second scenario is the recommended option to choose if you are open to choosing any # The third scenario should be used if you have nothing unique to state about the track # | Language | Track Title | Output | # | ------------ | ----------------------------- | --------------------------------------------- | # | es / Spanish | Spanish (Latin American, SDH) | - Spanish (Latin American, SDH), SubRip (SRT) | # | es / Spanish | Latin American (SDH) | - Spanish, Latin American (SDH), SubRip (SRT) | # | es / Spanish | None | - Spanish, SubRip (SRT) | language = pycountry.languages.get(alpha_2=sub.language).name if sub.title: if language.lower() in sub.title.lower(): line_items.append(sub.title) else: line_items.append(f"{language}, {sub.title}") else: line_items.append(language) line_items.append(sub.format.replace("UTF-8", "SubRip (SRT)")) line = "- " + ", ".join(line_items) data += [ (" " + x if i > 0 else x) for i, x in enumerate(textwrap.wrap(line, 64)) ] return data
[ "def video_get_title_description(self):\r\n return track_description_list(libvlc_video_get_title_description(self))", "def get_title(self):\n return [i['title'] for i in self]", "def video_get_chapter_description(self, title):\r\n return track_description_list(libvlc_video_get_chapter_descr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The mins method returns the lower bounds of the action spaces' parameters.
def mins(self) -> Tensor: return self._ranges[:, 0]
[ "def mins(self):\n return self.intervals[:, 0]", "def _rrv_minmax_ ( s ) :\n return s.getMin(),s.getMax()", "def argmin(self) -> int:\n return self.actuator_values.index(self.min)", "def minmin_maxmax( *args ):\n rmin = min( [ mv.min() for mv in args ] )\n rmax = max( [ mv.max() for mv ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The maxs method returns the upper bounds of the action spaces' parameters.
def maxs(self) -> Tensor: return self._ranges[:, 1]
[ "def maxs(self):\n return self._maxs", "def get_parameters_max(self):\n maxValues = numpy.zeros(self.get_num_parameters())\n i = 0\n for p in self.parameters:\n maxValues[i] = p.get_max_value()\n i += 1\n return maxValues", "def get_params_upper_bound():\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The _generate_iterator method creates an iterator which runs over all possible parameter combinations
def _generate_iterator(self) -> Iterable: params: List[Tensor] = [] for angle_range in self._ranges: lin_space: Tensor = linspace(angle_range[0], angle_range[1], steps=self._num_steps) params.append(lin_space) power: int dims: int for i in range(0, self._num_params): power = len(self._ranges) - 1 - i dims = i params[i] = params[i].repeat_interleave(self._num_steps ** power) params[i] = params[i].broadcast_to((self._num_steps ** dims, self._num_steps ** (power + 1))).flatten() return zip(*params)
[ "def __iter__(self):\n yield from generator(*self.args, **self.kwargs)", "def generate_parameter_combinations(params_def):\n param_lists = []\n for param_name, param_def in iter(params_def.items()):\n param_values = generate_values_for_param(param_def)\n param_lists.append([(param_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to rotate one vector to another, inspired by vrrotvec.m in MATLAB
def vrrotvec(a,b): a = normalize(a) b = normalize(b) ax = normalize(np.cross(a,b)) angle = np.arccos(np.minimum(np.dot(a,b),[1])) if not np.any(ax): absa = np.abs(a) mind = np.argmin(absa) c = np.zeros((1,3)) c[mind] = 0 ax = normalize(np.cross(a,c)) r = np.concatenate((ax,angle)) return r
[ "def create_rotvec(vec1, vec2):\n angle = vec_ang(vec1, vec2)\n vec3 = np.cross(vec1, vec2)\n vec3 *= angle / vec_norm(*vec3)\n return vec3", "def rotateVector(rot, v):\r\n print 'rotateVector:', 'heading', rot[1], 'attitude', rot[2], 'bank', rot[0]\r\n print 'input', v\r\n if rot[1]: v = mat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort the buses reversed by their period, having tagged them with their position in the sequence, which is their c value. >>> list(prep_input(EXAMPLE_BUSES)) [(59, 4), (31, 6), (19, 7), (13, 1), (7, 0)]
def prep_input(buses): return sorted([(bus, offset) for offset, bus in enumerate(buses) if bus], reverse=True)
[ "def dmet_bath_orb_sort(t_list, e_before, c_before):\n\n # Sort the orbital energies (Occupation of 1.0 should come first...)\n new_index = np.maximum(-e_before, e_before - 2.0).argsort()\n\n # Throw away some orbitals above threshold\n thresh_orb = np.sum(-np.maximum(-e_before, e_before - 2.0)[new_inde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reduce a bunch of periodic signals to a single signal. The value of x that answers the puzzle is the first place ( c + x ) % T = 0, that is to say, c + x = T, or x = Tc. >>> solve_buses(prep_input(EXAMPLE_BUSES)) 1068781
def solve_buses(prepared_buses): T, c = functools.reduce(combine_signals, prepared_buses) return T - c
[ "def bus_electricities(component_resistances: np.ndarray) -> List[OhmicVars]:\n\n buses: List[OhmicVars] = []\n\n # It might be slightly more efficient to do matrix math instead of using a for loop, but this\n # is more readable :)\n for bus_n in range(0, 4):\n # Calculate 1/resistance for each c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method opening all images to test their validity.
def verify_images(root_dir, root_listdir): counter = 0 for index, image_dir in enumerate(root_listdir): images_listdir = os.listdir(root_dir + "/" + image_dir) list_of_images_indices = [ image_index for image_index in range(3, len(images_listdir) - 1) if image_index % 2 == 0 ] for image_ind in list_of_images_indices: filename = root_dir + "/" + image_dir + "/" + images_listdir[image_ind] try: im = Image.open(filename) im.verify() im.close() except (OSError, ValueError): counter += 1 print("%d files caused error due to OSError and ValueError." % counter)
[ "def _open_images(self):\n filenames, _ = QFileDialog.getOpenFileNames(\n parent=self,\n caption='Select image(s)...',\n directory=self._last_visited_dir, # home dir by default\n )\n self._add_files(filenames)", "def _check_img_inversion(self):\n for i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for a given template and list of extensions, find every file related to that template which has one of the extensions.
def find_template_companion_files(template: Path, extensions: Iterable[str], recurse_up_to: Path = None) -> Set[Path]: files_to_check = [] # Get a list of all file names to look for in each folder data_file_names = [] basename = template.name.split('.')[0] for i in range(len(template.suffixes)): ext = ''.join(template.suffixes[:i+1]) for data_file_ext in extensions: data_file_names.append(Path(basename + ext).with_suffix(data_file_ext)) # Look for those files in the template's current folder (a.k.a. parent directory) files_to_check.extend([template.parent / file_name for file_name in data_file_names]) if recurse_up_to and recurse_up_to in template.parents: # Look for those files in every parent directory up to `recurse_up_to`, # excluding the template's parent directory which has already been checked relative_path = template.parent.relative_to(recurse_up_to) for folder in relative_path.parents: for file in data_file_names: files_to_check.append(recurse_up_to / folder / file) return set([file for file in files_to_check if file.is_file()])
[ "def _get_templates():\n SRC = _ARGS['SRC']\n TEMPLATE = _ARGS['TEMPLATE']\n \n templates = []\n files = list_files(SRC)\n for filename in files:\n name, extension = os.path.splitext(filename)\n if extension == TEMPLATE:\n templates.append(name + extension)\n if len(tem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform x elementwise through an affine function y = exp(s)x + t where s = st[...,0] and t = st[...,1] with s.shape == x.shape == t.shape The Jacobian for this transformation is the coordinatewise product of the scaling factors J = prod(es[...,i],i)
def element_wise_affine(x, st, compute_jacobian=True): es = torch.exp(st[..., 0]) t = st[..., 1] logj = None if compute_jacobian: logj = torch.sum(torch.log(es), dim=-1) return es * x + t, logj
[ "def inverse_element_wise_affine(x, st, compute_jacobian=True):\n es = torch.exp(-st[..., 0])\n t = st[..., 1]\n logj = None\n if compute_jacobian:\n logj = torch.sum(torch.log(es), dim=-1)\n\n return es * (x - t), logj", "def affine_transform(pt, t):\n new_pt = np.array([pt[0], pt[1]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform x elementwise through an affine function y = exp(s)(x t) where s = st[...,0] and t = st[...,1] with s.shape == x.shape == t.shape This is the inverse of `element_wise_affine` above for the same set of parameters st The Jacobian for this transformation is the coordinatewise product of the scaling factors J = prod(es[...,i],i)
def inverse_element_wise_affine(x, st, compute_jacobian=True): es = torch.exp(-st[..., 0]) t = st[..., 1] logj = None if compute_jacobian: logj = torch.sum(torch.log(es), dim=-1) return es * (x - t), logj
[ "def element_wise_affine(x, st, compute_jacobian=True):\n es = torch.exp(st[..., 0])\n t = st[..., 1]\n logj = None\n if compute_jacobian:\n logj = torch.sum(torch.log(es), dim=-1)\n\n return es * x + t, logj", "def transform(fn):\n def _(vec, dt):\n return np.einsum(\n 'ji,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the axis ranges from proviuded Plot or renderer.
def initialize_axis_ranges(self, plot, transform=None): if transform is None: def transform(x): return x elif isinstance(transform, int): ndigits = transform def transform(x): return round(x, ndigits) # Avoid UI polluting with non-sensical digits self.x_axis_range_low = transform(plot.x_axis.mapper.range.low) self.auto_x_axis_range_low = self.x_axis_range_low self.x_axis_range_high = transform(plot.x_axis.mapper.range.high) self.auto_x_axis_range_high = self.x_axis_range_high self.y_axis_range_low = transform(plot.y_axis.mapper.range.low) self.auto_y_axis_range_low = self.y_axis_range_low self.y_axis_range_high = transform(plot.y_axis.mapper.range.high) self.auto_y_axis_range_high = self.y_axis_range_high
[ "def _add_axes_range_sliders(self):\n self.axes_range_sliders = dict()\n\n default_range_x = (self.model.state_variable_range[self.svx][1] -\n self.model.state_variable_range[self.svx][0])\n default_range_y = (self.model.state_variable_range[self.svy][1] -\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an archive from the given tree, upload, and untar it.
def upload_tar_from_git(): require("release", provided_by=[deploy]) tree = prompt("Please enter a branch or SHA1 to deploy", default="master") local("git archive --format=tar %s | gzip > %s.tar.gz" % (tree, env['release'])) sudo("mkdir %(path)s/releases/%(release)s" % env) put("%(release)s.tar.gz" % env, "%(path)s/packages/" % env, use_sudo=True) sudo("cd %(path)s/releases/%(release)s && tar zxf ../../packages/%(release)s.tar.gz" % env) local("rm %(release)s.tar.gz" % env)
[ "def git_archive_and_upload_tar():\n current_branch = str(subprocess.Popen('git branch | grep \"*\" | sed \"s/* //\"', \\\n shell=True,\\\n stdin=subprocess.PIPE, \\\n stdout=subprocess.PIPE).communicate()[0]).rstrip()\n env.git_branch = current_branch\n local('git archive ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Symlink to the new current release.
def symlink_current_release(): require("release", provided_by=[deploy]) with cd("%(path)s/releases" % env): sudo("ln -s %(release)s current_tmp && mv -Tf current_tmp current" % env)
[ "def link(self, newpath):\n os.link(self, newpath)", "def symlink_single_version(version):\r\n default_version = version.project.default_version\r\n log.debug(LOG_TEMPLATE.format(project=version.project.slug, version=default_version, msg=\"Symlinking single_version\"))\r\n\r\n # The single_ver...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove older releases, keeping the last `keep_num` intact.
def cleanup(keep_num=5): keep_num = int(keep_num) assert keep_num > 0, "[ERROR] keep_num must be > 0; refusing to proceed." with cd("%(path)s/packages" % env): package_files = sorted(run("ls -1").split()) package_files = [_.replace(".tar.gz", "") for _ in package_files] with cd("%(path)s/releases" % env): release_files = sorted(run("ls -1").split()) release_files.remove('current') diff = set(package_files).symmetric_difference(set(release_files)) if diff: raise Exception("[ERROR]: Package and release directories are out of sync;" " refusing to proceed. Please fix this difference manually: %s" % diff) package_files = package_files[:-keep_num] release_files = release_files[:-keep_num] with cd("%(path)s/packages" % env): [sudo("rm %s.tar.gz" % _) for _ in package_files] with cd("%(path)s/releases" % env): [sudo("rm -r %s" % _) for _ in release_files]
[ "def delete_older_model_versions(self, model_name, n_versions_to_keep):\n\n def _get_use_time(version):\n use_time = version.get('lastUseTime') or version.get('createTime')\n return time.strptime(use_time, \"%Y-%m-%dT%H:%M:%SZ\")\n\n versions = self.__get_model_versions_with_meta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Give each Node uniform splits of data. Nodes will have same amounts of data.
def uniform_split(self, nr_agents): indices = np.linspace(start=0, stop=self.samples.shape[0], num=nr_agents + 1, dtype=int).tolist() self.samples = self.partition(self.samples, indices, nr_agents) self.labels = self.partition(self.labels, indices, nr_agents)
[ "def _split_node(self, split_ratio: float):\n if (self.num_nodes < len(split_ratio)):\n raise ValueError('in _split_node num of nodes are smaller than'\n 'number of splitted parts')\n\n split_graphs = []\n shuffled_node_indices = torch.randperm(self.num_no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function computes the distribution internal parameters from its two first moments.
def _compute_internals(self, moments): [mean, stdv] = moments internals = {} internals['a'] = mean - np.sqrt(3) * stdv internals['b'] = mean + np.sqrt(3) * stdv return internals
[ "def _compute_internals(self, moments):\n\n [mean, stdv] = moments\n internals = {}\n internals['mu'] = mean\n internals['sigma'] = stdv\n\n return internals", "def _get_distribution_variables(self, R):\n if self.domain == \"Negative\":\n R_typ = self.param.R_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function computes the distribution internal parameters from its two first moments.
def _compute_internals(self, moments): [mean, stdv] = moments internals = {} internals['mu'] = mean internals['sigma'] = stdv return internals
[ "def _compute_internals(self, moments):\n\n [mean, stdv] = moments\n internals = {}\n internals['a'] = mean - np.sqrt(3) * stdv\n internals['b'] = mean + np.sqrt(3) * stdv\n\n return internals", "def _get_distribution_variables(self, R):\n if self.domain == \"Negative\":\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Provides a Step Functions Activity data source Example Usage ```python import pulumi import pulumi_aws as aws sfn_activity = aws.sfn.get_activity(name="myactivity") ```
def get_activity_output(arn: Optional[pulumi.Input[Optional[str]]] = None, name: Optional[pulumi.Input[Optional[str]]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetActivityResult]: ...
[ "def activity2run(user, activity):\n run = Run()\n run.runner = user\n run.strava_id = activity.id\n run.name = activity.name\n run.distance = activity.distance\n run.elapsed_time = activity.elapsed_time.total_seconds()\n run.average_speed = activity.average_speed\n run.average_heartrate = a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the cvxpy variable associated with this layer
def get_cvxpy_variable(self, channel_indx=None): if channel_indx is None: output_channels = cp.hstack( [ self.layer_input[cur_channel_indx] for cur_channel_indx in range(self.n_in_channels) ] ) else: output_channels = self.layer_input[channel_indx] return output_channels
[ "def xvar ( self ) :\n return self.__xvar", "def _get_variable(self, varname):\n\n return NetcdfVariableNetcdf4(self._file.variables[varname])", "def x ( self ) :\n return self.xvar", "def var(self, name):\n return self.get_ground_vector('Var:{}-Var'.format(name))", "def var(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns number of output channels
def get_n_channels(self): return self.n_out_channels
[ "def nb_channels(self):", "def get_num_channels():\r\n check_mixer()\r\n return sdl.Mix_GroupCount(-1)", "def num_of_channels(self) -> int:\n return len(self.non_zero_channels())", "def num_layers(self):\n return len(self.out_channels)", "def GetNumChannels(self):\n # Return the n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a BiRealNet18 model.
def birealnet18(pretrained=False, **kwargs): model = BiRealNet(BasicBlock, [4, 4, 4, 4], **kwargs) return model
[ "def resnet18():\n model = ResNet18(BasicBlock, [2, 2, 2, 2])\n #if pretrained:\n #model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))\n return model", "def birealnet34(pretrained=False, **kwargs):\n model = BiRealNet(BasicBlock, [6, 8, 12, 6], **kwargs)\n return model", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a BiRealNet34 model.
def birealnet34(pretrained=False, **kwargs): model = BiRealNet(BasicBlock, [6, 8, 12, 6], **kwargs) return model
[ "def birealnet18(pretrained=False, **kwargs):\n model = BiRealNet(BasicBlock, [4, 4, 4, 4], **kwargs)\n return model", "def resnet34(pretrained=False, **kwargs):\n model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears the peak_to_peer info which can get quite large.
async def clear_sync_info(self) -> None: self.peak_to_peer = orderedDict()
[ "def reset():\n Peaks.offsets = set()\n Peaks.offsetdone = False", "def clear(self):\n self._fingerprint = 0", "def deleteRemainingPeaks(self):\n \n for existingPeak in self.existingPeaks:\n applData = existingPeak.findFirstApplicationData(application = self.format, keyword = peakN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a hex string from the venue names to use as a unique id. Only the last 8 characters are used for the unique id.
def make_unique_id(venue_list): md5_hash = md5() for name in venue_list: md5_hash.update(name) hash_hex = md5_hash.hexdigest() return hash_hex[-8:]
[ "def create_id(name):\n if _IDENTIFIER.match(name):\n return str(name).lower()\n return hexlify(name.encode('utf-8')).decode()", "def getuuid(data):\n if type(data) != bytes:\n data = data.encode('utf-8')\n h = hashlib.sha256(data).hexdigest()[:32].upper()\n for i, pos in enumerate([8...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raises a ValueError if matrix `value` is not square.
def assert_square(name: str, value: np.ndarray) -> None: if not len(value.shape) == 2 or value.shape[0] != value.shape[1]: raise ValueError(f"{name} must be a square")
[ "def _check_square(matrix):\n if matrix.ndim != 2 or (matrix.shape[0] != matrix.shape[-1]):\n raise ValueError(\n f\"Expected a square matrix, got array of shape {matrix.shape}.\"\n )", "def test_change_basis_raises_not_square(self, fun):\n A = np.random.rand(4, 6)\n with...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the Shannon entropy for probabilities `ps` with `base`.
def shannon_entropy(ps: np.ndarray, base: int = 2) -> float: return -np.sum(ps * np.log(ps) / np.log(base))
[ "def calculate_normalized_entropy(probabilities: list, base: float) -> float:\n entropy = calculate_entropy(probabilities)\n logarithm_base = np.log(base)\n normalized_entropy = entropy / logarithm_base\n\n return normalized_entropy", "def pssm_entropy_per_base( self ):\n return sum(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simply tests if `img` has 3 channels.
def is_rgb(img: np.ndarray) -> bool: return len(img.shape) >= 1 and img.shape[-1] == 3
[ "def is_rgb(im):\n return len(im.shape) == 3", "def is_rgb(im):\n if(im.ndim == 3):\n return True\n else:\n return False", "def rgb(self) -> bool:\n return self.image_shape[2] == 3", "def test_make_3channel():\n img_path = (\n Path(__file__).parent\n / 'images'\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an array [..., channels] of RGB values to HSI color values (H in rad). RGB values are assumed to be normalized to (0, 1).
def rgb_to_hsi(image: np.ndarray) -> np.ndarray: if not is_rgb(image): raise ValueError("Input needs to be an array of RGB values") r = image[..., 0] g = image[..., 1] b = image[..., 2] out = np.zeros_like(image) # allequal = (img == img[:, :, 0, np.newaxis]).all(axis=-1) with np.errstate(invalid="ignore"): tmp = (2.0 * r - g - b) / 2.0 / np.sqrt((r - g) ** 2 + (r - b) * (g - b)) # if r==g==b then 0/0 theta = np.arccos(np.clip(tmp, -1.0, +1.0)) out[..., 0] = np.where(b <= g, theta, 2 * np.pi - theta) # H out[..., 2] = np.sum(image, axis=-1) / 3.0 # I out[..., 1] = 1 - np.amin(image, axis=-1) / out[..., 2] # S if r==g==b==0 then 0/0 np.nan_to_num(out[..., 0:2], copy=False) return out
[ "def hc2hhsi(hc):\n\n import numpy as np\n\n ####################################################################################################################\n # Calculate the components c\n rows = hc.shape[0]\n cols = hc.shape[1]\n dims = hc.shape[2]\n\n c = np.zeros((rows, cols, dims-1))\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an array [..., channels] of RGB values to Digital Y'CbCr (0255). RGB values are assumed to be normalized to (0, 1). Don't forget to cast to uint8 for pillow.
def rgb_to_ycbcr(image: np.ndarray) -> np.ndarray: """ from RGB (0-1). """ if not is_rgb(image): raise ValueError("Input needs to be an array of RGB values") m = np.array( [ [+065.481, +128.553, +024.966], [-037.797, -074.203, +112.000], [+112.000, -093.786, -018.214], ] ) a = np.array([16, 128, 128]) return np.dot(image, m.T) + a
[ "def to_YCrCb(img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)", "def ycbcr2rgb(im):\n xform = np.array([[1, 0, 1.402], [1, -0.34414, -.71414], [1, 1.772, 0]])\n rgb = im.astype(np.float)\n rgb[:, :, [1, 2]] -= 128\n rgb = rgb.dot(xform.T)\n np.putmask(rgb, rgb > 255, 255)\n np.putmask(r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a triangular matrix with random value between 0 and 1 uniformly.
def random_triangular_matrix(size: int, lower: bool = True) -> np.ndarray: a = np.random.uniform(0, 1, (size, size)) if lower: ind = np.triu_indices(5, 1) else: ind = np.tril_indices(5, 1) a[ind] = 0 return a
[ "def triangular_distribution(p1, p2, p3):\n return random.triangular(p1, p2, p3)", "def random_matrix(n):\n return [[random() for j in range(n)] for i in range(n)]", "def uniformRandomRotation():\r\n q, r = np.linalg.qr(np.random.normal(size=(3, 3)))\r\n M = np.dot(q, np.diag(np.sign(np.diag(r))))\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs batched calculation of `v^T A v` transform. Special case of bilinear form `x^T A y`
def batch_vTAv(A: np.ndarray, v: np.ndarray) -> np.ndarray: """ Faster than Av = np.matmul(A, v[...,:,None]) # [B, X, 1] return np.matmul(v[...,None,:], Av).squeeze((-2, -1)) # [B] """ return np.einsum("...k,...kl,...l->...", v, A, v)
[ "def brute_multiply(x, y):\n \n n = x.shape[0]\n res = np.zeros(x.shape)\n \n for i in range(n):\n for j in range(n):\n for k in range(n):\n res[i, j] += x[i, k] * y[k, j]\n \n return res", "def Transform(B, A, T, nullFill = True): \n invT = np.linalg.inv(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs a batched inner product over the last dimension. Replacement for deprecated `from numpy.core.umath_tests import inner1d`.
def batch_inner(a: np.ndarray, b: np.ndarray, verify: bool = True) -> np.ndarray: if verify and a.shape != b.shape: raise ValueError("All dimensions have to be equal") if a.shape[-1] == 0: return np.empty_like(a) return np.einsum("...i,...i->...", a, b) # faster than np.sum(a * b, axis=-1)
[ "def batch_outer_product(a, b):\n a, b = normalize_and_check_ndim([a, b], 2)\n # This is a batchwise version of the matrix multiplication approach\n # used for outer_product(), see explanation there.\n return a[:, :, np.newaxis] * b[:, np.newaxis, :]", "def test_batched_outer_product():\n rng = tl....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`probs` values ndarray `k` take the smallest `k` elements, if `reverse` is False and the largest `k` if `reverse` is True `axis` sorting and selection axis.
def batchtopk( probs: np.ndarray, k: Optional[int] = None, axis: int = -1, reverse: bool = False ) -> Tuple[np.ndarray, np.ndarray]: if k is not None and k <= 0: raise ValueError("k must be larger than 0. Use None to chose all elements.") if axis != -1: raise ValueError("Only last axis supported atm") if len(probs.shape) <= 1: raise ValueError("probs must be at least 2-dimensional") if reverse: sign = -1 else: sign = 1 indices = np.argsort(sign * probs, axis=-1) # use argpartition? probs = np.take_along_axis(probs, indices[..., :k], axis=-1) return indices, probs
[ "def tflite_top_k_probs(probs, k):\n\n if k > 0:\n return np.flip(probs[0].argsort()[-k:])\n else:\n return np.flip(probs[0].argsort())", "def old_topk_sorted_implementation(X, k, axis, largest):\n sorted_indices = numpy.argsort(X, axis=axis)\n sorted_values = numpy.sort(X, axis=axis)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calcuates the sum of the logs of the diagonal elements (batchwise if necessary)
def logtrace(m: np.ndarray) -> np.ndarray: """ note: performance cannot easily be improve by numba. `np.diagonal` not supported by numba 0.52.0 """ return np.sum(np.log(np.diagonal(m, axis1=-2, axis2=-1)), axis=-1)
[ "def trace(X):\r\n return extract_diag(X).sum()", "def batch_trace(x, dim1=-2, dim2=-1):\n return torch.diagonal(x, dim1=dim1, dim2=dim2).sum(-1)", "def trace(X):\n return extract_diag(X).sum()", "def ln_sum_i_neq_j(x):\n iw_size = x.size(0)\n batch_size = x.size(1)\n\n # TODO: Would torch.e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shifts `pvals` by the largest value in the last dimension before the exp is calculated to prevent overflow (batchwise if necessary). Can be used if probabilities are normalized again later.
def shiftedexp(pvals: np.ndarray) -> np.ndarray: if pvals.shape[-1] == 0: return np.empty_like(pvals) return np.exp(pvals - np.amax(pvals, axis=-1)[..., None])
[ "def benjamini_hochberg_step_down(pvals):\r\n tmp = fdr_correction(pvals)\r\n corrected_vals = empty(len(pvals))\r\n max_pval = 1.\r\n for i in argsort(pvals)[::-1]:\r\n if tmp[i] < max_pval:\r\n corrected_vals[i] = tmp[i]\r\n max_pval = tmp[i]\r\n else:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample from list of probabilities `pvals` with replacement. The probabilities don't need to be normalized.
def sample_probabilities(pvals: np.ndarray) -> Callable[[], int]: return Sampler(np.cumsum(pvals))
[ "def _correct_p_values(self, p_vals):\r\n num_tests = len([p_val for p_val in p_vals if p_val is not None])\r\n corrected_p_vals = []\r\n for p_val in p_vals:\r\n if p_val is not None:\r\n corrected_p_vals.append(min(p_val * num_tests, 1))\r\n else:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample from the categorical distribution using `pvals`.
def categorical(pvals: np.ndarray) -> int: return sample_probabilities(pvals)() # faster than: np.argmax(np.random.multinomial(1, normalize(pvals)))
[ "def sample_probabilities(pvals: np.ndarray) -> Callable[[], int]:\n\n return Sampler(np.cumsum(pvals))", "def sample(self, params):\n probabilities = utils.normalize(self.counts[tuple(params)])\n sampler = self.rng.categorical_sampler(self.support(params), probabilities)\n return sampler()", "def s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a population (list of observations) to a CDF.
def population2cdf(population: np.ndarray) -> np.ndarray: population = np.sort(population) return np.searchsorted(population, population, side="right") / len(population)
[ "def cdf(self,x):\n coordinate = distribution1D.vectord_cxx(len(x))\n for i in range(len(x)):\n coordinate[i] = x[i]\n cdfValue = self._distribution.cdf(coordinate)\n return cdfValue", "def convert_to_cudf(cp_arrays):\n cupy_vertices, cupy_hubs, cupy_authorities = cp_arrays\n df = cudf.Data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a discrete PDF into a discrete CDF.
def pmf2cdf(pdf: np.ndarray) -> np.ndarray: cdf = np.cumsum(pdf) return cdf / cdf[-1]
[ "def cdf_to_pdf(cdf):\n pdf = deepcopy(cdf)\n pdf[1:] -= pdf[:-1].copy()\n return pdf", "def get_cdf(pdf):\n pdf_norm = normalize(pdf) # Calculate the normalized pdf\n lower_bound = np.min(pdf.x)\n upper_bound = np.max(pdf.x)\n\n def cdf_number(x):\n \"\"\"Numerical cdf.\n\n :p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate stochastic matrix `pm` to the power of infinity, by finding the eigenvector which corresponds to the eigenvalue 1.
def inf_matrix_power(pm: np.ndarray, dtype=np.float64) -> np.ndarray: w, v = np.linalg.eig( pm ) # scipy.linalg.eig would probably by faster as it can return the left and right eigen vectors if not np.isclose(w[0], 1.0): raise ValueError("The first eigenvalue is not none. Is this a right stochastic matrix?") vi = np.linalg.inv(v) d = np.zeros(pm.shape[0], dtype=dtype) d[0] = 1.0 return np.matmul(v, np.matmul(np.diag(d), vi))
[ "def calculate_E0(self) -> float:\n noisy = self.kernel_eigenvectors_[-1].copy()\n np.random.shuffle(noisy)\n\n kernel_eigenvectors = self.kernel_eigenvectors_[:-1]\n kernel_eigenvectors.append(noisy)\n\n eigenvectors_matrix = scipy.sparse.csr_matrix(\n np.column_stack(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace colored pixels with a `neutral_color`. The `ratio` defines the 'colorfulness' above which level the pixel should be replace. I.e. if the `ratio` is 1 nothing will be replaced, if `ratio` is 0 only strict greys are kept unmodified.
def remove_color(img: np.ndarray, ratio: float, neutral_color: Tuple[int, int, int] = RGB_WHITE) -> None: channels = img.shape[-1] assert channels == 3, "Not a 3 channel color image" norm = np.std(np.array(RGB_YELLOW)) # this is the same for all pure colors sd = np.std(img, axis=-1) img[sd > ratio * norm] = neutral_color
[ "def set_neutral_config(self, neutral_config_dict):\n self._neutral_config = neutral_config_dict", "def set_neutral(self):\n print(\"Moving to neutral pose...\")\n self._right_arm.move_to_neutral(speed = 0.15)", "def ratio_to_rgb(ratio):\n b = 0\n if round(ratio, 1) == 0.5:\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
np.broadcast_shapes requires `numpy==1.20.0`, which is not available for `python < 3.7`.
def broadcast_shapes(*shapes: Tuple[int, ...]) -> Tuple[int, ...]: arrays = [np.empty(shape) for shape in shapes] return np.broadcast(*arrays).shape
[ "def _broadcastShape(shape1, shape2):\n\n shape1, shape2, broadcastshape = _broadcastShapes(shape1, shape2)\n return broadcastshape", "def broadcast_shape(*shapes, **kwargs):\n strict = kwargs.pop(\"strict\", False)\n reversed_shape = []\n for shape in shapes:\n for i, size in enumerate(reve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Batched center of mass calculation of 2d arrays
def center_of_mass_2d(arr: np.ndarray, dtype=np.float32) -> np.ndarray: total = np.sum(arr, axis=(-1, -2)) grids = np.ogrid[[slice(0, i) for i in arr.shape[-2:]]] with np.errstate(invalid="ignore"): results = np.array([np.sum(arr * grid.astype(dtype), axis=(-1, -2)) / total for grid in grids], dtype=dtype) results = np.moveaxis(results, 0, -1) return results
[ "def centerOfMass(data):\r\n dd = []\r\n for d in data:\r\n dd.append(d.coordinate)\r\n\r\n data = dd\r\n data = np.array(data)\r\n n = len(data)\r\n x = sum(data[:,0])\r\n y = sum(data[:,1])\r\n z = sum(data[:,2])\r\n x/=n\r\n y/=n\r\n z/=n\r\n return x,y,z,n", "def cen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
validate_target verifies that target is a valid MAC address, IP address or hostname
def validate_target(target, arp_table): try: mac = mac_address(target) return mac except TypeError: pass try: ip = ip_address(target) if ip in arp_table.keys(): return arp_table[ip].mac except TypeError: pass if target in arp_table: return arp_table[target].mac else: raise TypeError('{} is not a valid target'.format(target))
[ "def validate_target(target: str) -> bool:\n try:\n gethostbyname(target)\n except (gaierror, UnicodeError):\n return False\n return True", "def _is_valid_target(self, target, target_name, target_ports, is_pair):\n if is_pair:\n return (target[:utils.PORT_ID_LENGTH] in target_port...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[authorize and initialize spotify client]
def init_auth_client(self): with open("config.yml", 'r') as ymlfile: cfg = yaml.load(ymlfile) token = util.prompt_for_user_token( cfg['username'], scope=cfg['scope'], client_id=cfg['spotipy_client_id'], client_secret=cfg['spotipy_client_secret'], redirect_uri=cfg['spotipy_redirect_uri']) sp = spotipy.Spotify(auth=token) return sp, cfg['username']
[ "def init_client(self):\n \n creds = sc.load_creds()\n client_id = creds['client_id']\n client_secret = creds['client_secret']\n client_credentials_manager = SpotifyClientCredentials(client_id=client_id,\n client_secret=client_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[creates a new playlist with given name, desc with given limts]
def create_new_playlist(self, name, desc=''): pl_names, _, _ = self.list_playlists() if name in pl_names: self.logger.debug( 'Playlist Name Already Exists, please use another name') else: pl = self.sp.user_playlist_create( self.user, name, public=False, description=desc) self.sp.user_playlist_change_details( self.user, pl['id'], collaborative=True)
[ "def create_playlist(self, playlist_name):\n print(\"create_playlist needs implementation\")", "def create_spot_playlist(name, description=\"\"):\n \n auth_manager = create_spot_oauth()\n\n sp = Spotify(auth_manager=auth_manager)\n\n return sp.user_playlist_create(user=sp.current_user()[\"id\"]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculates TS Percentage metric for a player
def set_ts_percentage(self): bx = self.get_standard_stats() ptos = float(bx["t2p_conv"]*2 + bx["t3p_conv"]*3 + bx["tl_conv"]) tcInt = float(bx["t2p_int"] + bx["t3p_int"]) tsAttempts = float(tcInt + (0.44*float(bx["tl_int"]))) result = 0.00 if tsAttempts > 0.00: result = (ptos/(2*tsAttempts))*100 self.ts_percentage = "%.2f" % round(result, 2)
[ "def get_percent(self):\n if not (self.votes and self.score):\n return 0\n return 100 * (self.get_rating() / self.field.range)", "def percent_score(self):\n return self.score * 100", "def get_percent(self, n):\n controlled = 0.00\n for i in range(len(self.tile_conte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculate USG% for each player from each team
def set_usg_percentage(self): bx = self.get_standard_stats() team = self.get_team_stats() tcInt = bx["t2p_int"] + bx["t3p_int"] a = tcInt + (Decimal('0.44')*bx["tl_int"]) + bx["turnovers"] b = team["minutes"]/5 c = (team["t2p_int"] + team["t3p_int"]) + (Decimal('0.44')*team["tl_int"]) + team["turnovers"] result = 0.00 if bx["minutes"] > 0: result = ((Decimal(a)*Decimal(b))/(bx["minutes"]*c))*100 self.usg_percentage = "%.2f" % round(result, 2)
[ "def opp_strength(team):\n opponent_count = 0\n opponent_wins = 0\n\n gov_rounds = team.gov_team\n opp_rounds = team.opp_team\n\n for round_obj in gov_rounds.all():\n opponent_wins += tot_wins(round_obj.opp_team)\n opponent_count += 1\n for round_obj in opp_rounds.all():\n opp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculate Total Rebound Percentage
def set_total_reb_percentage(self): bx = self.get_standard_stats() team = self.get_team_stats() opp_team = self.get_opp_team_stats() player_rebounds = bx["reb_def"] + bx["reb_of"] team_rebounds = team["reb_def"] + team["reb_of"] opp_team_rebounds = opp_team["reb_def"] + opp_team["reb_of"] result = 0.00 try: if bx["minutes"] > 0 and bx["minutes"] > 0: result = ((player_rebounds * (team["minutes"]/5)) / (bx["minutes"] * (team_rebounds + opp_team_rebounds)))*100 except ZeroDivisionError: print(BCOLORS.FAIL + "Error: División por cero" + BCOLORS.ENDC) except InvalidOperation: print(BCOLORS.FAIL + "Error: Invalid Operation" + BCOLORS.ENDC) self.total_reb_percentage = "%.2f" % round(result, 2)
[ "def calc_percentages(self):\n self.beyond_lower.calc_percentage(self.total_entries)\n for b in self.buckets:\n b.calc_percentage(self.total_entries)\n self.beyond_upper.calc_percentage(self.total_entries)", "def total_rebounds_percentage(self, total_rebounds_percentage):\n\n self._total_rebo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculate Total Rebound Defensive Percentage
def set_total_reb_def_percentage(self): bx = self.get_standard_stats() team = self.get_team_stats() opp_team = self.get_opp_team_stats() result = 0.00 try: if bx["minutes"] > 0 and bx["minutes"] > 0: result = ((bx["reb_def"] * (team["minutes"]/5)) / (bx["minutes"] * (team["reb_def"] + opp_team["reb_of"])))*100 except ZeroDivisionError: print(BCOLORS.FAIL + "Error: División por cero" + BCOLORS.ENDC) except InvalidOperation: print(BCOLORS.FAIL + "Error: Invalid Operation" + BCOLORS.ENDC) self.total_reb_def_percentage = "%.2f" % round(result, 2)
[ "def get_real_percent(self):\n if not (self.votes and self.score):\n return 0\n return 100 * (self.get_real_rating() / self.field.range)", "def set_total_reb_percentage(self):\n bx = self.get_standard_stats()\n team = self.get_team_stats()\n opp_team = self.get_opp_te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculate Steals Percentage of a player
def set_steals_percentage(self): bx = self.get_standard_stats() team = self.get_team_stats() opp_team = self.get_opp_team_stats() poss = self.get_team_possessions() result = 0.00 if bx["minutes"] > 0: result = ((bx["steals"] * (team["minutes"]/Decimal('5'))) / Decimal(float(bx["minutes"]) * poss)) * 100 self.steals_percentage = "%.2f" % round(result, 2)
[ "def get_percent(self, n):\n controlled = 0.00\n for i in range(len(self.tile_contents)):\n if(self.tile_contents[i].player_number == n):\n controlled += 1.00\n \n return float(controlled / self.paint_blocks)", "def win_percentage(self, return_on_div_by_zero='...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculate Assists Percentage of a player
def set_assists_percentage(self): bx = self.get_standard_stats() team = self.get_team_stats() team_tc_conv = team["t2p_conv"] + team["t3p_conv"] player_tc_conv = bx["t2p_conv"] + bx["t3p_conv"] result = 0.00 try: if bx["minutes"] > 0: result = (bx["assists"] / (((bx["minutes"] / (team["minutes"] / 5)) * team_tc_conv) - player_tc_conv))*100 result = result if result <= 100 and result >= 0 else 0 except ZeroDivisionError: print(BCOLORS.WARNING + "Error: División por cero" + BCOLORS.ENDC) except InvalidOperation: print(BCOLORS.WARNING + "Error: Invalid Operation" + BCOLORS.ENDC) self.assists_percentage = "%.2f" % round(result, 2)
[ "def get_percent(self):\n if not (self.votes and self.score):\n return 0\n return 100 * (self.get_rating() / self.field.range)", "def percent_score(self):\n return self.score * 100", "def calc_percentage(self, total_entries):\n self.percentage = self.count/total_entries * 100"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculate Ratio Assists Per Turnover of a player
def set_assists_per_turnover(self): bx = self.get_standard_stats() ratio = bx["assists"] if bx["turnovers"] > 0: ratio = bx["assists"] / bx["turnovers"] self.assists_per_turnover = "%.2f" % round(ratio, 2)
[ "def calc_ratio_of_moves(game, player):\n player_factor = 1\n opp_factor = 1\n player_moves = game.get_legal_moves(player)\n opp_moves = game.get_legal_moves(game.get_opponent(player))\n if not opp_moves:\n return float(\"inf\")\n elif not player_moves:\n return float(\"-inf\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculate Assists Ratio of a player
def set_assists_ratio(self): bx = self.get_standard_stats() tcInt = float(bx["t2p_int"] + bx["t3p_int"]) denominador = tcInt + (0.44 * float(bx["tl_int"])) + float(bx["assists"]) +float(bx["turnovers"]) numerador = float(bx["assists"]) result = 0.00 if denominador > 0: result = (numerador / denominador) * 100 self.assists_ratio = "%.2f" % round(result, 2)
[ "def calc_ratio_of_moves(game, player):\n player_factor = 1\n opp_factor = 1\n player_moves = game.get_legal_moves(player)\n opp_moves = game.get_legal_moves(game.get_opponent(player))\n if not opp_moves:\n return float(\"inf\")\n elif not player_moves:\n return float(\"-inf\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculate Defensive Ratio of a player. The total points received in 100 possessions
def set_defensive_ratio(self): bx = self.get_standard_stats() team = self.get_team_stats() opp_team = self.get_opp_team_stats() if bx["minutes"] > 0: opp_fga = opp_team["t2p_int"] + opp_team["t3p_int"] opp_fgm = opp_team["t2p_conv"] + opp_team["t3p_conv"] try: dor = Decimal(opp_team["reb_of"] / (opp_team["reb_of"] + team["reb_def"])) except ZeroDivisionError: print(BCOLORS.FAIL + "Error: División por cero" + BCOLORS.ENDC) dor = 0 except InvalidOperation: print(BCOLORS.FAIL + "Error: Invalid Operation" + BCOLORS.ENDC) dor = 0 try: dfg = Decimal(opp_fgm / opp_fga) except ZeroDivisionError: print(BCOLORS.WARNING + "Error: División por cero" + BCOLORS.ENDC) dfg = 0 try: fmwt = Decimal((dfg * (1 - dor)) / (dfg * (1 - dor) + (1 - dfg) * dor)) except: fmwt = 0 stops1 = bx["steals"] + bx["block_shots"] * fmwt * (1 - Decimal('1.07') * dor) + bx["reb_def"] * (1 - fmwt) try: stops2 = (Decimal((opp_fga - opp_fgm - team["block_shots"]) / team["minutes"]) * fmwt * (1 - Decimal('1.07') * dor) + Decimal((opp_team["turnovers"] - team["steals"]) / team["minutes"])) * bx["minutes"] + Decimal(bx["fouls_cm"] / team["fouls_cm"]) * Decimal('0.4') * opp_team["tl_int"] * (1 - Decimal(opp_team["tl_conv"] / opp_team["tl_int"]))**2 except ZeroDivisionError: print(BCOLORS.WARNING + "Error: División por cero" + BCOLORS.ENDC) stops2 = 0 except InvalidOperation: print(BCOLORS.WARNING + "Error: Invalid Operation" + BCOLORS.ENDC) stops2 = 0 stops = stops1 + stops2 poss = self.get_team_possessions() if bx["minutes"] > 0: stop_percentage = (float(stops) * float(opp_team["minutes"])) / (float(poss) * float(bx["minutes"])) else: stop_percentage = 0.00 opp_points = opp_team["t2p_conv"] * 2 + opp_team["t3p_conv"] * 3 + opp_team["tl_conv"] team_defensive_rating = 100 * (float(opp_points) / poss) try: d_pts_per_scposs = float(opp_points) / (float(opp_fgm) + (1 - (1 - (float(opp_team["tl_conv"]) / float(opp_team["tl_int"])))**2) * float(opp_team["tl_int"])*0.4) result = Decimal(team_defensive_rating) + Decimal('0.2') * (100 * Decimal(d_pts_per_scposs) * (1 - Decimal(stop_percentage)) - Decimal(team_defensive_rating)) except ZeroDivisionError: print(BCOLORS.WARNING + "Error: División por cero" + BCOLORS.ENDC) d_pts_per_scposs = 0 result = 0.00 # print("dor: " + str(dor)) # print("dfg: " + str(dfg)) # print("fmwt: " + str(fmwt)) # print("stops1: " + str(stops1)) # print("stops2: " + str(stops2)) # print("stops: " + str(stops)) # print("poss: " + str(poss)) # print("stop_percentage: " + str(stop_percentage)) # print("opp_points: " + str(opp_points)) # print("team_defensive_rating: " + str(team_defensive_rating)) # print("d_pts_per_scposs: " + str(d_pts_per_scposs)) # print("drtg: " + str(result) + "\n") else: result = 0.00 self.drtg = "%.2f" % round(result, 2)
[ "def calc_ratio_of_moves(game, player):\n player_factor = 1\n opp_factor = 1\n player_moves = game.get_legal_moves(player)\n opp_moves = game.get_legal_moves(game.get_opponent(player))\n if not opp_moves:\n return float(\"inf\")\n elif not player_moves:\n return float(\"-inf\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method which calculate Offensive Ratio of a player. The total points scored in 100 possessions
def set_offensive_ratio(self): bx = self.get_standard_stats() team = self.get_team_stats() opp_team = self.get_opp_team_stats() if bx["minutes"] > 0 and (bx["t2p_int"] + bx["t3p_int"]) > 0: fgm = bx["t2p_conv"] + bx["t3p_conv"] fga = bx["t2p_int"] + bx["t3p_int"] team_fgm = team["t2p_conv"] + team["t3p_conv"] team_fga = team["t2p_int"] + team["t3p_int"] team_points = team["t2p_conv"]*2 + team["t3p_conv"]*3 + team["tl_conv"] points = bx["t2p_conv"]*2 + bx["t3p_conv"]*3 + bx["tl_conv"] try: qAST = (Decimal(bx["minutes"] / (team["minutes"] / 5)) * (Decimal('1.14') * Decimal((team["assists"] - bx["assists"]) / team_fgm))) + \ Decimal((((team["assists"] / team["minutes"]) * bx["minutes"] * 5 - bx["assists"]) / ((team_fgm / team["minutes"]) * bx["minutes"] * 5 - fgm)) * (1 - (bx["minutes"] / (team["minutes"] / 5)))) except ZeroDivisionError: print(BCOLORS.WARNING + "Error: División por cero" + BCOLORS.ENDC) qAST = 1 except InvalidOperation: print(BCOLORS.WARNING + "Error: Invalid Operation" + BCOLORS.ENDC) qAST = 1 fg_part = fgm * (1 - Decimal('0.5') * Decimal((points - bx["tl_conv"]) / (2 * fga)) * qAST) try: ast_part = Decimal('0.5') * Decimal(((team_points - team["tl_conv"]) - (points - bx["tl_conv"])) / (2*(team_fga - fga))) * bx["assists"] except ZeroDivisionError: print(BCOLORS.WARNING + "Error: División por cero" + BCOLORS.ENDC) ast_part = 0 if bx["tl_int"] > 0: ft_part = Decimal(1 - (1 - (bx["tl_conv"] / bx["tl_int"]))**2) * Decimal('0.4') * bx["tl_int"] else: ft_part = 0 team_scoring_poss = Decimal(team_fgm + Decimal(1 - (1 - (team["tl_conv"] / team["tl_int"]))**2) * team["tl_int"] * Decimal('0.4')) try: team_orb_percentage = Decimal(team["reb_of"] / (team["reb_of"] + ((opp_team["reb_def"] + opp_team["reb_of"]) - opp_team["reb_of"]))) except ZeroDivisionError: print(BCOLORS.FAIL + "Error: División por cero" + BCOLORS.ENDC) team_orb_percentage = 0 except InvalidOperation: print(BCOLORS.FAIL + "Error: Invalid Operation" + BCOLORS.ENDC) team_orb_percentage = 0 team_play_percentage = Decimal(team_scoring_poss / (team_fga + team["tl_int"] * Decimal('0.4') + team["turnovers"])) try: team_orb_weight = ((1 - team_orb_percentage) * team_play_percentage) / ((1 - team_orb_percentage) * team_play_percentage + team_orb_percentage * (1 - team_play_percentage)) except InvalidOperation: print(BCOLORS.FAIL + "Error: Invalid Operation" + BCOLORS.ENDC) team_orb_weight = 0 orb_part = bx["reb_of"] * team_orb_weight * team_play_percentage fg_x_poss = (fga - fgm) * (1 - Decimal('1.07') * team_orb_percentage) if bx["tl_conv"] > 0: ft_x_poss = Decimal((1 - (bx["tl_conv"] / bx["tl_int"]))**2) * Decimal('0.4') * bx["tl_int"] else: ft_x_poss = Decimal(1 - (bx["tl_conv"] / 1)**2) * Decimal('0.4') * bx["tl_int"] try: sc_poss = (fg_part + ast_part + ft_part) * (1 - (team["reb_of"] / team_scoring_poss) * team_orb_weight * team_play_percentage) + orb_part except InvalidOperation: print(BCOLORS.FAIL + "Error: Invalid Operation" + BCOLORS.ENDC) sc_poss =0 tot_poss = sc_poss + fg_x_poss + ft_x_poss + bx["turnovers"] pprod_fg_part = 2 * (fgm + Decimal('0.5') * bx["t3p_conv"]) * (1 - Decimal('0.5') * Decimal((points - bx["tl_conv"]) / (2 * fga)) * qAST) try: pprod_ast_part = 2 * ((team_fgm - fgm + Decimal('0.5') * (team["t3p_conv"] - bx["t3p_conv"])) / (team_fgm - fgm)) * Decimal('0.5') * Decimal(((team_points - team["tl_conv"]) - (points - bx["tl_conv"])) / (2 * (team_fga - fga))) * bx["assists"] except: pprod_ast_part = 0 pprod_orb_part = bx["reb_of"] * team_orb_weight * team_play_percentage * (team_points / (team_fgm + Decimal(1 - (team["tl_conv"] / team["tl_int"])**2) * Decimal('0.4') * team["tl_int"])) try: pprod = (pprod_fg_part + pprod_ast_part + bx["tl_conv"]) * (1 - (team["reb_of"] / team_scoring_poss) * team_orb_weight * team_play_percentage) + pprod_orb_part except InvalidOperation: print(BCOLORS.FAIL + "Error: Invalid Operation" + BCOLORS.ENDC) pprod = 0 try: result = 100 * (pprod / tot_poss) except InvalidOperation: print(BCOLORS.FAIL + "Error: Invalid Operation" + BCOLORS.ENDC) result = 0 # print("fgm: " + str(fgm)) # print("fga: " + str(fga)) # print("team_fgm: " + str(team_fgm)) # print("team_fga: " + str(team_fga)) # print("team_points: " + str(team_points)) # print("points: " + str(points)) # print("qAST: " + str(qAST)) # print("fg_part: " + str(fg_part)) # print("ast_part: " + str(ast_part)) # print("ft_part: " + str(ft_part)) # print("team_scoring_poss: " + str(team_scoring_poss)) # print("team_orb_percentage: " + str(team_orb_percentage)) # print("team_play_percentage: " + str(team_play_percentage)) # print("team_orb_weight: " + str(team_orb_weight)) # print("orb_part: " + str(orb_part)) # print("fg_x_poss: " + str(fg_x_poss)) # print("ft_x_poss: " + str(ft_x_poss)) # print("sc_poss: " + str(sc_poss)) # print("tot_poss: " + str(tot_poss)) # print("pprod_fg_part: " + str(pprod_fg_part)) # print("pprod_ast_part: " + str(pprod_ast_part)) # print("pprod_orb_part: " + str(pprod_orb_part)) # print("pprod: " + str(pprod)) # print("result: " + str(result) + "\n") else: result = 0.00 self.ortg = "%.2f" % round(result, 2) if Decimal(self.ortg) < 0 or Decimal(self.ortg) >= 1000: """For one game, maybe we've got a negative result or one so big, so, for just only a game, we get the ORTG using team's formula""" print(BCOLORS.OKBLUE + "ORTG negativo o superior a 1000 para jugadora => recalculamos a través de la fórmula de equipo" + BCOLORS.ENDC) bx = self.get_standard_stats() result = round((bx["t2p_conv"]*2 + bx["t3p_conv"]*3 + bx["tl_conv"])/self.get_team_possessions(), 2) self.ortg = "%.2f" % result
[ "def calc_ratio_of_moves(game, player):\n player_factor = 1\n opp_factor = 1\n player_moves = game.get_legal_moves(player)\n opp_moves = game.get_legal_moves(game.get_opponent(player))\n if not opp_moves:\n return float(\"inf\")\n elif not player_moves:\n return float(\"-inf\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
auth_data will be used used as request_data in strategy
def set_input_data(self, request, auth_data): request.auth_data = auth_data
[ "def get_oauth_data():", "def authenticate(self, request):\n auth_data = super().authenticate(request)\n if not auth_data:\n return auth_data\n\n user, auth = auth_data\n\n if amr_claim := auth.data.get(\"amr\"):\n user.token_amr_claim = amr_claim\n\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that only 'admin' can add a product
def test_only_admin_can_create_product(self): resp = self.admin_create_user() reply = self.attendant_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Unauthorized Access!') self.assertEqual(resp.status_code, 401)
[ "def test_non_admin_cannot_delete_product(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='denims',\n stock=20,\n price=150\n )\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that 'admin' can add a product
def test_admin_create_product(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201)
[ "def test_only_admin_can_create_product(self):\n resp = self.admin_create_user()\n reply = self.attendant_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='denims',\n stock=20,\n price=150\n )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test admin cannot create a product with a blacklisted token
def test_cannot_create_product_with_blacklisted_token(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] resp = self.client.delete( '/api/v1/logout', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'You are successfully logged out!') self.assertEqual(resp.status_code, 200) product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Invalid Authentication, Please Login!') self.assertEqual(resp.status_code, 401)
[ "def test_cannot_view_a_product_with_blacklisted_token(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='denims',\n stock=20,\n price=150\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }